diff --git "a/2343.jsonl" "b/2343.jsonl" new file mode 100644--- /dev/null +++ "b/2343.jsonl" @@ -0,0 +1,768 @@ +{"seq_id":"359882119","text":"#!/usr/bin/python3\n# London Academy of IT\n# Python Exercise 23\n'''\nWrite a program that gives information about James Bond Films. The program gives 4 chances to name an actor who has played\nBond and then say whether you are right or not. They should use the text below in the messages output (up to the names of the actors and so\nfilms given). Finally they should print how well you did giving a score out of 4.\n'''\n\nmovies = {\"Sean Connery\" : \"From Russia with Love\",\n \"Roger Moore\": \"Live and let Die\",\n \"Pierce Brosnan\": \"Die Another Day\",\n \"Daniel Craig\": \"Skyfall\"}\n\nprint(\"Try and name 4 actors who have played James Bond.\")\ni = 1\nb = 0\nwhile i <= 4:\n a = input(\"Attemp {} - Name an actor: \".format(i))\n if a in movies:\n print(\"Well Done! {}, was in {}\".format(a, movies.get(a)))\n b += 1\n else:\n print(\"Sorry {}, hasn't played any James Bond movies\".format(a))\n i += 1\nprint(\"You got {} out of 4\".format(b))\n","sub_path":"londonacademy_beginner/londonitacademy_exercise/23.0-Exercise.py","file_name":"23.0-Exercise.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"412478812","text":"\"\"\"\nEvaluator settings.\n\"\"\"\n\nimport os\n\nimport tensorflow as tf\nfrom obspy.core.utcdatetime import UTCDateTime\nfrom datetime import datetime\n\nfrom seisnn.core import Instance\nfrom seisnn.model.attention import TransformerBlockE, TransformerBlockD, \\\n MultiHeadSelfAttention, ResBlock\nfrom seisnn.plot import plot_error_distribution\nimport seisnn.example_proto\nimport seisnn.io\nimport seisnn.sql\nimport seisnn.utils\n\n\nclass BaseEvaluator:\n @staticmethod\n def get_dataset_length(database=None):\n count = None\n try:\n db = seisnn.sql.Client(database)\n count = len(db.get_waveform().all())\n except Exception as error:\n print(f'{type(error).__name__}: {error}')\n\n return count\n\n @staticmethod\n def get_model_dir(model_instance):\n config = seisnn.utils.Config()\n save_model_path = os.path.join(config.models, model_instance)\n return save_model_path\n\n @staticmethod\n def get_eval_dir(dir_name):\n config = seisnn.utils.Config()\n eval_path = os.path.join(config.eval, dir_name.split('.')[0])\n seisnn.utils.make_dirs(eval_path)\n\n return eval_path\n\n\nclass GeneratorEvaluator(BaseEvaluator):\n \"\"\"\n Trainer class.\n \"\"\"\n\n def __init__(self,\n database=None,\n model_name=None):\n \"\"\"\n Initialize the evaluator.\n\n :param database: SQL database.\n :param model_name: Saved model.\n \"\"\"\n self.database = database\n self.model_name = model_name\n self.model = None\n\n def eval(self, tfr_list, batch_size=100):\n \"\"\"\n Main eval loop.\n\n :param tfr_list: List of .tfrecord.\n :param str name: Output name.\n \"\"\"\n model_path = self.get_model_dir(self.model_name)\n eval_path = self.get_eval_dir(self.model_name)\n\n self.model = tf.keras.models.load_model(\n model_path,\n custom_objects={\n 'TransformerBlockE': TransformerBlockE,\n 'TransformerBlockD': TransformerBlockD,\n 'MultiHeadSelfAttention': MultiHeadSelfAttention,\n 'ResBlock': ResBlock\n })\n\n data_len = self.get_dataset_length(self.database)\n progbar = tf.keras.utils.Progbar(data_len)\n dataset = seisnn.io.read_dataset(tfr_list)\n n = 0\n for val in dataset.prefetch(100).batch(batch_size):\n progbar.add(batch_size)\n\n val['predict'] = self.model.predict(val['trace'])\n\n iterator = seisnn.example_proto.batch_iterator(val)\n for i in range(len(val['predict'])):\n title = f\"eval_{n:0>5}\"\n\n instance = Instance(next(iterator))\n instance.to_tfrecord(\n os.path.join(eval_path, title + '.tfrecord'))\n n += 1\n\n val['id'] = tf.convert_to_tensor(\n title.encode('utf-8'), dtype=tf.string)[tf.newaxis]\n\n example = next(seisnn.example_proto.batch_iterator(val))\n instance = Instance(example)\n instance.to_tfrecord(os.path.join(eval_path, title + '.tfrecord'))\n n += 1\n\n def score(self, delta=0.1, error_distribution=True):\n db = seisnn.sql.Client(self.database)\n for phase in ['P', 'S']:\n tp = 0\n error = []\n predict_pick = db.get_picks(phase=phase, tag='predict')\n label_pick = db.get_picks(phase=phase, tag='manual')\n total_predict = len(predict_pick.all())\n total_label = len(label_pick.all())\n print(f'{phase}_total_predict: {total_predict} '\n f'{phase}_total_label: {total_label}')\n\n for pick in predict_pick:\n from_time, to_time = get_from_time_to_time(pick, delta)\n label = db.get_picks(\n from_time=str(from_time),\n to_time=str(to_time),\n phase=phase,\n station=pick.station,\n tag='manual'\n )\n if label.all():\n tp = tp + 1\n if error_distribution:\n error.append(UTCDateTime(label[0].time) - UTCDateTime(\n pick.time))\n plot_error_distribution(error)\n print(\n f'{phase}: tp = {tp},fp = {total_predict - tp},fn = {total_label - tp}')\n precision, recall, f1 = seisnn.qc.precision_recall_f1_score(\n true_positive=tp, val_count=total_label,\n pred_count=total_predict)\n print(\n f'{phase}: precision = {precision},recall = {recall},f1 = {f1}')\n\n\ndef get_from_time_to_time(pick, delta=0.1):\n from_time = UTCDateTime(pick.time) - delta\n from_time = datetime.strptime(str(from_time), '%Y-%m-%dT%H:%M:%S.%fZ')\n to_time = UTCDateTime(pick.time) + delta\n to_time = datetime.strptime(str(to_time), '%Y-%m-%dT%H:%M:%S.%fZ')\n return from_time, to_time\n","sub_path":"seisnn/model/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"122820411","text":"def foo11():\n import sys\n sf = sys.argv[1]\n df = sys.argv[2]\n sf_obj = open(sf,'rb')\n df_obj = open(df,'wb')\n while True:\n data = sf_obj.read(4096)\n df_obj.write(data)\n if not data:\n break\n df_obj.close()\n sf_obj.close()\n\nfoo11()","sub_path":"STEP05/project/python/day03/cp4.py","file_name":"cp4.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13410759","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# JewelCraft jewelry design toolkit for Blender.\n# Copyright (C) 2015-2019 Mikhail Rachinskiy\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\nimport os\n\nimport bpy.utils.previews\nfrom bpy.app.translations import pgettext_iface as _\n\nfrom .. import var\nfrom . import asset\n\n\n_cache = {}\n\n\ndef _iface_lang(context):\n view = context.preferences.view\n\n if view.use_international_fonts and view.use_translate_interface:\n return view.language\n\n return \"DEFAULT\"\n\n\ndef cuts(self, context):\n lang = _iface_lang(context)\n\n if _cache.get(\"cuts__lang\") == lang:\n return _cache[\"cuts__list\"]\n\n pcoll = var.preview_collections.get(\"cuts\")\n\n if not pcoll:\n pcoll = bpy.utils.previews.new()\n\n for entry in os.scandir(var.GEM_ASSET_DIR):\n if entry.name.endswith(\".png\"):\n name = os.path.splitext(entry.name)[0]\n pcoll.load(name, entry.path, \"IMAGE\")\n\n var.preview_collections[\"cuts\"] = pcoll\n\n list_ = (\n (\"ROUND\", _(\"Round\", \"JewelCraft\"), \"\", pcoll[\"round\"].icon_id, 0),\n (\"OVAL\", _(\"Oval\"), \"\", pcoll[\"oval\"].icon_id, 1),\n (\"CUSHION\", _(\"Cushion\"), \"\", pcoll[\"cushion\"].icon_id, 2),\n (\"PEAR\", _(\"Pear\"), \"\", pcoll[\"pear\"].icon_id, 3),\n (\"MARQUISE\", _(\"Marquise\"), \"\", pcoll[\"marquise\"].icon_id, 4),\n (\"PRINCESS\", _(\"Princess\"), \"\", pcoll[\"princess\"].icon_id, 5),\n (\"BAGUETTE\", _(\"Baguette\"), \"\", pcoll[\"baguette\"].icon_id, 6),\n (\"SQUARE\", _(\"Square\"), \"\", pcoll[\"square\"].icon_id, 7),\n (\"EMERALD\", _(\"Emerald\"), \"\", pcoll[\"emerald\"].icon_id, 8),\n (\"ASSCHER\", _(\"Asscher\"), \"\", pcoll[\"asscher\"].icon_id, 9),\n (\"RADIANT\", _(\"Radiant\"), \"\", pcoll[\"radiant\"].icon_id, 10),\n (\"FLANDERS\", _(\"Flanders\"), \"\", pcoll[\"flanders\"].icon_id, 11),\n (\"OCTAGON\", _(\"Octagon\"), \"\", pcoll[\"octagon\"].icon_id, 12),\n (\"HEART\", _(\"Heart\"), \"\", pcoll[\"heart\"].icon_id, 13),\n (\"TRILLION\", _(\"Trillion\"), \"\", pcoll[\"trillion\"].icon_id, 14),\n (\"TRILLIANT\", _(\"Trilliant\"), \"\", pcoll[\"trilliant\"].icon_id, 15),\n (\"TRIANGLE\", _(\"Triangle\"), \"\", pcoll[\"triangle\"].icon_id, 16),\n )\n\n _cache[\"cuts__list\"] = list_\n _cache[\"cuts__lang\"] = lang\n\n return list_\n\n\ndef stones(self, context):\n lang = _iface_lang(context)\n\n if _cache.get(\"stones__lang\") == lang:\n return _cache[\"stones__list\"]\n\n list_ = [\n (\"DIAMOND\", _(\"Diamond\"), \"\", 0),\n (\"ALEXANDRITE\", _(\"Alexandrite\"), \"\", 1),\n (\"AMETHYST\", _(\"Amethyst\"), \"\", 2),\n (\"AQUAMARINE\", _(\"Aquamarine\"), \"\", 3),\n (\"CITRINE\", _(\"Citrine\"), \"\", 4),\n (\"CUBIC_ZIRCONIA\", _(\"Cubic Zirconia\"), \"\", 5),\n (\"EMERALD\", _(\"Emerald\"), \"\", 6),\n (\"GARNET\", _(\"Garnet\"), \"\", 7),\n (\"MORGANITE\", _(\"Morganite\"), \"\", 8),\n (\"QUARTZ\", _(\"Quartz\"), \"\", 9),\n (\"PERIDOT\", _(\"Peridot\"), \"\", 10),\n (\"RUBY\", _(\"Ruby\"), \"\", 11),\n (\"SAPPHIRE\", _(\"Sapphire\"), \"\", 12),\n (\"SPINEL\", _(\"Spinel\"), \"\", 13),\n (\"TANZANITE\", _(\"Tanzanite\"), \"\", 14),\n (\"TOPAZ\", _(\"Topaz\"), \"\", 15),\n (\"TOURMALINE\", _(\"Tourmaline\"), \"\", 16),\n (\"ZIRCON\", _(\"Zircon\"), \"\", 17),\n ]\n\n list_.sort(key=lambda x: x[1])\n\n _cache[\"stones__list\"] = list_\n _cache[\"stones__lang\"] = lang\n\n return list_\n\n\n# Weighting\n# ---------------------------\n\n\ndef weighting_set(self, context):\n\n if \"weighting_set__list\" in _cache:\n return _cache[\"weighting_set__list\"]\n\n prefs = bpy.context.scene.jewelcraft_preset\n list_ = []\n\n if not prefs.weighting_hide_default_sets:\n list_ += [\n (\n \"JCASSET_PRECIOUS\",\n \"[JewelCraft] Precious\",\n \"Commonly used precious alloys, physical properties taken directly from suppliers\"\n ),\n (\n \"JCASSET_PRECIOUS_RU\",\n \"[JewelCraft] Precious RU (ГОСТ 30649-99)\",\n \"Set of precious alloys according to Russian regulations\"\n ),\n (\n \"JCASSET_BASE\",\n \"[JewelCraft] Base\",\n \"Set of base metal alloys, physical properties taken directly from suppliers\"\n ),\n ]\n\n folder = asset.user_asset_library_folder_weighting()\n\n if os.path.exists(folder):\n for entry in os.scandir(folder):\n if entry.is_file() and entry.name.endswith(\".json\"):\n id_ = entry.name\n name_ = os.path.splitext(entry.name)[0] + \" \" # Add trailing space so UI translation won't apply\n list_.append((id_, name_, \"\"))\n\n if not list_:\n list_ = [(\"\", \"\", \"\")]\n\n _cache[\"weighting_set__list\"] = list_\n\n return list_\n\n\ndef weighting_set_refresh(self=None, context=None):\n if \"weighting_set__list\" in _cache:\n del _cache[\"weighting_set__list\"]\n\n\n# Assets\n# ---------------------------\n\n\ndef asset_folders(self, context):\n\n if \"asset_folders__list\" in _cache:\n return _cache[\"asset_folders__list\"]\n\n folder = asset.user_asset_library_folder_object()\n\n if not os.path.exists(folder):\n _cache[\"asset_folders__list\"] = [(\"\", \"\", \"\")]\n return [(\"\", \"\", \"\")]\n\n list_ = []\n\n for entry in os.scandir(folder):\n\n if entry.is_dir() and not entry.name.startswith(\".\"):\n id_ = entry.name\n name_ = entry.name + \" \" # Add trailing space so UI translation won't apply\n list_.append((id_, name_, \"\"))\n\n if not list_:\n list_ = [(\"\", \"\", \"\")]\n\n _cache[\"asset_folders__list\"] = list_\n\n return list_\n\n\ndef assets(self, context):\n category = context.scene.jewelcraft.asset_folder\n\n if \"assets__list\" in _cache and category == _cache.get(\"assets__category\"):\n return _cache[\"assets__list\"]\n\n _cache[\"assets__category\"] = category\n folder = os.path.join(asset.user_asset_library_folder_object(), category)\n\n if not os.path.exists(folder):\n _cache[\"assets__list\"] = [(\"\", \"\", \"\")]\n return [(\"\", \"\", \"\")]\n\n pcoll = var.preview_collections.get(\"assets\")\n\n if not pcoll:\n pcoll = bpy.utils.previews.new()\n\n list_ = []\n i = 0\n no_preview = var.preview_collections[\"icons\"][\"NO_PREVIEW\"].icon_id\n\n for entry in os.scandir(folder):\n\n if entry.is_file() and entry.name.endswith(\".blend\"):\n filename = os.path.splitext(entry.name)[0]\n id_ = filename\n name_ = filename + \" \" # Add trailing space so UI translation won't apply\n\n preview_id = category + filename\n preview_path = os.path.splitext(entry.path)[0] + \".png\"\n\n if os.path.exists(preview_path):\n if preview_id not in pcoll:\n pcoll.load(preview_id, preview_path, \"IMAGE\")\n preview = pcoll[preview_id].icon_id\n else:\n preview = no_preview\n\n list_.append((id_, name_, \"\", preview, i))\n i += 1\n\n var.preview_collections[\"assets\"] = pcoll\n\n if not pcoll:\n bpy.utils.previews.remove(pcoll)\n del var.preview_collections[\"assets\"]\n\n if not list_:\n list_ = [(\"\", \"\", \"\")]\n\n _cache[\"assets__list\"] = list_\n\n return list_\n\n\ndef asset_folder_list_refresh():\n if \"asset_folders__list\" in _cache:\n del _cache[\"asset_folders__list\"]\n\n\ndef asset_list_refresh(preview_id=False, hard=False):\n pcoll = var.preview_collections.get(\"assets\")\n\n if pcoll:\n\n if preview_id and preview_id in pcoll:\n del pcoll[preview_id]\n\n if not pcoll:\n bpy.utils.previews.remove(pcoll)\n del var.preview_collections[\"assets\"]\n\n elif hard:\n bpy.utils.previews.remove(pcoll)\n del var.preview_collections[\"assets\"]\n\n if \"assets__list\" in _cache:\n del _cache[\"assets__list\"]\n","sub_path":"All_In_One/addons/learnbgame/jewelcraft/lib/dynamic_list.py","file_name":"dynamic_list.py","file_ext":"py","file_size_in_byte":9031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"49393515","text":"import pandas as pd\nimport math\nfrom scipy.stats import norm\nimport numpy as np\n\ntabulato = pd.read_csv(\"../dati_pre_eventi/data/tabulato_semplificato.csv\")\neventi3 = pd.read_csv(\"creazione_eventi/data/events/events3.csv\")\nparts = {}\nfinestra = 43200\nminT = tabulato[\"timestamp\"].min()\nmaxT = tabulato[\"timestamp\"].max()\n\n\ndef group():\n global eventi3\n eventi3[\"chiamate\"] = eventi3[\"esito_positivo\"] + eventi3[\"esito_negativo\"]\n eventi3 = eventi3.drop(columns=[\"esito_positivo\", \"esito_negativo\"])\n events3_df_grouped = eventi3.groupby(by=[\"timestamp\", \"X\", \"Y\", \"A\", \"Z\"], as_index=False).sum()\n eventi3 = events3_df_grouped\n\n\ndef get_part_a(x, y):\n eventsxy = eventi3[eventi3[\"X\"] == x]\n eventsxy = eventsxy[eventsxy[\"Y\"] == y]\n intervals = []\n\n if len(eventsxy) != 0:\n start = 0\n start_finestra = True\n prec = 0\n end = 0\n for i, row in eventsxy.iterrows():\n if start_finestra:\n start = row[\"timestamp\"]\n start_finestra = False\n if row[\"timestamp\"] > start + finestra:\n intervals.append((start, prec + finestra))\n start = row[\"timestamp\"]\n if i == len(eventsxy) - 1:\n end = row[\"timestamp\"]\n prec = row[\"timestamp\"]\n\n intervals.append((start, end + finestra))\n return intervals\n\n\ndef merge_parts(part1, part2):\n part1 = [item for sublist in part1 for item in sublist]\n part2 = [item for sublist in part2 for item in sublist]\n timestamps = part1 + part2\n timestamps.sort()\n part = []\n if len(timestamps) != 0:\n start = 0\n start_finestra = True\n prec = 0\n end = 0\n for i, item in enumerate(timestamps):\n if start_finestra:\n start = item\n start_finestra = False\n if item > start + finestra:\n part.append((start, prec + finestra))\n start = item\n if i == len(timestamps) - 1:\n end = item\n prec = item\n part.append((start, end + finestra))\n return part\n\n\ndef get_part_b(partA1, partA2):\n partA = merge_parts(partA1, partA2)\n intervals = []\n if len(partA) != 0:\n start = minT\n for item in partA:\n end = item[0] - 1\n intervals.append((start, end))\n start = item[1] + 1\n intervals.append((start, maxT))\n return intervals\n else:\n return [(minT, maxT)]\n\n\ndef get_p0(x, y, a, z):\n partB = get_part_b(parts[(x, y)][\"A\"], parts[(y, a)][\"A\"])\n tabulato_az = tabulato[tabulato[\"mittente\"] == a]\n tabulato_az = tabulato_az[tabulato_az[\"destinatario\"] == z]\n tabulato_az.reset_index(inplace=True, drop=True)\n c = 0\n for _, row in tabulato_az.iterrows():\n timestamp = row[\"timestamp\"]\n for item in partB:\n if item[0] <= timestamp <= item[1]:\n c += 1\n break\n if timestamp < item[0]:\n break\n return c / len(tabulato)\n\n\ndef get_p_cappuccio(x, y, a, z):\n events_xya = eventi3[eventi3[\"X\"] == x]\n events_xya = events_xya[events_xya[\"Y\"] == y]\n events_xya = events_xya[events_xya[\"A\"] == a]\n events_xya.reset_index(inplace=True, drop=True)\n events_xyaz = events_xya[events_xya[\"Z\"] == z]\n events_xyaz.reset_index(inplace=True, drop=True)\n return events_xyaz[\"chiamate\"].sum() / eventi3[\"chiamate\"].sum() # TODO? su tutti gli eventi\n\n\ndef calcolo_p0_p_hat():\n global tabulato\n\n tabulato_coppie = tabulato\n tabulato_coppie = tabulato_coppie.drop(\n columns=[\"timestamp\", \"durata\", \"is_mittente_intercettato\", \"mittente_cella_start\", \"mittente_cella_end\",\n \"is_destinatario_intercettato\", \"destinatario_cella_start\", \"destinatario_cella_end\", \"esito_chiamata\",\n \"tipo\"])\n tabulato_coppie.drop_duplicates(inplace=True)\n tabulato_coppie.reset_index(inplace=True, drop=True)\n for i, row in tabulato_coppie.iterrows():\n x = row[\"mittente\"]\n y = row[\"destinatario\"]\n parts[(x, y)] = {}\n parts[(x, y)][\"A\"] = get_part_a(x, y)\n\n p0 = []\n p_cappuccio = []\n for i, row in eventi3.iterrows():\n x = row[\"X\"]\n y = row[\"Y\"]\n a = row[\"A\"]\n z = row[\"Z\"]\n p0.append(get_p0(x, y, a, z))\n p_cappuccio.append(get_p_cappuccio(x, y, a, z))\n eventi3[\"p0\"] = p0\n eventi3[\"p_cappuccio\"] = p_cappuccio\n eventi3.to_csv(\"data/events3_sign.csv\", index=False)\n\n\ndef n_chiamate():\n global tabulato\n tabulato_coppie = tabulato\n tabulato_coppie = tabulato_coppie.drop(\n columns=[\"timestamp\", \"durata\", \"is_mittente_intercettato\", \"mittente_cella_start\", \"mittente_cella_end\",\n \"is_destinatario_intercettato\", \"destinatario_cella_start\", \"destinatario_cella_end\", \"esito_chiamata\",\n \"tipo\"])\n tabulatof = tabulato_coppie.groupby(tabulato_coppie.columns.tolist()).size().reset_index().rename(\n columns={0: 'n_telefonate'})\n for i, row in tabulatof.iterrows():\n parts[(row[\"mittente\"], row[\"destinatario\"])][\"n_telefonate\"] = row['n_telefonate']\n return\n\n\ndef calcolo_z():\n eventi_p = pd.read_csv(\"data/events3_sign.csv\")\n z = []\n for i, row in eventi_p.iterrows():\n p_hat = row[\"p_cappuccio\"]\n p0 = row[\"p0\"] # if row[\"p0\"] != 0 else zero_probability_factor\n n = parts[(row[\"X\"], row[\"Y\"])][\"n_telefonate\"]\n root = math.sqrt((p0 * (1 - p0)) / n)\n z.append((p_hat - p0) / root)\n eventi_p[\"z\"] = z\n eventi_p.to_csv(\"data/events3_sign.csv\", index=False)\n\n return\n\n\ndef calcolo_sign():\n eventi_z = pd.read_csv(\"data/events3_sign.csv\")\n sign = []\n for i, row in eventi_z.iterrows():\n p = 1 - norm.cdf(row[\"z\"])\n sign.append(p)\n eventi_z[\"significativo\"] = sign\n eventi_z.to_csv(\"data/events3_sign.csv\", index=False)\n return\n\n\nif __name__ == \"__main__\":\n print(\"Inizio\")\n group()\n calcolo_p0_p_hat()\n n_chiamate()\n calcolo_z()\n calcolo_sign()\n print(\"Fine\")\n","sub_path":"window_43200/events3_sign.py","file_name":"events3_sign.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"336088774","text":"import sys\nimport time\n\nsys.path.insert(0, '/home/sshann/Documents/thesis/experiments/android-runner-configuration/')\n\nfrom scripts.interaction.python3.common import tap\nfrom scripts.interaction.python3.common import tap_phone_back\nfrom scripts.interaction.python3.common import write_username\nfrom scripts.interaction.python3.common import write_password\n\n\ndef login(device):\n print('\\tlogin')\n\n # click on username\n tap(device, 310, 602, 1)\n write_username(device)\n\n # click on password\n tap(device, 297, 858, 1)\n write_password(device)\n\n # click on login\n tap(device, 1210, 1056, 6)\n\n\ndef visit_global_stories(device):\n print('\\tvisit_global_stories')\n\n # click on global stories\n tap(device, 594, 330, 10)\n\n # click on card 1\n tap(device, 436, 453, 12)\n tap_phone_back(device)\n\n # click on card 2\n tap(device, 435, 858)\n tap_phone_back(device)\n\n # return to front page\n tap_phone_back(device)\n\n # click on global stories\n tap(device, 594, 330, 10)\n\n # click on card 1\n tap(device, 436, 453)\n tap_phone_back(device)\n\n # return to front page\n tap_phone_back(device)\n\n\ndef visit_all_shared_stories(device):\n print('\\tvisit_all_shared_stories')\n\n # click on all shared stories\n tap(device, 553, 442, 10)\n\n # click on card 1\n tap(device, 436, 453, 12)\n tap_phone_back(device)\n\n # click on card 2\n tap(device, 435, 858)\n tap_phone_back(device)\n\n # return to front page\n tap_phone_back(device)\n\n # click on all shared stories\n tap(device, 553, 442, 10)\n\n # click on card 1\n tap(device, 436, 453)\n tap_phone_back(device)\n\n # return to front page\n tap_phone_back(device)\n\n\n# noinspection PyUnusedLocal\ndef main(device, *args, **kwargs):\n if device.current_activity().find('com.newsblur') != -1:\n time.sleep(4)\n run_news_blur_interaction(device)\n else:\n print('\\tSkip file')\n\n\ndef run_news_blur_interaction(device):\n print('\\tRunning interaction for NewsBlur')\n # Login works, but there seems to be something wrong with Newblur deleting accounts,\n # so it is best to be logged in the entire experiment\n # login(device)\n visit_global_stories(device)\n visit_all_shared_stories(device)\n","sub_path":"android-runner-configuration/scripts/interaction/python3/com_newsblur.py","file_name":"com_newsblur.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"359260572","text":"'''\nCreated on 30 Mar 2018\n\n@author: vwltam\nmodified by ho yu hin on 18/5\n'''\nimport plotly.plotly as py\nimport pandas as pd\nfrom plotly.graph_objs import *\n\npy.sign_in('ms042087', 'Ytktzy7FUBCOGMoFSX0w')\n\nhb=pd.read_csv(\"test.csv\")\n\ndata = Data([\n Scatter(\n y=hb[\"y\"],\n mode='lines+markers',\n name=\"'linear'\",\n hoverinfo='name',\n line=dict(\n shape='linear'\n )\n )\n])\n\nlayout = Layout(\n title='HeartBeat [Line Chart]',\n xaxis = dict(title = 'data'),\n yaxis = dict(title = 'HeartBeat rate'),\n font=Font(\n family='Courier'\n )\n)\n\nfig = Figure(data=data, layout=layout)\nplot_url = py.plot(data,filename='HeartBeat [Line]')\npy.image.save_as(fig, 'HeartBeat.png')\n","sub_path":"Project/BusSafetySystem/crypt/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"42109151","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom dataset import *\n\nfrom Utils import *\n\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='Hyper Score')\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--epochs', type=int, default=40, metavar='N',\n help='number of epochs to train (default: 10)')\n parser.add_argument('--step-size', type=int, default=30)\n parser.add_argument('--lr', type=float, default=0.001, metavar='LR',\n help='learning rate (default: 0.001)')\n parser.add_argument('--combine-trainval', action='store_true',\n help=\"train and val sets together for training, val set alone for validation\")\n parser.add_argument('--momentum', type=float, default=0, metavar='M',\n help='SGD momentum (default: 0.5)')\n parser.add_argument('--train', action='store_true')\n parser.add_argument('--use_AM', action='store_true')\n parser.add_argument('--save_result', action='store_true')\n parser.add_argument('--resume', action='store_true')\n parser.add_argument('--data-path', type=str, default='1fps_train_IDE_40/',\n metavar='PATH')\n parser.add_argument('-L', type=str, default='L2', choices=['L1', 'L2'])\n # parser.add_argument('--tracklet', type=int, default=20, choices=[20, 40])\n parser.add_argument('--window', type=str, default='300', choices=['Inf','75', '150', '300', '600', '1200'])\n parser.add_argument('--log-dir', type=str, default='', metavar='PATH')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=100, metavar='N',\n help='how many batches to wait before logging training status')\n args = parser.parse_args()\n args.log_dir = 'logs/{}/appear_only/'.format(args.L, ) + args.data_path + args.log_dir\n args.data_path = os.path.expanduser('~/Data/DukeMTMC/ground_truth/') + args.data_path\n if args.combine_trainval:\n train_data_path = args.data_path + 'hyperGT_{}_trainval_{}.h5'.format(args.L, args.window)\n else:\n train_data_path = args.data_path + 'hyperGT_{}_train_{}.h5'.format(args.L, args.window)\n if args.save_result:\n test_data_path = args.data_path + 'hyperGT_{}_train_Inf.h5'.format(args.L)\n else:\n test_data_path = args.data_path + 'hyperGT_{}_val_Inf.h5'.format(args.L)\n torch.manual_seed(args.seed)\n if not os.path.isdir(args.log_dir):\n os.mkdir(args.log_dir)\n\n trainset = SiameseHyperFeat(HyperFeat(train_data_path))\n testset = SiameseHyperFeat(HyperFeat(test_data_path), train=True)\n train_loader = DataLoader(trainset, batch_size=args.batch_size,\n num_workers=4, pin_memory=True, shuffle=True)\n\n test_loader = DataLoader(testset, batch_size=args.batch_size,\n # sampler=HyperScoreSampler(testset, 1024),\n num_workers=4, pin_memory=True)\n\n metric_net = nn.DataParallel(MetricNet(num_class=2)).cuda()\n if args.resume:\n checkpoint = torch.load(args.log_dir + '/metric_net_{}_{}.pth.tar'.format(args.L, args.window))\n model_dict = checkpoint['state_dict']\n metric_net.module.load_state_dict(model_dict)\n\n appear_motion_net = nn.DataParallel(AppearMotionNet()).cuda()\n criterion = nn.CrossEntropyLoss().cuda()\n\n if args.train:\n # Draw Curve\n x_epoch = []\n train_loss_s = []\n train_prec_s = []\n test_loss_s = []\n test_prec_s = []\n optimizer = optim.SGD(metric_net.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=0.005)\n if not args.resume:\n for epoch in range(1, args.epochs + 1):\n train_loss, train_prec = train(args, metric_net, appear_motion_net, train_loader, optimizer, epoch,\n criterion)\n test_loss, test_prec = test(args, metric_net, appear_motion_net, test_loader, criterion)\n x_epoch.append(epoch)\n train_loss_s.append(train_loss)\n train_prec_s.append(train_prec)\n test_loss_s.append(test_loss)\n test_prec_s.append(test_prec)\n draw_curve(args, x_epoch, train_loss_s, train_prec_s, test_loss_s, test_prec_s)\n pass\n torch.save({'state_dict': metric_net.module.state_dict(), }, args.log_dir + '/metric_net_{}_{}.pth.tar'.\n format(args.L, args.window))\n else:\n test(args, metric_net, appear_motion_net, test_loader, criterion, )\n\n x_epoch = []\n train_loss_s = []\n train_prec_s = []\n test_loss_s = []\n test_prec_s = []\n # train appear_motion_net\n optimizer = optim.SGD(metric_net.parameters(), lr=0.1 * args.lr, momentum=args.momentum)\n if args.use_AM:\n for epoch in range(1, args.epochs + 1):\n train_loss, train_prec = train(args, metric_net, appear_motion_net, train_loader, optimizer, epoch,\n criterion, train_motion=True)\n test_loss, test_prec = test(args, metric_net, appear_motion_net, test_loader, criterion,\n test_motion=True)\n x_epoch.append(epoch)\n train_loss_s.append(train_loss)\n train_prec_s.append(train_prec)\n test_loss_s.append(test_loss)\n test_prec_s.append(test_prec)\n draw_curve(args, x_epoch, train_loss_s, train_prec_s, test_loss_s, test_prec_s, train_motion=True)\n pass\n torch.save({'state_dict': appear_motion_net.module.state_dict(), },\n args.log_dir + '/appear_motion_net_{}_{}.pth.tar'.format(args.L, args.window))\n if args.use_AM:\n save_model_as_mat(args, metric_net.module, appear_motion_net.module)\n else:\n save_model_as_mat(args, metric_net.module, [])\n\n checkpoint = torch.load(args.log_dir + '/metric_net_{}_{}.pth.tar'.format(args.L, args.window))\n model_dict = checkpoint['state_dict']\n metric_net.module.load_state_dict(model_dict)\n if args.use_AM:\n checkpoint = torch.load(args.log_dir + '/appear_motion_net_{}_{}.pth.tar'.format(args.L, args.window))\n model_dict = checkpoint['state_dict']\n appear_motion_net.module.load_state_dict(model_dict)\n test(args, metric_net, appear_motion_net, test_loader, criterion,\n test_motion=args.use_AM, save_result=args.save_result, epoch_max=100)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/hyper_score/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"260048092","text":"from bson import ObjectId\nfrom django import forms\nfrom models import *\n\n\nclass HumanForm(forms.Form):\n amount = forms.IntegerField()\n manager = forms.CharField(max_length=20)\n pet_name = forms.CharField(max_length=20)\n pet_age = forms.IntegerField()\n pet_specie = forms.CharField(max_length=20)\n job_name = forms.CharField(max_length=20)\n salary = forms.IntegerField()\n human_name = forms.CharField(max_length=20)\n human_age = forms.IntegerField()\n dateCreating = forms.DateTimeField()\n\n def __init__(self, *args, **kwargs):\n self.instance = kwargs.pop('instance', None)\n super(HumanForm, self).__init__(*args, **kwargs)\n if self.instance:\n self.fields['amount'].initial = self.instance.amount\n self.fields['pet_specie'].initial = self.instance.pet_specie\n self.fields['manager'].initial = self.instance.manager\n self.fields['pet_name'].initial = self.instance.pet_name\n self.fields['pet_age'].initial = self.instance.pet_age\n self.fields['job_name'].initial = self.instance.job_name\n self.fields['salary'].initial = self.instance.salary\n self.fields['human_name'].initial = self.instance.human_name\n self.fields['human_age'].initial = self.instance.human_age\n self.fields['dateCreating'].initial = self.instance.dateCreating\n\n def save(self, commit=True):\n human = self.instance if self.instance else Human()\n human.amount = self.cleaned_data['amount']\n human.pet_name = self.cleaned_data['pet_name']\n human.manager = self.cleaned_data['manager']\n human.pet_specie = self.cleaned_data['pet_specie']\n human.pet_age = self.cleaned_data['pet_age']\n human.job_name = self.cleaned_data['job_name']\n human.salary = self.cleaned_data['salary']\n human.human_name = self.cleaned_data['human_name']\n human.human_age = self.cleaned_data['human_age']\n human.dateCreating = self.cleaned_data['dateCreating']\n if commit:\n human.save()\n\n return human\n","sub_path":"Laba3/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"607858564","text":"from decimal import Decimal\n\nimport stripe\n\nfrom flask import (\n request, json, abort, jsonify, render_template, redirect, url_for)\nfrom flask_login import login_required, fresh_login_required\n\nfrom . import app, tryton\nfrom . import util\nfrom .compat import HTTPStatus\n\nCustomer = tryton.pool.get('account.payment.stripe.customer')\nCurrency = tryton.pool.get('currency.currency')\nJournal = tryton.pool.get('account.payment.journal')\nPayment = tryton.pool.get('account.payment')\nPaymentGroup = tryton.pool.get('account.payment.group')\nSale = tryton.pool.get('sale.sale')\n\n\n@app.route('/payment/setup_intent', methods={'POST'})\n@tryton.transaction()\n@login_required\ndef payment_setup_intent():\n stripe_account = util.get_stripe_account()\n party = util.get_session_party()\n try:\n if party.stripe_customers:\n customer = party.stripe_customers[0]\n if customer.stripe_setup_intent_id:\n return customer.stripe_setup_intent.client_secret\n else:\n cu = stripe.Customer.create(\n api_key=stripe_account.secret_key,\n description=party.rec_name,\n email=party.email)\n customer = Customer(\n party=party,\n stripe_account=stripe_account,\n stripe_customer_id=cu.id)\n setup_intent = stripe.SetupIntent.create(\n api_key=stripe_account.secret_key,\n customer=customer.stripe_customer_id)\n except stripe.error.StripeError as e:\n return (\n jsonify(e.user_message), HTTPStatus.INTERNAL_SERVER_ERROR)\n customer.stripe_setup_intent_id = setup_intent.id\n customer.save()\n return setup_intent.client_secret\n\n\n@app.route('/payment/setup_intent/update', methods={'POST'})\n@tryton.transaction()\n@login_required\ndef payment_setup_intent_update():\n party = util.get_session_party()\n customer = party.stripe_customers[0]\n setup_intent = customer.stripe_setup_intent\n customer.stripe_intent_update()\n if setup_intent:\n update_customer_payment(customer, setup_intent.payment_method)\n return ('', HTTPStatus.NO_CONTENT)\n\n\n@app.route('/payment/confirm/',\n methods={'GET'})\n@app.route('//payment/confirm/',\n methods={'GET'})\n@tryton.transaction()\n@fresh_login_required\ndef payment_confirm(payment):\n party = util.get_session_party()\n if payment.party != party:\n abort(HTTPStatus.FORBIDDEN)\n payment_intent = payment.stripe_payment_intent\n if not payment_intent:\n abort(HTTPStatus.FORBIDDEN)\n if isinstance(payment.origin, Sale):\n end_url = url_for('checkout_sale_end', order=payment.origin)\n else:\n end_url = url_for('payment_confirm_end')\n if payment_intent.status == 'succeeded':\n return redirect(end_url)\n return render_template('payment_confirm.html',\n payment=payment,\n stripe_key=util.get_stripe_account().publishable_key,\n end_url=end_url)\n\n\n@app.route('//payment/confirm/end')\n@tryton.transaction()\ndef payment_confirm_end():\n return render_template('payment_confirm_end.html')\n\n\n@app.route('/payment/cancel/',\n methods={'POST'})\n@tryton.transaction()\n@fresh_login_required\ndef payment_cancel(payment):\n party = util.get_session_party()\n if payment.party != party:\n abort(HTTPStatus.FORBIDDEN)\n payment_intent = payment.stripe_payment_intent\n if not payment_intent:\n abort(HTTPStatus.FORBIDDEN)\n if payment_intent.status in {'processing', 'succeeded'}:\n abort(HTTPStatus.FORBIDDEN)\n if payment_intent.status != 'canceled':\n payment_intent.cancel()\n Payment.fail([payment])\n if isinstance(payment.origin, Sale):\n return redirect(url_for(\n 'checkout_sale', order=payment.origin, step='payment'))\n return redirect(url_for('index'))\n\n\n@app.route('/payment/source/register', methods={'POST'})\n@tryton.transaction()\ndef payment_source_register():\n stripe_account = util.get_stripe_account()\n source = json.loads(request.form['source'])\n source = stripe.Source.retrieve(\n source['id'], api_key=stripe_account.secret_key)\n party = util.get_session_party()\n if not party:\n abort(HTTPStatus.BAD_REQUEST)\n if source.type == 'sepa_debit' and not party.sepa_debit_allowed:\n abort(HTTPStatus.FORBIDDEN)\n try:\n if party.stripe_customers:\n customer = party.stripe_customers[0]\n cu = customer.retrieve()\n cu.sources.create(source=source['id'])\n cu.save()\n else:\n cu = stripe.Customer.create(\n api_key=stripe_account.secret_key,\n source=source['id'])\n customer = Customer(\n party=party,\n stripe_account=stripe_account,\n stripe_customer_id=cu.id)\n except stripe.error.StripeError as e:\n return (\n jsonify(e.user_message), HTTPStatus.INTERNAL_SERVER_ERROR)\n customer.save()\n Customer._sources_cache.clear()\n update_customer_payment(customer, source['id'])\n return ('', HTTPStatus.NO_CONTENT)\n\n\n@app.route('/payment/register', methods={'POST'})\n@tryton.transaction()\ndef payment_register():\n source = json.loads(request.form['source'])\n party = util.get_session_party()\n if not party:\n abort(HTTPStatus.BAD_REQUEST)\n currency, = Currency.search([\n ('code', '=', source['currency'].upper()),\n ])\n payment = Payment()\n payment.company = util.get_company()\n payment.kind = 'receivable'\n payment.party = party\n payment.origin = request.args.get('origin', None)\n if not payment.origin:\n payment.account = util.get_deposit_account()\n payment.amount = Decimal(source['amount']) / (10 ** currency.digits)\n payment.journal = util.get_stripe_journal()\n payment.stripe_token = source['id']\n payment.stripe_chargeable = source['status'] == 'chargeable'\n if isinstance(payment.origin, Sale):\n Sale.quote([payment.origin])\n payment.save()\n Payment.approve([payment])\n group = PaymentGroup(\n company=payment.company, journal=payment.journal, kind=payment.kind)\n group.save()\n Payment.process([payment], lambda: group)\n return ('', HTTPStatus.NO_CONTENT)\n\n\n@app.route('/payment/wait', methods={'GET'})\n@tryton.transaction()\ndef payment_wait():\n return render_template('payment_wait.html',\n stripe_key=util.get_stripe_account().publishable_key,\n source=request.args.get('source'),\n client_secret=request.args.get('client_secret'),\n next=util.get_redirect_target())\n\n\ndef update_customer_payment(customer, payment):\n sales = util.get_session_sales()\n current_sale = util.get_session_sale()\n for sale in sales:\n if not sale.stripe_customer:\n sale.stripe_customer = customer\n if (sale.stripe_customer == customer\n and (not sale.stripe_customer_payment\n or sale == current_sale)):\n sale.stripe_customer_payment = payment\n Sale.save(sales)\n subscription = util.get_session_subscription()\n if subscription:\n if not subscription.stripe_customer:\n subscription.stripe_customer = customer\n if not subscription.stripe_customer_payment:\n subscription.stripe_customer_payment = payment\n subscription.save()\n","sub_path":"fruit/webshop/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"334462962","text":"import re\n\nPATERN_VARIABLE = [\n r'[A-Za-z0-9_]{1,}\\s{1,}[A-Za-z0-9_]{1,}\\s*',\n r'[A-Za-z0-9_]{1,}\\s{0,}<[A-Za-z0-9_]{1,}>\\s{0,}[A-Za-z0-9_]{1,}',\n r'[A-Za-z0-9_]{1,}\\s{1,}[A-Za-z0-9_]{1,}\\s{1,}[A-Za-z0-9_]{1,}',\n\n r'[A-Za-z0-9_]{1,}\\s{1,}[A-Za-z0-9_]{1,}\\s{0,};',\n r'[A-Za-z0-9_]{1,}\\s*<[A-Za-z0-9_]{1,}>\\s*[A-Za-z0-9_]{0,};',\n r'[A-Za-z0-9_]{1,}\\s{1,}[A-Za-z0-9_]{1,}\\s{1,}[A-Za-z0-9_]{0,};',\n]\n\n\n\n\n\n\ndico_stemming = {\n \"def\": \"d\",\n \"while\": \"w\",\n \"for\": \"f\",\n \"elif\": \"ei\",\n \"else\": \"e\",\n \"<=\": \"c\",\n \">=\": \"c\",\n \"<\": \"c\",\n \">\": \"c\",\n \"!=\": \"!\",\n \"==\": \"-\",\n \"and\": \"&\",\n \"or\": \"|\",\n \"int\": \"i\",\n \"bool\": \"bo\",\n \"string\": \"s\",\n \"long \": \"l\",\n \"char\":\"ch\",\n \"float \": \"fl\",\n \"void\": \"v\",\n \"double\":\"db\",\n \"break\":\"b\",\n \"case\":\"cs\",\n \"try\":\"t\",\n \"catch\":\"ct\",\n \"class\":\"cl\",\n \"continue\":\"cn\",\n \"default\":\"df\",\n \"const\": \"cst\",\n \"delete\": \"dl\" ,\n \"enum\":\"en\",\n \"private\":\"pri\",\n \"protected\":\"pro\",\n \"public\":\"pub\",\n \"extern\": \"ex\",\n \"friend\": \"fr\",\n \"goto\": \"got\",\n \"inline\": \"inl\",\n \"new\": \"nw\",\n \"operator\": \"op\",\n \"register\": \"rg\",\n \"return\": \"rt\",\n \"short\": \"sh\",\n \"signed\": \"sg\",\n \"sizeof\": \"sz\",\n \"static\": \"stc\",\n \"struct\": \"str\",\n \"switch\": \"sw\",\n \"typedef\": \"td\",\n \"template\": \"tmp\",\n \"throw\": \"th\",\n \"union\": \"un\",\n \"unsigned\": \"uns\",\n \"virtual\": \"vr\",\n \"volatile\": \"vl\",\n\n \"alignas\": \"ag\",\n \"alignof\": \"agn\",\n \"and_eq\": \"&e\",\n \"auto\": \"au\",\n \"bitand\": \"btd\",\n \"bitor\": \"bt\",\n \"char16_t\": \"c16\",\n \"char32_t\": \"c32\",\n\n \"constexpr\": \"cx\",\n \"decltype\": \"dt\",\n \"const_cast\": \"ca\",\n \"export\": \"ep\",\n \"thread_local\": \"tl\",\n \"static_assert\": \"ss\",\n \"reinterpret_cast\": \"ra\",\n \"this\": \"ti\",\n \"mutable\": \"mt\",\n \"xor_eq\": \"xe\",\n \"using,\": \"us\",\n \"noexcept, \": \"nx\",\n \"not\": \"n\",\n \"not_eq\": \"!p\",\n \"nullptr\": \"nr\",\n \"or_eq\": \"|p\",\n \"true\": \"tr\",\n \"false\": \"fs\",\n \"typeid\": \"tp\",\n \"xor\": \"xr\",\n\n}\n\n\ndico_supression = {\n \" \": \"\",\n \"{\": \"\",\n \"}\": \"\",\n \"(\": \"\",\n \")\": \"\",\n \";\": \"\",\n \":\": \"\"\n}\n\n\ndef delete_string(ligne):\n delete = False\n list_chain_to_remove = []\n\n if ligne.count(\"\\\"\") > 0:\n\n i = 0\n chain_to_remove = \"\"\n\n while i < len(ligne):\n\n if ligne[i] == '\\\"':\n list_chain_to_remove.append(chain_to_remove)\n chain_to_remove = \"\"\n delete = not delete\n\n if delete and ligne[i] != '\"':\n chain_to_remove = chain_to_remove + ligne[i]\n\n i += 1\n\n for chain in list_chain_to_remove:\n ligne = ligne.replace(chain, \"\")\n\n ligne = ligne.replace(\"\\\"\\\"\", \"\\\"\")\n\n return ligne\n\n\ndef replace_by_new_content(ligne):\n for key in dico_stemming:\n ligne = ligne.replace(key, dico_stemming[key])\n return ligne\n\n\ndef delete_unuse_content(ligne):\n for key in dico_supression:\n ligne = ligne.replace(key, dico_supression[key])\n\n return ligne\n\n\ndef sanitize_content(ligne):\n filtered_content = \"\"\n ligne = delete_string(ligne)\n filtered_content = filtered_content + (replace_by_new_content(ligne))\n filtered_content = delete_unuse_content(filtered_content)\n return filtered_content\n\n\n\ndef findVariableInFuction(line):\n listVariable = []\n cpt = 0\n inFunction = False\n\n listContentinit = []\n listVarInFunction = \"\"\n\n for signe in line:\n\n if signe == \"(\":\n cpt +=1\n inFunction = True\n\n elif signe == \")\":\n cpt -=1\n\n if inFunction:\n if True and cpt > 0 and signe != \"(\":\n listVarInFunction += signe\n\n else:\n listContentinit.append(listVarInFunction)\n listVarInFunction = \"\"\n\n\n listContentSplit = []\n listContentSplit2 = []\n\n for functionContent in listContentinit:\n functionContent = functionContent.replace(',', ', ')\n x = functionContent.split(\", \")\n\n for content in x:\n listContentSplit2.append(content)\n if not set('~!@#$%^&*()+.{}\":;\\'+$').intersection(content):\n\n if \"[\" in content:\n newContent = \"\"\n id=0\n finishExtractVarFromTable = False\n\n while id < len(content) and not finishExtractVarFromTable:\n if content[id] == \"[\":\n finishExtractVarFromTable = True\n\n else:\n newContent += content[id]\n id +=1\n\n content = newContent\n\n if re.search(PATERN_VARIABLE[0], content) != None or re.search(PATERN_VARIABLE[1], content) != None or re.search(PATERN_VARIABLE[2], content) != None:\n\n listContentSplit.append(content)\n\n\n for varaiblePart in listContentSplit:\n\n if \">\" in varaiblePart:\n parts = varaiblePart.split(\">\")\n parts[len(parts)-2] +=\">\"\n else:\n parts = varaiblePart.split(\" \")\n\n i = 0\n type=\"\"\n\n while i < len(parts) -1:\n type = type+parts[i]\n i +=1\n\n type = re.sub(' ', '', type)\n variable = re.sub(' ', '', parts[len(parts)-1])\n listVariable.append((type, variable))\n\n\n return listVariable\n\n\ndef findVariableDeclare(ligne):\n \"\"\"\n :param ligne: représente une ligne de code\n :return: retour le la liste des variable au seins d'une fonction\n \"\"\"\n\n listVariable = []\n type = \"\"\n list = []\n\n if True:\n i = 0\n find = False\n\n while i < len(ligne) and not find:\n\n if ligne[i] == \"=\":\n\n notFind = True\n findSeparator = True\n permissionParcourtWord = False\n\n k = i\n var = \"\"\n typeVar = \"\"\n listVariableTransition = []\n inTab = False\n\n while k > 0 and notFind:\n\n if ligne[k] == \" \":\n\n permissionParcourtWord = False\n\n if var != \"\":\n listVariableTransition.append(var)\n\n var = \"\"\n\n if ligne[k] == \",\":\n\n findSeparator = True\n permissionParcourtWord = False\n\n if var != \"\":\n listVariableTransition.append(var)\n var = \"\"\n\n if ligne[k] == \"]\":\n inTab= True\n\n if ligne[k] == \"/\":\n if len(ligne) > k+1:\n if ligne[k+1] == \"/\" or ligne[k+1] == \"*\":\n\n notFind = False\n\n #Si on trouve un signe arpès avoir trouvé un séparateur ou qu'on est en train de parcourir un mot\n if ligne[k] != \",\" and ligne[k] != \" \" and k != i and not inTab:\n\n if findSeparator or permissionParcourtWord:\n findSeparator = False\n permissionParcourtWord = True\n var = ligne[k]+var\n\n else:\n notFind = False\n\n\n if ligne[k] == \"[\":\n inTab = False\n\n\n if not notFind:\n type = \"\"\n while k > 0 and ligne[k] != \" \":\n type = ligne[k]+type\n k -=1\n\n\n for variable in listVariableTransition:\n if not set('[~!@#$%^&*()+.{}\":;\\']+$').intersection(type) and not set('[~!@#$%^&*()+.{}\":;\\']+$').intersection(variable) :\n type = re.sub(' ', '', type)\n variable = re.sub(' ', '', variable)\n typeVar = (type, variable)\n\n if typeVar not in listVariable:\n listVariable.append(typeVar)\n\n k -= 1\n\n elif ligne[i] == \";\" and \"=\" not in ligne:\n line=\"\"\n line = re.findall(r'\\s{0,}[A-Za-z0-9_]{1,}\\s{1,}[A-Za-z0-9_]{1,};', ligne)\n\n if line != [] and \"return\" not in line[0]:\n\n line = re.sub(';', '', line[0])\n ligneTab = line.split(\" \")\n\n u = 0\n type = \"\"\n var = \"\"\n while u\n line = re.sub(r'\\s{0,}'+variable+r'\\s{0,}<', type+\"<\", line)\n line = re.sub(r'\\s{0,}'+variable+r'\\s{0,}>', type+\">\", line)\n line = re.sub(r'>\\s{0,}'+variable+r'\\s{0,}>', \">\"+type+\">\", line)\n line = re.sub(r'<\\s{0,}'+variable+r'\\s{0,}<', \"<\"+type+\"<\", line)\n line = re.sub(r'>\\s{0,}'+variable+r'\\s{0,}<', \">\"+type+\"<\", line)\n line = re.sub(r'<\\s{0,}'+variable+r'\\s{0,}>', \"<\"+type+\">\", line)\n\n ###gestion du séparateur \",\"\n line = re.sub(r'\\s{0,}'+variable+r'\\s{0,},', type+\",\", line)\n line = re.sub(r',\\s{0,}'+variable+r'\\s{0,},', \",\"+type+\",\", line)\n line = re.sub(r',\\s{0,}'+variable+r'\\s{0,}=', \",\"+type+\"=\", line)\n line = re.sub(r',\\s{0,}'+variable+r'\\s{0,}\\)', \",\"+type+\")\", line)\n\n ###gestion des symbole ( )\n line = re.sub(r'\\s{0,}'+variable+r'\\s{0,}\\)', type+\")\", line)\n line = re.sub(r'\\(\\s{0,}'+variable+r'\\s{0,},', \"(\"+type+\",\", line)\n line = re.sub(r'\\(\\s{0,}'+variable+r'\\s{0,}\\)', \"(\"+type+\")\", line)\n line = re.sub(r'\\s{0,}'+variable+r'\\s{0,}!', type+\"!\", line)\n line = re.sub(r'\\s{0,}'+variable+r'\\s{0,}<', type+\"<\", line)\n line = re.sub(r'\\s{0,}'+variable+r'\\s{0,}>', type+\">\", line)\n\n i += 1\n\n return line\n\n\n\n\n\n\ndef sanitize_list(liste_variable):\n \"\"\"\n :param liste_variable: représente la liste des variables du code\n :return: retourne la liste des variables après avoir ajouté un espace après le type de la variable. Permet de différencier les types Matrice et collection\n \"\"\"\n\n id = 0\n for elt in liste_variable:\n cpt = elt[0].count('>')\n\n if cpt == 0:\n newElt = (elt[0] + \" \", elt[1])\n elt = newElt\n liste_variable[id] = newElt\n\n id += 1\n\n return liste_variable\n\n\n\ndef remove_comentary(lignes):\n \"\"\"\n :param liste_variable: représente la liste des variables du code\n :return: retourne la liste des variables après avoir ajouté un espace après le type de la variable. Permet de différencier les types Matrice et collection\n \"\"\"\n long_comment = False\n code_without_comentary = []\n\n for ligne in lignes:\n\n if \"//\" in ligne:\n tab_line = ligne.split(\"//\")\n code_without_comentary.append(tab_line[0])\n\n elif \"/*\" in ligne and \"*/\" in ligne:\n tab_line1 = ligne.split(\"/*\")\n tab_line2 = ligne.split(\"*/\")\n new_line = tab_line1[0] + tab_line2[len(tab_line2)-1]\n code_without_comentary.append(new_line)\n\n elif \"/*\" in ligne:\n tab_line = ligne.split(\"/*\")\n code_without_comentary.append(tab_line[0])\n long_comment = True\n\n elif \"*/\" in ligne:\n tab_line = ligne.split(\"*/\")\n code_without_comentary.append(tab_line[len(tab_line)-1])\n long_comment = False\n\n\n elif not long_comment:\n code_without_comentary.append(ligne)\n\n\n\n return code_without_comentary\n\n\ndef excecEvalRedondance(code):\n\n listFunction = []\n listVariableRename = []\n lastListVariableRename = []\n\n listVarBlock = []\n lignes = code.split(\"\\n\")\n\n scopeCodeUser = False\n firstInsert = False\n long_comment = False\n\n lignesCompacte = \"\"\n newBlock = []\n functionCode = \"\"\n\n lignes = remove_comentary(lignes)\n\n for ligne in lignes:\n\n if \"#include\" not in ligne and \"using namespace\" not in ligne:\n\n ligne = ligne.replace('\\n', '')\n\n listeVarInitFunction = findVariableInFuction(ligne)\n\n if listeVarInitFunction != []:\n\n if listVariableRename != []:\n\n listFunction.append(listVariableRename)\n functionCode= \"\"\n listVariableRename=[]\n listVarToRenameFunction = []\n lastListVariableRename = []\n\n i = 0\n while i < len(listeVarInitFunction):\n if listeVarInitFunction[i] not in listVariableRename and listeVarInitFunction[i] != \"\":\n listVariableRename.append(listeVarInitFunction[i])\n i += 1\n\n else:\n listVarToRenameFunction = listeVarInitFunction\n\n i = 0\n while i < len(listVarToRenameFunction):\n if listVarToRenameFunction[i] not in listVariableRename and listVarToRenameFunction[i] != \"\":\n listVariableRename.append(listVarToRenameFunction[i])\n i += 1\n\n\n else:\n listVarToRenameFunction = listeVarInitFunction + findVariableDeclare(ligne)\n\n i = 0\n while i < len(listVarToRenameFunction):\n if listVarToRenameFunction[i] not in listVariableRename and listVarToRenameFunction[i] != \"\":\n listVariableRename.append(listVarToRenameFunction[i])\n i += 1\n\n\n\n lignesCompacte +=ligne\n\n listFunction.append(listVariableRename)\n\n blockCodesWithRenameVariable = []\n listFunctionCode = find_function(lignesCompacte)\n\n\n for function in listFunctionCode:\n blockCodesWithRenameVariable.append(function)\n\n codeRename = \"\"\n i=0\n for elt in blockCodesWithRenameVariable:\n codeRename += rename_variable(elt, listFunction[i])\n i +=1\n\n blockCodes = find_block(codeRename)\n\n\n\n print(blockCodes)\n\n for bl in blockCodes:\n print(bl)\n\n\n cptRedondance = 0\n\n for block in blockCodes:\n if blockCodes[block] > 1:\n cptRedondance += blockCodes[block]-1\n\n return cptRedondance\n\n","sub_path":"evaluation_code/cpp/evalRedondance.py","file_name":"evalRedondance.py","file_ext":"py","file_size_in_byte":19177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"192185487","text":"\"\"\"\nImporting and using sqlite module within python program\n@author: outsider\n\"\"\"\n\nimport sqlite3\n\nsqliteFile = 'test.sqlite'\ntableName = 'table2'\nid = 'testID'\nsomeID = 123456\ncol2 = 'table2seconCol' #Name of the new column\ncol3 = 'table2thirdCol' #Name of the new column\n\n#Connecting to the database file\nconn = sqlite3.connect(sqliteFile)\nc = conn.cursor()\n\n#Contents of all columns for row that match the id number from column 1\nc.execute('SELECT * FROM {tn} WHERE {cn}=\"Hi Sylvain\"'\\\n .format(tn=tableName, cn=col2))\nallRows = c.fetchall()\nprint('1:', allRows)\n\n#Value of a particular column for rows that match a certain value in column 1\nc.execute('SELECT ({coi}) FROM {tn} WHERE {cn}=\"Hi Sylvain\" '\\\n .format(coi=col2, tn=tableName, cn=col2))\nallRows = c.fetchall()\nprint('2:', allRows)\n\n#Values of 2 particular columns for rows that match a certain value in column 1\nc.execute('SELECT {coi},{coi1} FROM {tn} WHERE {cn}=\"Hi Sylvain\" '\\\n .format(coi=col2, coi1=col3, tn=tableName, cn=col2))\nallRows = c.fetchall()\nprint('3:', allRows)\n\nc.execute('SELECT * FROM {tn} WHERE {cn}=\"Hi Sylvain\" LIMIT 10 '\\\n .format(coi=col2, tn=tableName, cn=col2))\ntenRows = c.fetchall()\nprint('4:', tenRows)\n\n#Check whether or not an ID exists and print all columns relative to that\nc.execute('SELECT * FROM {tn} WHERE {idf}={testID} '\\\n .format(tn=tableName, cn=col2, idf=id, testID=someID))\nidExists = c.fetchone()\nif(idExists):\n print('5: {}'.format(idExists))\nelse:\n print('5: {} does not exists'.format(id))\n\n\nconn.close()\n\n\n#This method is for cleanning the variables and prevent SQL's injections... \ndef cleanNames(someVariable):\n return ''.join(char for char in someVariable if char.isalnum())\n\n\n\n\n","sub_path":"select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"461474794","text":"class Cars:\n def minecolor(self,color):\n self.color=color\n print(self.color)\nclass BMW(Cars):\n def topspeed(self,speed):\n self.speed=speed\n print(self.speed)\nobjc=Cars()\nobjBMW=BMW()\nobjc.minecolor(\"red\")\n#objc.topspeed(100)\nobjBMW.minecolor(\"blue\")\nobjBMW.topspeed(50)","sub_path":"day6assignment-26july/26july2021-Kalaiarasi-day6assignment/inherit.py","file_name":"inherit.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"560989566","text":"import os\nimport sys\nimport random\nimport math\nimport re\nimport time\nimport numpy as np\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn import utils\n\n\ndef random_shape(height, width):\n \"\"\"Generates specifications of a random shape that lies within\n the given height and width boundaries.\n Returns a tuple of three valus:\n * The shape name (square, circle, ...)\n * Shape color: a tuple of 3 values, RGB.\n * Shape dimensions: A tuple of values that define the shape size\n and location. Differs per shape type.\n \"\"\"\n # Shape\n shape = random.choice([\"square\", \"circle\", \"triangle\"])\n # Color\n color = tuple([random.randint(0, 255) for _ in range(3)])\n # Center x, y\n buffer = 20\n y = random.randint(buffer, height - buffer - 1)\n x = random.randint(buffer, width - buffer - 1)\n # Size\n s = random.randint(buffer, height // 4)\n return shape, color, (x, y, s)\n\n\ndef random_image():\n \"\"\"Creates random specifications of an image with multiple shapes.\n Returns the background color of the image and a list of shape\n specifications that can be used to draw the image.\n \"\"\"\n # Pick random background color\n bg_color = np.array([random.randint(0, 255) for _ in range(3)])\n height = random.randint(300, 350)\n width = random.randint(350, 400)\n print(\"bg_color: \" + str(bg_color))\n print(\"height: \" + str(height))\n print(\"width: \" + str(width))\n\n image = np.ones([height, width, 3], dtype=np.uint8) * bg_color\n mask = np.zeros([height, width, 3], dtype=np.uint8)\n labels = []\n assert image.shape == mask.shape\n\n # Generate a few random shapes\n shapes = []\n boxes = []\n N = random.randint(1, 4)\n for _ in range(N):\n shape, color, dims = random_shape(height, width)\n shapes.append((shape, color, dims))\n x, y, s = dims\n boxes.append([y - s, x - s, y + s, x + s])\n # Apply non-max suppression wit 0.3 threshold to avoid\n # shapes covering each other\n keep_ixs = utils.non_max_suppression(\n np.array(boxes), np.arange(N), 0.1)\n shapes = [s for i, s in enumerate(shapes) if i in keep_ixs]\n\n for shape, color, dims in shapes:\n x, y, s = dims\n if shape == 'square':\n image = cv2.rectangle(image, (x - s, y - s),\n (x + s, y + s), color, -1)\n mask = cv2.rectangle(mask, (x - s, y - s),\n (x + s, y + s), 1, -1)\n labels.append([1, x, y, s])\n elif shape == \"circle\":\n image = cv2.circle(image, (x, y), s, color, -1)\n mask = cv2.circle(mask, (x, y), s, 2, -1)\n labels.append([2, x, y, s])\n elif shape == \"triangle\":\n points = np.array([[(x, y - s),\n (x - s / math.sin(math.radians(60)), y + s),\n (x + s / math.sin(math.radians(60)), y + s),\n ]], dtype=np.int32)\n image = cv2.fillPoly(image, points, color)\n mask = cv2.fillPoly(mask, points, 3)\n labels.append([3, x, y, s])\n\n return image, mask, np.array(labels)\n\n\nif __name__ == \"__main__\":\n num_simple = 100\n simple_path = os.path.join(ROOT_DIR, \"samples/shapes/generated\")\n\n for i in range(num_simple):\n temp_dir = os.path.join(simple_path, \"simple\" + str(i))\n if os.path.exists(temp_dir):\n ls = os.listdir(temp_dir)\n for file in ls:\n os.remove(os.path.join(temp_dir, file))\n else:\n os.makedirs(temp_dir)\n\n image, mask, labels = random_image()\n cv2.imwrite(os.path.join(temp_dir, \"img.png\"), image)\n cv2.imwrite(os.path.join(temp_dir, \"label.png\"), mask)\n np.savetxt(os.path.join(temp_dir, \"labels.txt\"), labels)","sub_path":"samples/shapes/generate_shapes.py","file_name":"generate_shapes.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"593147232","text":"from django.shortcuts import render, redirect \r\nfrom django.contrib.auth.decorators import login_required \r\nfrom django.contrib import messages \r\nfrom .forms import ImageCreateForm\r\nfrom .models import Image\r\n\r\n\r\n@login_required \r\ndef image_create(request):\t\r\n\tif request.method == 'POST': \r\n\t\tform = ImageCreateForm(data=request.POST,files=request.FILES) \r\n\t\tif form.is_valid(): \r\n\t\t\tcd = form.cleaned_data\r\n\t\t\t \r\n\t\t\tnew_item = form.save(commit=False) \r\n\t\t\tnew_item.user = request.user \r\n\t\t\tnew_item.save() \r\n\t\t\tmessages.success(request, 'Image added successfully') \r\n\telse:\r\n\t\tform = ImageCreateForm(data=request.GET)\r\n\r\n\treturn render(request,'image/img/create.html',{'section': 'images','form': form})\r\n","sub_path":"image/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"604035713","text":"#!/bin/bash/env python\n# coding=UTF-8\n# by Tarcisio marinho\n# github.com/tarcisio-marinho\nimport os, subprocess, random, socket\n\ndef conexao(meuIP):\n # servidor\n f=open('private_key.txt','r')\n chave_privada=f.read()\n print(chave_privada)\n print('Servidor rodando')\n while True:\n porta=6064\n\n socket_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_obj.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # se der ctrl + c, ele para de escutar na porta\n socket_obj.bind((meuIP, porta))\n socket_obj.listen(1) # escuta apenas 1 \"vitma\"\n #os.system('clear')\n conexao,endereco=socket_obj.accept()\n\n # ao se conectar, envia a chave privada (S)\n conexao.send(str(chave_privada))\n # recebeu do cliente o ID\n\n print(recebido)\n\n\nconexao('127.0.0.1')\n","sub_path":"C&C/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"417184586","text":"import os\nimport shutil\nimport argparse\nfrom PIL import Image, ImageChops, ImageStat\n\nimport misli\nfrom .constants import RECORDING_EXTENSION, SNAP_EXTENSION\nfrom misli.gui import update_components_from_changes\nfrom misli.gui.qt_main_loop import QtMainLoop\n\nimport pamet\n\nfrom .gui_recorder import MisliGuiRecorder\nfrom .gui_replay import MisliGuiReplay\n\nINSPECTION_TEMPLATES_PATH = 'inspection_templates'\nAUTOMATIC_INSPECTION_OUTPUT_PATH = 'automatic_inspection_output'\nMANUAL_INSPECTION_OUTPUT_PATH = 'manually_verified_inspections'\nDIFF_FOLDER = 'tmp_last_visual_inspection_diffs'\n\n\ndef run_recording(file_for_replay, output_folder, replay_speed):\n misli.set_main_loop(QtMainLoop())\n misli_gui.set_reproducible_ids(True)\n\n recorder = MisliGuiRecorder('BrowserWindowView')\n misli.gui.on_action(recorder.handle_action_channel)\n\n replay = MisliGuiReplay(file_for_replay)\n replay.speed = replay_speed\n\n misli.on_change(update_components_from_changes)\n misli.gui.on_action(replay.queue_next_action)\n\n # desktop_app = misli.gui.create_view('DesktopApp', parent_id='')\n\n desktop_app_class = pamet.view_library.get_view_class('BrowserWindowView')\n desktop_app = desktop_app_class(parent_id='')\n\n replay.queue_next_action([])\n desktop_app.exec_()\n\n recorder.save_recording(output_folder, overwrite=True)\n\n\ndef compare_images(img1, img2):\n # Don't compare if images are of different modes or different sizes.\n if (img1.mode != img2.mode) \\\n or (img1.size != img2.size) \\\n or (img1.getbands() != img2.getbands()):\n return 100\n\n # Generate diff image in memory.\n diff_img = ImageChops.difference(img1, img2)\n # Calculate difference as a ratio.\n stat = ImageStat.Stat(diff_img)\n diff_ratio = sum(stat.mean) / (len(stat.mean) * 255)\n\n return diff_ratio * 100\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--manual-verification', action='store_true')\n parser.add_argument('--replay-speed', default=1)\n args = parser.parse_args()\n\n manual_verification = args.manual_verification\n replay_speed = args.replay_speed\n\n output_folder = AUTOMATIC_INSPECTION_OUTPUT_PATH\n if manual_verification:\n print('MANUAL MODE: The generated snapshots of the BrowserWindow will'\n ' be used for the automatic visual inspections, so you should'\n ' verify that the app is working correctly. You can adjust the'\n ' actions replay speed with the --replay-speed argument.')\n output_folder = MANUAL_INSPECTION_OUTPUT_PATH\n\n print('RUNNING AUTOMATED TESTS: press CTRL+C in the console to abort the '\n 'process and discard the last test. Press Enter to start.')\n\n for template in os.scandir(INSPECTION_TEMPLATES_PATH):\n if not template.name.endswith(RECORDING_EXTENSION):\n raise Exception('Unexpected file %s' % template)\n\n tname = template.name[:-len(RECORDING_EXTENSION)]\n\n results_folder = os.path.join(output_folder, tname)\n\n run_recording(template.path, results_folder, replay_speed)\n print('Done with template \"%s\".' % tname)\n\n if manual_verification:\n return\n\n print('Done with all inspections. Starting to compare with the manually '\n 'verified data')\n\n diffs_found = 0\n\n for recording in os.scandir(AUTOMATIC_INSPECTION_OUTPUT_PATH):\n snapshots_folder = os.path.join(recording.path, 'snapshots')\n good_snaps_folder = os.path.join(\n MANUAL_INSPECTION_OUTPUT_PATH,\n recording.name,\n 'snapshots')\n\n if not os.path.exists(good_snaps_folder):\n print('Manually verified images for %s missing.' % recording.name)\n continue\n\n for snap in os.scandir(snapshots_folder):\n good_snap_path = os.path.join(good_snaps_folder, snap.name)\n\n if not os.path.exists(good_snap_path):\n continue\n\n image = Image.open(snap.path)\n good_image = Image.open(good_snap_path)\n\n diff_value = compare_images(image, good_image)\n\n if diff_value > 0.01:\n diffs_found += 1\n snap_meta, ext = os.path.splitext(snap.name)\n print('DIFFERENCE %s (>0.001) for \"%s\" in recording \"%s\"' %\n (diff_value, snap_meta, recording.name))\n\n diff_folder = os.path.join(\n DIFF_FOLDER, recording.name, snap_meta)\n\n if os.path.exists(diff_folder):\n shutil.rmtree(diff_folder)\n\n os.makedirs(diff_folder, exist_ok=True)\n\n common_target_path = os.path.join(diff_folder, snap.name)\n target_path_good_img = (common_target_path + '_good' +\n SNAP_EXTENSION)\n\n shutil.copy(snap.path, common_target_path + SNAP_EXTENSION)\n shutil.copy(good_snap_path, target_path_good_img)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests/visual/run_visual_inspection.py","file_name":"run_visual_inspection.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"83356037","text":"#!flask/bin/python\nfrom flask import Flask, jsonify\nfrom flask import abort\nimport array\nfrom flask import request\nfrom flask import make_response\nfrom flask import url_for\n\n\napp = Flask(__name__)\n\n\n#We use a temporary in memory json object to store the services\n#This of course should be on a DB in the long term.\t \nservices = [\n {\n 'id': 1,\n#\t\t'uniqueID' : u'0.0.1.1.epochtime',\n 'change_version':1, \n 'service': u'test',\n 'version': u'0.0.1', \n 'change': u'created'\n },\n {\n 'id': 2,\n#\t\t'uniqueID' : u'0.0.1.2.epochtime',\n 'change_version':1,\n 'service': u'test',\n\t 'version': u'0.0.1', \n 'change': u'created'\n },\n\t{\n 'id': 3,\n#\t\t'uniqueID' : u'0.0.2.1.epochtime',\n 'change_version':1,\n 'service': u'test',\n 'version': u'0.0.2', \n 'change': u'created'\n },\n {\n 'id': 4,\n#\t\t'uniqueID' : u'0.0.2.2.epochtime',\n 'change_version':1,\n 'service': u'test',\n\t 'version': u'0.0.2', \n 'change': u'created'\n },\n {\n 'id': 5,\n#\t\t'uniqueID' : u'0.0.2.1.epochtime',\n 'change_version':1,\n 'service': u'test2',\n\t 'version': u'0.0.2', \n 'change': u'created'\n },\n\t {\n 'id': 6,\n#\t\t'uniqueID' : u'0.0.2.2.epochtime',\n 'change_version':1,\n 'service': u'test2',\n\t 'version': u'0.0.2', \n 'change': u'created'\n }\n]\n\n#This is our get function at the high level. This will return a json object including all registered services.\n#We also return a URI refering to each service so that the users don't have to create that\n@app.route('/service_registry/api/v1.0/services', methods=['GET'])\ndef get_services():\n return jsonify({'services': services})\n#put the code below in once you get URIs working\n# return jsonify({'services': [make_public_service(service) for service in services]})\n\n#This get function returns a service by service id\n@app.route('/service_registry/api/v1.0/services/', methods=['GET'])\ndef get_service_id(service_id):\n service = [service for service in services if service['id'] == service_id]\n if len(service) == 0:\n abort(404)\n return jsonify({'service': service[0]})\n#This end point returns all instances and versions for a given service\n@app.route('/service_registry/api/v1.0/services//getAll', methods=['GET'])\ndef get_service_all(service_name_all):\n service = [service for service in services if service['service'] == service_name_all]\n if len(service) == 0:\n abort(404)\n return jsonify({'service': service})\n\t\n\n\n\n#This returns the count of a given service\n@app.route('/service_registry/api/v1.0/services/', methods=['GET'])\ndef get_service(service_name):\n service = [service for service in services if service['service'] == service_name]\n if len(service) == 0:\n return jsonify({'service': service_name,'count': 0 })\n count=len(service)\t\n return jsonify({'service': service_name,'count': count })\n#this returns the counts of a service and version\n@app.route('/service_registry/api/v1.0/services//', methods=['GET'])\ndef get_service_count(service_name,service_version):\n service = [service for service in services if service['service'] == service_name and service['version'] == service_version]\n if len(service) == 0:\n return jsonify({'service': service_name, 'version' : service_version ,'Not found':'True', 'count': 0 })\n count=len(service)\t\n #return jsonify({'service': service})\t\n return jsonify({'service': service_name, 'version' : service_version, 'count': count })\n\t\n\n#return a nice message if not found\n@app.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\t#This is the post end point implementation\n@app.route('/service_registry/api/v1.0/services', methods=['POST'])\ndef create_service():\n if not request.json or not 'service' in request.json or not 'version' in request.json:\n abort(400)\n service = {\n 'id': services[-1]['id'] + 1,\n 'change_version':1,\n 'service': request.json['service'],\n 'version': request.json.get('version', \"\"),\n# 'uniqueID' : u'0.0.2.2.epochtime',\n 'change': u'created'\n }\n services.append(service)\n return jsonify({'service': service}), 201\n\n \n\n#This is the update service using the service id\n#Other types of update needs to be implemented\n@app.route('/service_registry/api/v1.0/services/', methods=['PUT'])\ndef update_service(service_id):\n service = [service for service in services if service['id'] == service_id]\n if len(service) == 0:\n abort(404)\n if not request.json:\n abort(400)\n if 'service' in request.json and type(request.json['service']) != str:\n abort(400)\n if 'version' in request.json and type(request.json['version']) != str:\n abort(400)\n if 'change' in request.json and type(request.json['change']) != str:\n abort(400)\n service[0]['service'] = request.json.get('service', service[0]['service'])\n service[0]['version'] = request.json.get('version', service[0]['version'])\n service[0]['change'] = u'changed'\n service[0]['change_version']=service[0]['change_version']+1\n return jsonify({'service': service[0]})\n\n#This is the put implementation for /services/service_name\n@app.route('/service_registry/api/v1.0/services/', methods=['PUT'])\ndef update_service_serviceName(service_name):\n service = [service for service in services if service['service'] == service_name]\n if len(service) == 0:\n abort(404)\n if not request.json:\n abort(400)\n if 'service' in request.json and type(request.json['service']) != str:\n abort(400)\n if 'version' in request.json and type(request.json['version']) != str:\n abort(400)\n if 'change' in request.json and type(request.json['change']) != str:\n abort(400)\n\n for i in range(0,len(service)):\n service[i]['service'] = request.json.get('service', service[i]['service'])\n service[i]['version'] = request.json.get('version', service[i]['version'])\n service[i]['change'] = u'changed'\n service[i]['change_version']=service[i]['change_version']+1\n\n return jsonify({'service': service})\n\n#This is the put implementation for /services/service_name/version_name\n@app.route('/service_registry/api/v1.0/services//', methods=['PUT'])\ndef update_service_serviceName_versionName(service_name,service_version):\n service = [service for service in services if service['service'] == service_name and service['version'] == service_version]\n if len(service) == 0:\n abort(404)\n if not request.json:\n abort(400)\n if 'service' in request.json and type(request.json['service']) != str:\n abort(400)\n if 'version' in request.json and type(request.json['version']) != str:\n abort(400)\n if 'change' in request.json and type(request.json['change']) != str:\n abort(400)\n\n for i in range(0,len(service)):\n service[i]['service'] = request.json.get('service', service[i]['service'])\n service[i]['version'] = request.json.get('version', service[i]['version'])\n service[i]['change'] = u'changed'\n service[i]['change_version']=service[i]['change_version']+1\n\n return jsonify({'service': service})\n\n#This is the delete end point\n@app.route('/service_registry/api/v1.0/services/', methods=['DELETE'])\ndef delete_service(service_id):\n service = [service for service in services if service['id'] == service_id]\n if len(service) == 0:\n abort(404)\n services.remove(service[0])\n return jsonify({'sesrvice': service[0]['service'],'id': service[0]['id'],'change': 'removed'})\n services.append(service)\n return jsonify({'service': service}), 201\n#This function is used to create a URI to our services. This helps the user interact with the service\n#We have removed it for now and can be added in the future to help users make calls to services\n#def make_public_service(service):\n# new_service = {}\n# for field in service:\n# if field == 'id':\n# new_service['uri'] = url_for('get_services', service_id=service['id'], _external=True)\n# else:\n# new_service[field] = service[field]\n # return new_service\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"service-registry-api/service_resigter.py","file_name":"service_resigter.py","file_ext":"py","file_size_in_byte":8485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189248962","text":"import time\nimport os\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nimport json\nimport requests\n\n\nclass Watcher:\n dir_path = os.path.dirname(os.path.realpath(__file__))\n DIRECTORY_TO_WATCH = dir_path + \"/data/\"\n\n def __init__(self):\n self.observer = Observer()\n\n def run(self):\n print(self.DIRECTORY_TO_WATCH)\n event_handler = Handler()\n self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)\n self.observer.start()\n print(self.DIRECTORY_TO_WATCH)\n try:\n while True:\n time.sleep(5)\n except:\n self.observer.stop()\n print(\"Error\")\n\n self.observer.join()\n\n\nclass Handler(FileSystemEventHandler):\n def on_any_event(self, event):\n if event.is_directory:\n print(event)\n return None\n\n elif event.event_type == 'created':\n # Take any action here when a file is first created.\n # print(\"Received created event - %s.\" % event.src_path);\n file = event.src_path\n json_data = open(file)\n test_data = json.load(json_data)\n for item in test_data:\n requests.post('http://localhost:8000/api/records/', data=item)\n\n\nif __name__ == '__main__':\n w = Watcher()\n w.run()\n","sub_path":"backend/records/watch_for_changes.py","file_name":"watch_for_changes.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"548280961","text":"from setuptools import setup\nfrom setuptools.command.install import install\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\nclass CustomInstall(install):\n def run(self):\n install.run(self)\n # custom stuff here\n print(readme())\n\nsetup(name='theonering',\n version='0.1',\n description='One ring to rule them all, one ring to find them, one ring to bring them all and in the darkness bind them',\n long_description=readme(),\n url='http://github.com/unk/unk',\n author='unk',\n author_email='unk@unk.com',\n license='MIT',\n packages=['theonering'],\n install_requires=[\n 'virtualenv',\n 'virtualenvwrapper',\n 'ipython'\n ],\n scripts=['bin/sauron'],\n test_suite='nose.collector',\n tests_require=['nose'],\n include_package_data=True,\n zip_safe=False,\n cmdclass={'install': CustomInstall})\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"452349951","text":"import os.path\n\nfrom saml2 import BINDING_HTTP_REDIRECT\nfrom saml2.saml import NAME_FORMAT_BASIC\n\ntry:\n from saml2.sigver import get_xmlsec_binary\nexcept ImportError:\n get_xmlsec_binary = None\n\nif get_xmlsec_binary:\n xmlsec_path = get_xmlsec_binary([\"/opt/local/bin\"])\nelse:\n xmlsec_path = '/usr/bin/xmlsec1'\n\n\n#BASE = 'http://edem.microcomp.sk'\n#entityid' : 'http://edem.microcomp.sk',\nBASE = 'http://edem.microcomp.sk'\nCONFIG_PATH = os.path.dirname(__file__)\n\nUSER_MAPPING = {\n 'email': 'mail',\n 'fullname': 'field_display_name',\n}\n#'idp': ['urn:mace:umu.se:saml:ckan:idp'],\nCONFIG = {\n 'entityid' : 'http://edem.microcomp.sk',\n 'description': 'CKAN saml2 auth',\n 'service': {\n 'sp': {\n 'name' : 'CKAN SP',\n 'endpoints': {\n 'assertion_consumer_service': [BASE],\n 'single_logout_service' : [(BASE + '/slo',\n BINDING_HTTP_REDIRECT)],\n },\n 'required_attributes': [\n # 'sn',\n 'uid',\n # 'name',\n # 'mail',\n # 'status',\n # 'roles',\n # 'field_display_name',\n # 'realname',\n # 'groups',\n # 'givenname',\n # 'surname',\n # 'edupersonaffiliation',\n ],\n 'optional_attributes': [],\n \"authn_assertions_signed\": \"true\",\n \"authn_requests_signed\" : \"true\",\n \"want_assertions_signed\": \"true\",\n \"logout_requests_signed\": \"true\",\n }\n },\n 'debug': 1,\n 'key_file': CONFIG_PATH + '/pki/mod_key.pem',\n 'cert_file': CONFIG_PATH + '/pki/mod_cert.pem',\n 'attribute_map_dir': CONFIG_PATH + '/../attributemaps',\n 'metadata': {\n 'local': [CONFIG_PATH + '/idp.xml'],\n },\n # -- below used by make_metadata --\n# 'organization': {\n# 'name': 'Exempel AB',\n# 'display_name': [('Exempel AB','se'),('Example Co.','en')],\n# 'url':'http://www.example.com/ckan',\n# },\n# 'contact_person': [{\n# 'given_name':'John',\n# 'sur_name': 'Smith',\n# 'email_address': ['john.smith@example.com'],\n# 'contact_type': 'technical',\n# },\n# ],\n 'name_form': NAME_FORMAT_BASIC,\n \"xmlsec_binary\": '/usr/bin/xmlsec1',\n 'logger': {\n 'rotating': {\n 'filename': 'sp.log',\n 'maxBytes': 100000,\n 'backupCount': 5,\n },\n 'loglevel': 'debug',\n }\n}\n","sub_path":"ckanext/saml2/config/sp_config.py","file_name":"sp_config.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566944155","text":"from rest_framework import serializers\n\nfrom aerpay_main.models import Category, Coupon, FMCGProduct, FMCGTransaction, Product, QuantityType, Store, SubscriptionPrice\n\nclass SubscriptionPriceGetSrlzr(serializers.ModelSerializer):\n class Meta:\n model = SubscriptionPrice\n fields = ('id', 'new_price',)\n\nclass QuantityTypesGetSrlzr(serializers.ModelSerializer):\n class Meta:\n model = QuantityType\n fields = ('id', 'type_label',)\n\nclass StoreRegisterSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Store\n fields = ('email', 'help_desk_email',\n 'name', 'phone_number', 'image', 'base64Image', 'imageType', \n 'description', 'address', 'address_latitude', 'address_longitude', \n 'refered_by_store_referal_code',)\n\nclass StoreProductsSerializer(serializers.ModelSerializer):\n class Meta:\n model = Product\n fields = ('id', 'category', 'name', 'image', 'quantity_type', 'price', 'discounted_price', 'is_out_of_stock')\n\n def to_representation(self, instance):\n rep = super().to_representation(instance)\n rep['category'] = instance.category.name\n return rep\n\nclass StoreListSrlzr(serializers.ModelSerializer):\n products = serializers.SerializerMethodField()\n class Meta:\n model = Store\n fields = ('id','name', 'image', 'address', \n 'description', 'no_of_ratings', 'rating', 'products')\n \n def get_products(self, obj):\n selected_products = Product.objects.filter(\n category__store=obj).distinct()[0:5]\n return StoreProductsSerializer(selected_products, many=True).data\n\nclass StoreGetSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Store\n fields = ('id', 'email', 'help_desk_email',\n 'name', 'phone_number', 'image', 'base64Image', 'imageType', 'address', 'address_latitude', 'address_longitude', \n 'description', 'default_subscription_price', 'subscription_renewal_price', \n 'last_paid_subscription_date', 'subscription_renewal_date', \n 'refered_by_store_referal_code', 'own_referal_code', 'no_of_ratings', 'rating')\n\n\nclass StoreUpdateSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Store\n fields = ('email', 'help_desk_email',\n 'name', 'phone_number', 'image', 'base64Image', 'imageType', \n 'description', 'address', 'address_latitude', 'address_longitude',)\n\n\nclass CategoryMdlSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('id', 'name', 'image', 'base64Image', 'imageType')\n\nclass ProductCreateSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Product\n fields = ('category', 'name', 'image', 'base64Image', 'imageType', \n 'description', 'quantity_type', 'initial_quantity',\n 'price', 'discounted_price',)\n\nclass ProductGetSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Product\n fields = ('id', 'category', 'name', 'image', 'base64Image', 'imageType', 'description', 'quantity_type',\n 'initial_quantity', 'quantity_in_stock', 'price', 'discounted_price', \n 'is_out_of_stock')\n\n def to_representation(self, instance):\n rep = super().to_representation(instance)\n rep['category'] = CategoryMdlSrlzr(\n instance.category).data\n return rep\n\nclass ProductUpdateSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Product\n fields = ('category', 'name', 'image', 'base64Image', 'imageType', \n 'description', 'quantity_type',\n 'price', 'discounted_price',)\n\nclass RefillProductSrlzr(serializers.Serializer):\n new_quantity_in_stock = serializers.IntegerField()\n\nclass ProductDeleteSrlzr(serializers.Serializer):\n id = serializers.IntegerField()\n\nclass CategoryCreateSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('name', 'image', 'base64Image', 'imageType')\n\nclass CatProductsSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Product\n fields = ('id', 'name', 'image', 'description', 'quantity_type',\n 'quantity_in_stock', 'price', 'discounted_price', \n 'is_out_of_stock')\n\nclass CategoryGetSrlzr(serializers.ModelSerializer):\n products = CatProductsSrlzr(\n many=True, read_only=True)\n class Meta:\n model = Category\n fields = ('id', 'name', 'image', 'products')\n\nclass StoreUsrGetSrlzr(serializers.ModelSerializer):\n categories = CategoryGetSrlzr(\n many=True, read_only=True)\n class Meta:\n model = Store\n fields = ('id', 'email', 'help_desk_email',\n 'name', 'phone_number', 'image', 'address', 'address_latitude', 'address_longitude', \n 'description', 'no_of_ratings', 'rating', 'categories')\n\n\nclass CategoryUpdateSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('name', 'image', 'base64Image', 'imageType')\n\nclass CategoryDeleteSrlzr(serializers.Serializer):\n id = serializers.IntegerField()\n\nclass FMCGStrProductGetSrlzr(serializers.ModelSerializer):\n class Meta:\n model = FMCGProduct\n fields = ('id', 'name', 'image', 'description', 'quantity_type',\n 'quantity_in_stock', 'price', 'discounted_price', \n 'is_out_of_stock')\n\nclass FMCGTrnsctnCreateSrlzr(serializers.ModelSerializer):\n class Meta:\n model = FMCGTransaction\n fields = ('fmcg_product', \n 'quantity_taken_from_fmcg', 'total_cost_at_the_time')\n\nclass FMCGTrnsctnGetSrlzr(serializers.ModelSerializer):\n class Meta:\n model = FMCGTransaction\n fields = ('id', 'fmcg_product', 'transaction_occured_at', \n 'quantity_taken_from_fmcg', 'total_cost_at_the_time',)\n\n def to_representation(self, instance):\n rep = super().to_representation(instance)\n rep['fmcg_product'] = FMCGStrProductGetSrlzr(\n instance.fmcg_product).data\n return rep\n\nclass CouponGnrtSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Coupon\n fields = ('category', 'product',\n 'minimum_order_Rs', 'discount_type',\n 'discount_amount', 'uses_per_customer')\n\nclass CouponGetSrlzr(serializers.ModelSerializer):\n class Meta:\n model = Coupon\n fields = ('id', 'category', 'product', 'code',\n 'minimum_order_Rs', 'discount_type',\n 'discount_amount', 'uses_per_customer')\n \nclass CouponDeleteSrlzr(serializers.Serializer):\n id = serializers.IntegerField()\n\n","sub_path":"aerpay_main/store_serializers.py","file_name":"store_serializers.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"328816868","text":"import numpy as np\nfrom numpy.linalg import inv\n\nm_ = np.matmul\nmprod_ = m_\n\ndef _kfi(xp, uxp, m, um, h, f = None, q = None):\n #if (f is not None): print('---')\n #else: print ('xxx')\n size = len(xp)\n f = f if f is not None else np.identity(size)\n xi = mprod_(f, xp.T)\n #print('f xp ', xi)\n q = np.zeros(size * size).reshape(size, size) if q is None else q\n #print(' qi ', q)\n uxi = mprod_(f, mprod_(uxp, f.T)) + q\n ide = np.identity(size)\n #h2 = h2 if h2 is not None else 0. * h\n res = m - mprod_(h, xi.T) # - mprod_(h2, xi.T)\n #print('xi ', xi.T)\n #print('h ', h)\n #print('h xi ', mprod_(h, xi.T))\n #print('res ', res)\n k = np.matmul(mprod_(uxi, h.T), inv(mprod_(h, mprod_(uxi, h.T)) + um))\n #print('k ', k)\n x = xi + mprod_(k, res.T)\n #print(' k res ', mprod_(k, res.T))\n #print('x ', x)\n ux = mprod_((ide - mprod_(k, h)), uxi)\n #print('cov ', cov)\n return x, ux, res, k\n\ndef _kfs(ms, ums, hs, x0, ux0 = None, fs = None, qs = None):\n nsample, msize, ssize = len(ms), len(ms[0]), len(x0)\n ux0 = 1e4 * np.identity(ssize) if ux0 is None else ux0\n xs = [x0 for ii in range(nsample)]\n uxs = [np.identity(ssize) for ii in range(nsample)]\n res = [np.zeros(msize) for ii in range(nsample)]\n fs = [np.identity(ssize) for ii in range(nsample)] if fs is None else fs\n qs = [0.* fi for fi in fs] if qs is None else qs\n for i in range(nsample):\n xp, uxp = x0, ux0\n if (i >= 1):\n xp, uxp = xs[i-1], uxs[i-1]\n xi, uxi, resi, _ = _kfi(xp, uxp, ms[i], ums[i], hs[i], f = fs[i], q = qs[i])\n xs[i], uxs[i], res[i] = xi, uxi, resi\n return xs, uxs, res\n\n\ndef _kfs(xi, xi1, xi1p, ui, ui1p, ui1, fi = None):\n size = len(xs)\n fi = fi if fi is not None else np.identity(size)\n ak = mprod_(ui, mprod_(fi.T, inv(uip)))\n xis = xi + mprod_(ai, (xi1 - xi1p))\n uis = ui + mprod_(ai, ui1p - ui1p)\n print('Ak ', ak)\n print('xk ', xis)\n return xis,\n\nclass KFnode:\n\n names = ['xp', 'uxp', 'k', 'res']\n names += ['xm', 'uxm', 'a', 'xs', 'uxs']\n\n def __init__(self, m = None, um = None, h = None, f = None, q = None):\n for name in KFnode.names:\n setattr(self, name, None)\n self.m = m\n self.um = um\n self.h = h\n self.f = f\n self.q = q\n return\n\ndef kfilter(kfnodes, x0, ux0):\n\n nsize = len(kfnodes)\n msize = len(x0)\n\n _kfstep = _kfstep_m\n\n def _kfnode0(x0, ux0):\n k0 = KFnode()\n k0.xm = x0\n k0.uxm = ux0\n k0.f = np.identity(msize)\n k0.q = 0. * np.identity(msize)\n return k0\n\n k0 = _kfnode0(x0, ux0)\n kfnodes[0] = _kfstep(k0, kfnodes[0])\n for i in range(1, nsize):\n #print('i-node ', i)\n _kfstep(kfnodes[i-1], kfnodes[i])\n\n return kfnodes\n\ndef kfsmooth(kfnodes):\n nsize = len(kfnodes)\n\n def _klast(kn):\n kn.xs = kn.xm\n kn.uxs = kn.uxm\n return kn\n\n _klast(kfnodes[-1])\n\n for i in range(nsize-2, -1, -1):\n #print('back-step ', i)\n _kfback(kfnodes[i], kfnodes[i+1])\n\n return kfnodes\n\ndef _kfstep_m(kip, ki):\n\n #print('x0 ', kip.xm)\n #print('ux0 ', kip.uxm)\n #print('f0 ', kip.f)\n #print('q0 ', kip.q)\n\n ki.xp = m_(kip.f, kip.xm.T)\n #print('xp :', ki.xp)\n ki.uxp = m_(kip.f, m_(kip.uxm, kip.f.T)) + kip.q\n #print('uxp :', ki.uxp)\n\n ki.res = ki.m - m_(ki.h, ki.xp.T)\n #print('res ', ki.res)\n\n ki.uxm = inv(inv(ki.uxp) + m_(ki.h.T, m_(ki.um, ki.h)))\n #print('um : ', ki.um)\n #print('uxm : ', ki.uxm)\n ki.xm = m_(ki.uxm, m_(inv(ki.uxp), ki.xp) + m_(ki.h.T, m_(ki.um, ki.m.T)))\n #print('xm : ', ki.xm)\n\n return ki\n\ndef _kfstep_k(kip, ki):\n\n #print('x0 ', kip.xm)\n #print('ux0 ', kip.uxm)\n #print('f :', kip.f)\n #print('q :', kip.q)\n\n ki.xp = m_(kip.f, kip.xm.T)\n ki.uxp = m_(kip.f, m_(kip.uxm, kip.f.T)) + kip.q\n #print('xp : ', ki.xp)\n #print('uxp : ', ki.uxp)\n\n ki.res = ki.m - m_(ki.h, ki.xp.T)\n ki.k = m_( m_(ki.uxp, ki.h.T), inv(m_(ki.h, m_(ki.uxp, ki.h.T)) + ki.um))\n #print('res : ', ki.res)\n #print('k : ', ki.k)\n\n ide = np.identity(len(ki.xp))\n ki.xm = ki.xp + m_(ki.k, ki.res.T)\n ki.uxm = m_((ide - m_(ki.k, ki.h)), ki.uxp)\n #print('xm : ', ki.xm)\n #print('uxm : ', ki.uxm)\n\n return ki\n\n\ndef _kfback(kip, ki):\n #print('fT-1 ', kip.f.T)\n #print('Cp ', ki.uxp)\n #print('Cm-1 ', kip.uxm)\n kip.a = m_(kip.uxm, m_(kip.f.T, inv(ki.uxp)))\n #print('A ', kip.a)\n kip.xs = kip.xm + m_(kip.a, (ki.xs - ki.xp).T)\n kip.uxs = kip.uxm + m_(kip.a, m_(ki.uxs - ki.uxp, kip.a.T))\n return ki\n\n#------\n\ndef _delta(xs, type = float):\n #dxs[1:] = dxs[1:] - xs[:-1]\n #dxs = np.array(dxs, dtype = type)\n axs = np.array(xs)\n dxs = axs[1:] - axs[:-1]\n return dxs\n\ndef _delta_ms(cs, ufactor = 2., umin = 2.4):\n size = len(cs[0])\n ms = _delta(cs)\n ums = [np.identity(size) * ufactor * np.maximum(np.sqrt(np.abs(ci)), umin) for ci in cs]\n return ms, ums\n\ndef _hs(ts, cs, N, hi_):\n dts = _delta(ts)\n hs = [hi_(ci, dt, N) for dt, ci in zip(dts, cs[:-1])]\n return hs\n\ndef _delta_kfs(ts, cs, x0, N, hi_, full_output = False):\n ms, ums = _delta_ms(cs)\n hs = _hs(ts, cs, N, hi_)\n xs, uxs, res = _kfs(ms, ums, hs, x0)\n result = (xs, uxs, res, ms, ums, hs) if full_output else (xs, uxs)\n return result\n\ndef _rvs(cs):\n nsample, size = len(cs), len(cs[0])\n n0 = np.random.poisson(np.abs(cs[0]))\n ns = [n0,]\n for i in range(1, nsample):\n dci = cs[i] - cs[i-1]\n nip = ns[i-1]\n sig = np.ones(size)\n sig[dci < 0 ] = -1.\n dni = sig * np.random.poisson(np.abs(dci))\n ni = nip + dni\n ns .append(ni)\n return ns\n\ndef _hrvs(N, x0, ci0, hi_, t0 = 0, dt = 0.5, nsamples = 200):\n size = len(ci0)\n ts = [t0 + i * dt for i in range(nsamples)]\n cis = [ci0,]\n for i in range(1, nsamples):\n cip = cis[i-1]\n # #print('cip', cip)\n hi = hi_(cip, dt, N)\n # #print('hi ', hi)\n dci = np.matmul(hi, x0.T)\n # #print('dci ', dci)\n ci = cip + dci\n cis .append(ci)\n nis = _rvs(cis)\n return ts, cis, nis\n\n\n#\n# Specific KF\n#\n\n\n#\n# Extende\n#-----\n\ndef sirm_fi(si, xi, dt, N):\n f = np.identity(4)\n s = (N - np.sum(si))/N\n ni, nid = si[0], xi[4]\n f = np.identity(4)\n f[4, 1], f[4, 4] = s * ni * dt, nid * dt\n return f\n\ndef sirm_hi(si, xi, dt, N):\n h = np.zeros( 3 * 5).reshape(3, 5)\n s = (N - np.sum(si))/N\n ni, nid = si[0], xi[4]\n h[0, 0 ], h[0, 2] = s * ni, nid - ni\n h[1, 2] = -nid + ni\n h[2, 3] = nid\n return dt * h\n\n\ndef sirm_hv(s0 = (1, 0, 0), x0 = (0.6, 0.06, 0.2, 0.2), dt = 1, N = 1e6, nsamples = 100):\n ts, xs, ss = [], [], []\n for i in range(nsamples):\n ti = i * dt\n sip, xip = s0, x0 if i == 0 else xs[i-1], ss[i-1]\n fi = sirm_fi(sip, xip, dt, N)\n xi = mprod_(fi, x0.T)\n hi = sirm_hi(sip, xip, dt, N)\n si = mprod_(hi, x0.T)\n ss.append(si); xs.append(xi)\n return ts, xs, ss\n\n\n#\n#\n#-------\n\ndef sirm_hi(ci, dt, N):\n size = 3\n ni, nr, nd = ci[0], ci[1], ci[2]\n h = np.zeros(size * size).reshape(size, size)\n si = N - np.sum(ci)\n h[0, 0], h[0, 1], h[0, 2] = si/N, -1., -1.\n h[1, 1] = 1.\n h[2, 2] = 1.\n h = h * dt * ni\n return h\n\ndef sirm_rvs(N, x0, s0 = np.array((1, 0, 0)), **kargs):\n return _hrvs(N, x0, s0, sirm_hi, **kargs)\n\ndef sirm_kf(ts, cs, x0, N, full_output = False, **kargs):\n return _delta_kfs(ts, cs, x0, N, sirm_hi, full_output, **kargs)\n #ms, ums = delta_ms(cs)\n #hs = hs_(ts, cs, N, sirm_hi)\n #xs, uxs, res = _kfs(ms, ums, hs, x0, N, **kargs)\n #result = (xs, uxs, res, ms, ums, hs) if full_output else (xs, uxs)\n #return result\n\n#\n# SIM Model\n#\n\ndef sir_hi(ci, dt, N):\n size = 2\n ni, nr = ci[0], ci[1]\n h = np.zeros(size * size).reshape(size, size)\n si = N - np.sum(ci)\n h[0, 0], h[0, 1] = si/N, -1., -1\n h[1, 2] = 1.\n h = h * dt * ni\n return h\n\ndef sir_rvs(N, x0, s0 = np.array((1, 0, 0)), **kargs):\n return _hrvs(N, x0, s0, sirm_hi, **kargs)\n\ndef sir_kf(ts, cs, x0, N, full_output = False, **kargs):\n return _delta_kfs(ts, cs, x0, N, sir_hi, full_output, **kargs)\n# ms, ums = _delta_ms(cs)\n# hs = _hs(ts, cs, N, sir_hi)\n# xs, uxs, res = _kfs(ms, ums, hs, x0, N, **kargs)\n# result = (xs, uxs, res, ms, ums, hs) if full_output else (xs, uxs)\n# return result\n\n#\n\n#\n# SIR Model\n#\n\n# def sir_hi(ci, dt, N):\n# size = 2\n# ni, nr = ci[0], ci[1]\n# h = np.zeros(size * size).reshape(size, size)\n# si = N - np.sum(ci)\n# h[0, 0], h[0, 1] = si/N, -1.\n# h[1, 1] = 1.\n# h = h * dt * ni\n# return h\n#\n# def sir_rvs(N, x0, **kargs):\n# ci = np.array((1, 0))\n# return _hrvs(N, x0, ci, sir_hi, **kargs)\n#\n# def sir_kf(ts, cs, x0, N, full_output = False, **kargs):\n# ms, ums = delta_ms(cs)\n# hs = hs_(ts, cs, N, sir_hi)\n# xs, uxs, res = _kfs(ms, ums, hs, x0, N, **kargs)\n# result = (xs, uxs, res, ms, ums, hs) if full_output else (xs, uxs)\n# return result\n\n#\n# SEIR model\n#\n\ndef seir_hi(ci, dt, N):\n size = 3\n ne, ni, nr = ci[0], ci[1], ci[2]\n si = N - np.sum(ci)\n h = np.zeros(size * size).reshape(size, size)\n h[0, 0], h[0, 2] = ni * si/N, -ne\n h[1, 1], h[1, 2] = -ni , ne\n h[2, 1] = ni\n h = h * dt\n return h\n\ndef seir_rvs(N, x0, ci = (1, 1, 0), **kargs):\n ci = np.array(ci)\n return _hrvs(N, x0, ci, seir_hi, **kargs)\n\n\ndef seir_kf(ts, cs, x0, N, full_output = False, **kargs):\n ms, ums = delta_ms(cs)\n hs = hs_(ts, cs, N, seir_hi)\n xs, uxs, res = _kfs(ms, ums, hs, x0, N, **kargs)\n result = (xs, uxs, res, ms, ums, hs) if full_output else (xs, uxs)\n return result\n\n#\n# SEIR2 model\n#\n\ndef seir2_hi(ci, dt, N):\n ne, ni, nr, nd = ci[0], ci[1], ci[2], ci[3]\n si = N - np.sum(ci)\n h = np.zeros(4 * 5).reshape(4, 5)\n h[0, 0], h[0, 2] = ni * si/N, -ne\n h[1, 1], h[1, 2] = -ni , ne\n h[2, 1], h[2, 3] = ni , -ni\n h[3, 3], h[3, 4] = ni , -nd\n h = h * dt\n return h\n\n\ndef seir2_rvs(N, x0, ci = (1, 1, 0, 0), **kargs):\n ci = np.array(ci)\n return _hrvs(N, x0, ci, seir2_hi, **kargs)\n\n\ndef seir2_kf(ts, cs, x0, N, full_output = False, **kargs):\n ms, ums = delta_ms(cs)\n hs = hs_(ts, cs, N, seir2_hi)\n xs, uxs, res = _kfs(ms, ums, hs, x0, N, **kargs)\n result = (xs, uxs, res, ms, ums, hs) if full_output else (xs, uxs)\n return result\n\n\n\n#\n# SIR2 no-exposed model\n#\n\ndef sir2_hi(ci, dt, N):\n ni, nr, nd = ci[0], ci[1], ci[2]\n si = N - np.sum(ci)\n h = np.zeros(3 * 4).reshape(3, 4)\n h[0, 0], h[0, 1] = ni * si/N, -ni\n h[1, 1], h[1, 2] = ni , -ni\n h[2, 2], h[2, 3] = ni , -nd\n h = h * dt\n return h\n\n\ndef sir2_rvs(N, x0, ci = (1, 0, 0), **kargs):\n ci = np.array(ci)\n return _hrvs(N, x0, ci, sir2_hi, **kargs)\n\n\ndef sir2_kf(ts, cs, x0, N, full_output = False, **kargs):\n ms, ums = delta_ms(cs)\n hs = hs_(ts, cs, N, sir2_hi)\n xs, uxs, res = _kfs(ms, ums, hs, x0, N, **kargs)\n result = (xs, uxs, res, ms, ums, hs) if full_output else (xs, uxs)\n return result\n\n#\n# SIR2 completed with death\n#\n\ndef sir2c_hi(ci, dt, N):\n ni, nr, nd, nm = ci[0], ci[1], ci[2], ci[3]\n si = N - np.sum(ci)\n h = np.zeros(4 * 4).reshape(4, 4)\n h[0, 0], h[0, 1] = ni * si/N, -ni\n h[1, 1], h[1, 2] = ni , -ni\n h[2, 2], h[2, 3] = ni , -nd\n h[3, 3] = nd\n h = h * dt\n return h\n\n\ndef sir2c_rvs(N, x0, ci = (1, 0, 0, 0), **kargs):\n ci = np.array(ci)\n return _hrvs(N, x0, ci, sir2c_hi, **kargs)\n\n\ndef sir2c_kf(ts, cs, x0, N, full_output = False, **kargs):\n ms, ums = delta_ms(cs)\n hs = hs_(ts, cs, N, sir2c_hi)\n xs, uxs, res = _kfs(ms, ums, hs, x0, N, **kargs)\n result = (xs, uxs, res, ms, ums, hs) if full_output else (xs, uxs)\n return result\n\n#\n# Chainned KF\n#\n#\n\ndef sirm_xhi(sp, dt, sf):\n ni, nr, nm = sp[0], sp[1], sp[2]\n h = np.zeros(3 * 3).reshape(3, 3)\n h[0, 0], h[0, 1], h[0, 2] = ni * sf, -ni, -ni\n h[1, 1] = ni\n h[2, 2] = ni\n h = h * dt\n return h\n\ndef sirm_sfi(xi, dt, sf):\n beta, gamma, rho = xi[0], xi[1], xi[2]\n f = np.zeros(3 * 3).reshape(3, 3)\n f[0, 0] = sf * beta - gamma\n f[1, 0] = gamma - rho\n f[2, 0] = rho\n f = np.identity(3) + f * dt\n return f\n\ndef _extrapolate(ts, ss, xs, N, sfi_):\n\n sps = []\n for i in range(1, len(ss)):\n dt, si, xi = ts[i] - ts[i-1], ss[i-1], xs[i-1]\n sf = (N - np.sum(si))/N\n sfi = sfi_(xi, dt, sf)\n spi = mprod_(sfi, si.T)\n #print('si ', si)\n #print('dt ', dt, 'xi', xi)\n #print('fi ', sfi)\n #print('spi', spi)\n sps.append(spi)\n return sps\n\n\ndef _delta_ckfs(ts, cs, x0, s0, N, xhi_, sfi_, sh = None, sigma = 100, **kargs):\n csize, ssize, xsize = len(cs[0]), len(s0), len(x0)\n #ucs = np.random.poisson(np.sqrt(cs))\n ms, ums = _delta_ms(cs)\n ssize, xsize = len(s0), len(x0)\n shi = sh if sh is not None else np.identity(ssize)\n #hp = np.zeros(2 * 3).reshape(2, 3)\n #hp[0, 0], hp[1, 2] = 1, 1\n ux0 = sigma * sigma * np.identity(xsize)\n us0 = sigma * sigma * np.identity(ssize)\n xs, uxs, xrs = [x0,], [ux0,], []\n ss, uss, srs = [s0,], [us0,], []\n #for i in range(1, 20): # len(ms)):\n for i in range(1, len(ms)):\n ci, uci = cs[i] , np.identity(csize) * np.sqrt(np.maximum(1, cs[i]))\n mi, umi = ms[i] , ums[i-1]\n xp, uxp = xs[i-1], uxs[i-1]\n sp, usp = ss[i-1], uss[i-1]\n # Move first the samples\n dt = ts[i] - ts[i-1]\n sf = (N - np.sum(sp))/N\n sfi = sfi_(xp, dt, sf)\n usp = usp * (np.sqrt(2) ** 2)\n si, usi, sri, _ = _kfi(sp, usp, ci, uci, shi, sfi)\n si = np.maximum(si, 0.)\n si = np.minimum(si, N)\n # Now the state\n # Use the true values\n # sp = cp -\n dt = ts[i] - ts[i-1]\n sf = (N - np.sum(si))/N\n xhi = mprod_(shi, xhi_(si, dt, sf))\n xi, uxi, xri, _ = _kfi(xp, uxp, mi, umi, xhi)\n xi = np.maximum(xi, 0.)\n #print('ci ', ci)\n #print('sp ', sp)\n #print('si-p', mprod_(sfi, sp))\n #print('si ', si)\n xs.append(xi); uxs.append(uxi); xrs.append(xri)\n ss.append(si); uss.append(usi); srs.append(sri)\n return (xs, uxs, xrs), (ss, uss, srs)\n#\n#\n\n\n#\n# def model_h(ci, dt, N):\n# h\n# P * h, (1- P)* h\n# return h\n#\n# def model_rvs()\n#\n#\n# def _model_kfi(sp, xp, uxp, mi, umi):\n# h = model_hi(sp, dt, N):\n#\n# si = h * xp\n#\n#\n#\n# def model_kf(ts, cs, c0, N, full_output = False, **kargs):\n# nsample = len(cs)\n# ms, ums = delta_ms(cs)\n# for i in range(1, nsample):\n# mi, umi = ms[i], umi[i]\n# sp, xp, uxp = ss[i], xs[i], uxp[i]\n# si, xi, uxi, res = _model_kfi(xp, uxp, sp, mi, umi)\n#\n#\n# #\n# #\n# #\n#\n#\n# #---------\n#\n# #\n# # def kf_hssir_ms(ts, cs, N):\n# #\n#\n# def kf_kfilter(ts, nis, x0, N, mifun, hifun, sigma = 100., ufactor = 1., full_output = False):\n# nsample, size, msize = len(ts), len(x0), len(nis)\n# dt = ts[1] - ts[0]\n# ux0 = np.identity(size)*sigma*sigma\n# xs = [x0 for ii in range(nsample)]\n# uxs = [np.identity(size) for ii in range(nsample)]\n# res = [np.zeros(size) for ii in range(nsample)]\n# #hmatrix = hmatrix[model]\n# ms = _delta(nis)\n# ums = [np.identity(msize) * np.abs(ms) * ufactor]\n# hi_ = models[model]\n# hs = [hi_(ni, dt, N) for ni in nis]\n# for i in range(nsample):\n# xp, uxp = x0, ux0\n# if (i >= 1):\n# xp, uxp = xs[i-1], uxs[i-1]\n# xi, uxi, resi, _ = _kfilter(xp, uxp, ms[i], ums[i], hs[i])\n# xs[i], uxs[i], res[i] = xi, uxi, resi\n# result = (xs, uxs) if full_output is False else (xs, uxs, ms, ums, res)\n# return result\n#\n#\n# def kf_kfilter(ts, cs, x0, N, model = 'seir2', sigma = 100., ufactor = 2., full_output = False):\n# nsample, size = len(ts), len(x0)\n# ux0 = np.identity(size)*sigma*sigma\n# xs = [x0 for ii in range(nsample)]\n# uxs = [np.identity(size) for ii in range(nsample)]\n# res = [np.zeros(size) for ii in range(nsample)]\n# #hmatrix = hmatrix[model]\n# ms, ums = kf_measurements(ts, cs)\n# ms [-1] = cs[-1]\n# for i in range(nsample):\n# ums[-1][4, 4] = mp.sqrt(np.maximum(ms[-1][i], 2.4))\n# hs = kf_hmatrices_seir2(ts, cs, N)\n# for i in range(nsample):\n# xp, uxp = x0, ux0\n# if (i >= 1):\n# xp, uxp = xs[i-1], uxs[i-1]\n# xi, uxi, resi, _ = _kfilter(xp, uxp, ms[i], ums[i], hs[i])\n# xs[i], uxs[i], res[i] = xi, uxi, resi\n# result = (xs, uxs) if full_output is False else (xs, uxs, ms, ums, hs, res)\n# return result\n","sub_path":"c19/kfilter.py","file_name":"kfilter.py","file_ext":"py","file_size_in_byte":17428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"362689914","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\nfrom google.appengine.ext import ndb\nfrom gaecookie.decorator import no_csrf\nfrom gaeforms import base\nfrom gaeforms.base import Form\nfrom gaeforms.ndb.form import ModelForm\nfrom gaegraph.model import Node\nfrom gaepermission.decorator import login_not_required,login_required\nfrom config.template_middleware import TemplateResponse\nfrom tekton import router\nfrom tekton.gae.middleware.redirect import RedirectResponse\nfrom gaegraph.model import Arc\n\n\n# CRUD\n\n@login_required\n@no_csrf\ndef index():\n\n query = Noticias.query().order(Noticias.nome)\n noticia_lista = query.fetch()\n\n form = NoticiasForm()\n noticia_lista=[form.fill_with_model(noticias) for noticias in noticia_lista]\n\n editar_form_path = router.to_path(editar_form)\n\n delete_path = router.to_path(delete)\n\n for noticias in noticia_lista:\n noticias['edit_path']='%s/%s'%(editar_form_path,noticias['id'])\n noticias['delete_path'] = '%s/%s' % (delete_path,noticias['id'])\n contexto = {'noticias_lista':noticia_lista}\n\n return TemplateResponse(contexto)\n\n\n@no_csrf\n@login_required\ndef editar_form(categoria_id):\n categoria_id=int(categoria_id)\n categoria = Noticias.get_by_id(categoria_id)\n\n categoria_form = NoticiasForm()\n categoria_form.fill_with_model(categoria)\n\n # teste\n erros = categoria_form.validate()\n # teste\n #teste\n\n contexto = {'salvar_path': router.to_path(editar,categoria_id),\n 'erros': erros,\n 'noticias' : categoria_form}\n\n\n return TemplateResponse(contexto,router.to_path('/noticias/home.html'))\n\n\n@login_required\ndef delete(categoria_id):\n chave = ndb.Key(Noticias,int(categoria_id))\n chave.delete()\n return RedirectResponse(router.to_path(index))\n\n\n@login_required\n@no_csrf\ndef editar(categoria_id,**propriedades):\n categoria_id = int(categoria_id)\n categoria = Noticias.get_by_id(categoria_id)\n\n categoria_form = NoticiasForm(**propriedades)\n\n erros = categoria_form.validate()\n\n if erros:\n contexto = {'salvar_path': router.to_path(salvar),\n 'erros': erros,\n 'noticias' : categoria_form}\n return TemplateResponse(contexto,'/noticias/home.html')\n\n else:\n categoria_form.fill_model(categoria)\n\n categoria.put()\n return RedirectResponse(router.to_path(index))\n #feito para mostrar o que esta sendo salvo no banco\n\n\n##################\n@login_required\n@no_csrf\ndef salvar(**propriedades):\n categorias_form = NoticiasForm(**propriedades)\n erros = categorias_form.validate()\n if erros:\n contexto = {'salvar_path': router.to_path(index),\n 'erros': erros,\n 'noticias' : categorias_form}\n return TemplateResponse(contexto,'/noticias/home.html')\n\n else:\n categorias=categorias_form.fill_model()\n\n categorias.put()\n\n return RedirectResponse(router.to_path('/noticias_listar'))\n #feito para mostrar o que esta sendo salvo no banco\n#####################\n\n\n\n# Modelos\nclass Noticias(Node):\n nome = ndb.StringProperty(required=True)\n descricao = ndb.StringProperty()\n\nclass NoticiasForm(ModelForm):\n _model_class = Noticias\n _include = [Noticias.nome,Noticias.descricao]","sub_path":"backend/appengine/routes/noticias_listar/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583557212","text":"from glob import iglob\nimport os\nimport requests\nimport pymongo\nimport os.path\nfrom pymongo import MongoClient\nimport json\nfrom py2neo import Graph,Path,authenticate,Node,Relationship\n\ndef commoncount(list1,list2):\n count = 0\n for element in list1:\n if element in list2:\n count +=1\n return count\n\nauthenticate(\"localhost:7474\",\"neo4j\",\"haha\")\ngraph = Graph(\"http://localhost:7474/db/data/\")\narray = []\ni=0\nfor fname in iglob(os.path.expanduser('test/*.json')):\n with open(fname) as fin:\n videos = json.load(fin)\n array.append(videos)\n stats = videos['videoInfo']['statistics']\n node = Node(\"Video\",id = videos['videoInfo']['id'], commentCount = stats['commentCount'], viewCount = stats['viewCount'], favoriteCount = stats['favoriteCount'], likeCount = int(stats['likeCount']) , dislikeCount = stats['dislikeCount'])\n graph.create(node)\nprint(\"Nodes Finished\")\n\nfor i in range(len(array)):\n temp = array[i]['videoInfo']\n for j in range(i-1,-1,-1):\n dup = array[j]['videoInfo']\n a = graph.find_one(\"Video\",property_key = 'id', property_value = temp['id'])\n b = graph.find_one(\"Video\",property_key = 'id', property_value = dup['id'])\n if temp['snippet']['channelId'] == dup['snippet']['channelId']:\n crelation = Relationship(a,\"samechannel\",b, weight=5)\n graph.create(crelation)\n\n dcount = 1.5*commoncount(temp['snippet']['description'].split(),dup['snippet']['description'].split())\n if dcount != 0:\n drelation = Relationship(a , \"similardescription\" , b , weight = dcount)\n graph.create(drelation)\n\n if 'tags' in temp['snippet'] and 'tags' in dup['snippet']:\n tcount = 4*commoncount(temp['snippet']['tags'],dup['snippet']['tags'])\n if tcount != 0:\n trelation = Relationship(a, \"similartags\", b, weight = tcount)\n graph.create(trelation)\n\n ccount=10*commoncount(temp['snippet']['title'].split(),dup['snippet']['title'].split())\n if ccount != 0:\n crelation = Relationship(a , \"similardescription\" , b , weight = ccount)\n graph.create(crelation)\n print(i)\n\n\nprint(\"Neo4j...Finish\")\n\n# match (n)-[r]-(m) where n.id='5zG6AagUQBY' return m.id,r.weight order by r.weight desc limit 5;\n\nconnection = MongoClient()\ndb = connection.videos\nvideos = db.videos\n\nfor fname in iglob(os.path.expanduser('test/*.json')):\n with open(fname) as fin:\n videos = json.load(fin)\n title= videos['videoInfo']['snippet']['title']\n desc=videos['videoInfo']['snippet']['description']\n videos['title']=title\n videos['desc']=desc\n likeCount=videos['videoInfo']['statistics']['likeCount']\n videos['likeCount']=int(likeCount)\n del videos['videoInfo']['statistics']['likeCount']\n del videos['videoInfo']['snippet']['title']\n del videos['videoInfo']['snippet']['localized']['title']\n del videos['videoInfo']['snippet']['localized']['description']\n del videos['videoInfo']['snippet']['description']\n if 'tags' in videos['videoInfo']['snippet']:\n blah=videos['videoInfo']['snippet']['tags']\n videos['tags']=blah\n del videos['videoInfo']['snippet']['tags']\n ids=db.videos.insert(videos)\n#db.videos.createIndex( { title: \"text\", desc: \"text\", tags:\"text\" }, { weights: { title: 20, tags:4, desc: 2 }, name: \"TextIndex\" } )\n","sub_path":"myDbShit/NOSQL.py","file_name":"NOSQL.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"23940596","text":"def bellman_ford(vertices, edges, start, limit):\n distances = [float('inf')] * vertices\n distances[start] = 0\n for i in range(limit):\n tmp = list(distances)\n for (vertex_from, vertex_to, weight) in edges:\n if distances[vertex_to] > tmp[vertex_from] + weight:\n distances[vertex_to] = tmp[vertex_from] + weight\n return distances\n\n\nif __name__ == '__main__':\n with open('input.txt', 'r') as file:\n vertices, start, finish, limit = map(int, file.readline().split())\n adj_matrix = []\n for _ in range(vertices):\n adj_matrix.append(list(map(int, file.readline().split())))\n edges = []\n for i in range(vertices):\n for j in range(vertices):\n if adj_matrix[i][j] != -1:\n edges.append((i, j, adj_matrix[i][j]))\n distances = bellman_ford(vertices, edges, start, limit)\n print(distances[finish] if distances[finish] != float('inf') else -1)\n\n","sub_path":"bellman_ford.py","file_name":"bellman_ford.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"382288487","text":"# -*- coding: utf-8 -*-\nimport timeit\nimport sys\nimport io\nimport uuid\nimport random\n\nfrom ctools import *\n\n\ndef humanize(t):\n if t > 1:\n return \"%.3f s\" % t\n t *= 1000\n if t > 1:\n return \"%.3f ms\" % t\n t *= 1000\n if t > 1:\n return \"%.3f µs\" % t\n t *= 1000\n return \"%.3f ns\" % t\n\n\ndef mean_std(seq):\n mean = sum(seq) / len(seq)\n return mean, sum((x - mean) ** 2 for x in seq) ** 0.5\n\n\nbuffer = io.StringIO()\n\n\ndef run_str(run, title, loop=1000000, repeat=10, **kwargs):\n t_arr = timeit.repeat(run, globals=globals(), number=loop, repeat=repeat, **kwargs)\n t_arr = [t / loop for t in t_arr]\n mean, std = mean_std(t_arr)\n print(\n title, \",\\t\", humanize(mean), \" ± \", humanize(std),\n \"each ({:,} runs, {:,} loops)\".format(repeat, loop),\n sep=\"\", flush=True, file=sys.stderr\n )\n\n\nrun_str(\"int8_to_datetime(20170101)\", 'int8_to_datetime')\n\nrad = random.randint(0, 0xffffffff)\n\nrun_str(\n \"jump_consistent_hash(65535, 1024)\",\n \"jump_consistent_hash\",\n setup=\"rad = random.randint(0, 0xffffffff)\"\n)\n\nstring = str(uuid.uuid1())\nrun_str(\"strhash(string)\", \"strhash default\", setup=\"string = str(uuid.uuid1())\")\nrun_str(\"strhash(string, 'fnv1a')\", \"strhash fnv1a\", setup=\"string = str(uuid.uuid1())\")\nrun_str(\"strhash(string, 'fnv1')\", \"strhash fnv1\", setup=\"string = str(uuid.uuid1())\")\nrun_str(\"strhash(string, 'djb2')\", \"strhash djb2\", setup=\"string = str(uuid.uuid1())\")\nrun_str(\"strhash(string, 'murmur')\", \"strhash murmur\", setup=\"string = str(uuid.uuid1())\")\n","sub_path":"benchmarks/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"44609669","text":"from setuptools import setup, find_packages\n\nfrom helm_upgrade import __version__\n\n# Source dependencies from requirements.txt file.\nwith open(\"requirements.txt\", \"r\") as f:\n lines = f.readlines()\n install_packages = [line.strip() for line in lines]\n\nsetup(\n name=\"helm_upgrade\",\n version=__version__,\n install_requires=install_packages,\n include_package_data=True,\n python_requires=\">=3.7\",\n author=\"Sarah Gibson\",\n author_email=\"drsarahlgibson@gmail.com\",\n url=\"https://sgibson91.github.io/\",\n # this should be a whitespace separated string of keywords, not a list\n keywords=\"development helm dependencies\",\n description=\"Update the dependencies of a helm chart to the latest published versions.\", # noqa: E501\n long_description=open(\"./README.md\", \"r\").read(),\n long_description_content_type=\"text/markdown\",\n license=\"MIT\",\n packages=find_packages(),\n use_package_data=True,\n entry_points={\"console_scripts\": [\"helm-upgrade = helm_upgrade.cli:main\"]},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"117684988","text":"from django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .models import Point_type, Point\n\n\nclass PointAdmin(admin.ModelAdmin):\n \"\"\"\n Settings for Point section in admin.\n \"\"\"\n list_display = ('name', 'code', 'point_type', 'address')\n list_display_links = ('name', 'address')\n list_filter = ('point_type',)\n search_fields = ('name', 'code')\n\n def get_readonly_fields(self, request, obj=None):\n if obj:\n return ['code']\n else:\n return []\n\n\nclass PointtypeAdmin(admin.ModelAdmin):\n \"\"\"\n Settings for Point type section in admin.\n \"\"\"\n list_display = ('name', 'description', 'points_count')\n search_fields = ('name',)\n\n def points_count(self, obj):\n return obj.points.count()\n points_count.short_description = _('points count')\n\n\nadmin.site.register(Point_type, PointtypeAdmin)\nadmin.site.register(Point, PointAdmin)\n","sub_path":"points/pointsapp/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"89645784","text":"\nimport logging\nfrom copy import deepcopy\nimport random\n\nimport new_utility_functions\nimport main\nimport players\nimport games\nimport clot\n\n\n\ndef createGames_RoundRobin(tourney_id, tourney_clotconfig):\n\t\"\"\"This is called periodically to check for new games that need to be created.\n\tthe roundrobin part is that we want everyone to play everyone else.\n\tso the players not currently in games are just paired up with each other,\n\tso long as they have not yet played each other.\n\t\"\"\"\n\tlogging.info('')\n\tlogging.info('in createGames_RoundRobin()')\n\n\tif main.hasTourneyFinished(tourney_id, tourney_clotconfig):\n\t\tlogging.info('round robin tourney has finished')\n\t\treturn\n\n\t#Retrieve all games that are ongoing\n\tactiveGames = list(games.Game.all().filter(\"winner =\", None).filter(\"tourney_id =\", tourney_id)) ###.run(batch_size=1000))\n\tactiveGameIDs = dict([[g.key().id(), g] for g in activeGames])\n\t#logging.info(\"Active games: \" + str(activeGameIDs))\n\n\t#Throw all of the player IDs that are in these ongoing games into a dictionary\n\tplayerIDsInGames = dict([[gp.playerID, gp] for gp in games.GamePlayer.all().filter(\"tourney_id =\", tourney_id) if gp.gameID in activeGameIDs]) ##.run(batch_size=1000) \n\n\t#Find all players who aren't in the dictionary (and therefore aren't in any games) and also have not left the CLOT (isParticipating is true)\n\tallPlayers = players.Player.all().filter(\"tourney_id =\", tourney_id)#.run(batch_size=1000)\n\t\n\tall_players_vec = [p for p in allPlayers]\n\t#logging.info(\"all_players_vec: \")\n\t#logging.info(all_players_vec)\n\tall_players_keys_ids_vec = [p.key().id() for p in allPlayers]\n\t#logging.info(\"all_players_keys_ids_vec: \" + str(all_players_keys_ids_vec))\n\tplayer_ids_in_games_vec = [p for p in playerIDsInGames]\n\t#logging.info(\"player_ids_in_games_vec: \" + str(player_ids_in_games_vec))\n\t\n\tplayersNotInGames = [p for p in allPlayers if p.isParticipating and p.key().id() not in playerIDsInGames]\n\t#logging.info(\"Players not in games: \")\n\t#logging.info(playersNotInGames)\n\n\t#------------------------\n\t#now pair up players who are not in games. IF they have not played each otehr yet.\n\n\t#get the head-to-head matrix, so we can see who has played who\n\thead_to_head_biggermat, head_to_head_2d = new_utility_functions.getHeadToHeadTable(tourney_id)\n\t##logging.info('head_to_head_2d:')\n\t##logging.info(head_to_head_2d)\n\n\t#\n\tthe_ids = deepcopy(head_to_head_biggermat[0][1:])\n\t#logging.info('the_ids:')\n\t#logging.info(the_ids)\n\n\t#Randomize the order\n\trandom.shuffle(playersNotInGames)\n\n\t#loop over all possible pairs, and pair IF they have not played each other yet\n\tpaired_yet = [False]*len(playersNotInGames)\n\tlist_for_pairing = []\n\tfor i in range(0,len(playersNotInGames)-1):\n\t\tif not paired_yet[i]:\n\t\t\tpi = playersNotInGames[i]\n\t\t\tpi_id = int(pi.player_id)\n\t\t\tpi_index = the_ids.index(pi_id) #find where in the head-to-head matrix this player is.\n\t\t\t\n\t\t\t#logging.info('pi:')\n\t\t\t#logging.info(pi)\n\t\t\t#logging.info(pi_id)\n\t\t\t#logging.info(pi_index)\n\t\t\t\n\t\t\tfor j in range(i+1,len(playersNotInGames)):\n\t\t\t\tif (not paired_yet[j]) and (not paired_yet[i]):\n\t\t\t\t\tpj = playersNotInGames[j]\n\t\t\t\t\tpj_id = int(pj.player_id)\n\t\t\t\t\tpj_index = the_ids.index(pj_id) #find where in the head-to-head matrix this player is.\n\t\t\t\t\t\n\t\t\t\t\t#logging.info('pj:')\n\t\t\t\t\t#logging.info(pj)\n\t\t\t\t\t#logging.info(pj_id)\n\t\t\t\t\t#logging.info(pj_index)\n\t\t\t\n\t\t\t\t\tif (head_to_head_2d[pi_index][pj_index][0]==0) and (head_to_head_2d[pj_index][pi_index][0]==0): \n\t\t\t\t\t\t#they have not played each other.\n\t\t\t\t\t\t#so match them.\n\t\t\t\t\t\tpaired_yet[i] = True\n\t\t\t\t\t\tpaired_yet[j] = True\n\t\t\t\t\t\tlist_for_pairing.append(pi)\n\t\t\t\t\t\tlist_for_pairing.append(pj)\n\t\t\t\t\t\t#logging.info('paired '+str(pi)+' '+str(pj))\n\n\t##debug\n\t#logging.info(\"new player order is: \")\n\t#logging.info(list_for_pairing)\n\t#for pair in clot.pairs(list_for_pairing):\n\t#\tlogging.info(pair)\n\t##end of debug\n\n\t#The template ID defines the settings used when the game is created. You can create your own template on warlight.net and enter its ID here\n\ttemplateID = main.getTemplateID(tourney_id, tourney_clotconfig)\n\n\t#Create a game for everyone not in a game.\n\tgamesCreated = [games.createGame(pair, templateID, tourney_id) for pair in clot.pairs(list_for_pairing)]\n\tlogging.info(\"Created games \" + str(gamesCreated))\n\t\n\tif (len(activeGames)==0) and (len(list_for_pairing)==0):\n\t\tif main.isTourneyInPlay(tourney_id, tourney_clotconfig):\n\t\t\t#tourney is in play, but no games are going on, and we found no games we could create.\n\t\t\t#so the tourney is over\n\t\t\tmain.endTourney(tourney_id, tourney_clotconfig)\n\t\t\tlogging.info('')\n\t\t\tlogging.info('all games have been played, so TOURNAMENT IS OVER !!!!!!!!!!!!!!')\n\t\t\tlogging.info('')\n\n\n\n","sub_path":"tournament_roundrobin.py","file_name":"tournament_roundrobin.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"410525499","text":"import time \nimport sys\nimport logging\nimport socket\n\nlogger = logging.getLogger(\"job\")\n\nTASK_STARTING = 0\nTASK_RUNNING = 1\nTASK_FINISHED = 2\nTASK_FAILED = 3\nTASK_KILLED = 4\nTASK_LOST = 5\n\nclass Job:\n def __init__(self):\n self.id = self.newJobId()\n self.start = time.time()\n\n def slaveOffer(self, s, availableCpus):\n raise NotImplementedError\n\n def statusUpdate(self, t):\n raise NotImplementedError\n\n def error(self, code, message):\n raise NotImplementedError\n \n nextJobId = 0\n @classmethod\n def newJobId(cls):\n cls.nextJobId += 1\n return cls.nextJobId\n\nLOCALITY_WAIT = 5\nMAX_TASK_FAILURES = 4\nCPUS_PER_TASK = 1\n\n# A Job that runs a set of tasks with no interdependencies.\nclass SimpleJob(Job):\n\n def __init__(self, sched, tasks):\n Job.__init__(self)\n self.sched = sched\n self.tasks = tasks\n\n self.launched = [False] * len(tasks)\n self.finished = [False] * len(tasks)\n self.numFailures = [0] * len(tasks)\n self.blacklist = [[] for i in xrange(len(tasks))]\n self.tidToIndex = {}\n self.numTasks = len(tasks)\n self.tasksLaunched = 0\n self.tasksFinished = 0\n self.total_used = 0\n\n self.lastPreferredLaunchTime = time.time()\n\n self.pendingTasksForHost = {}\n self.pendingTasksWithNoPrefs = []\n self.allPendingTasks = []\n\n self.failed = False\n self.causeOfFailure = \"\"\n\n for i in range(len(tasks)):\n self.addPendingTask(i)\n\n @property\n def taskEverageTime(self):\n return self.total_used / self.tasksFinished\n\n def addPendingTask(self, i):\n loc = self.tasks[i].preferredLocations()\n if not loc:\n self.pendingTasksWithNoPrefs.append(i)\n else:\n for host in loc:\n self.pendingTasksForHost.setdefault(host, []).append(i)\n self.allPendingTasks.append(i)\n\n def getPendingTasksForHost(self, host):\n try:\n h, hs, ips = socket.gethostbyname_ex(host)\n except Exception:\n h, hs, ips = host, [], []\n return sum((self.pendingTasksForHost.setdefault(h, []) \n for h in [h] + hs + ips), [])\n\n def findTaskFromList(self, l, host):\n for i in l:\n if not self.launched[i] and not self.finished[i] and host not in self.blacklist[i]:\n self.blacklist[i].append(host)\n return i\n\n def findTask(self, host, localOnly):\n localTask = self.findTaskFromList(self.getPendingTasksForHost(host), host)\n if localTask is not None:\n return localTask, True\n noPrefTask = self.findTaskFromList(self.pendingTasksWithNoPrefs, host)\n if noPrefTask is not None:\n return noPrefTask, True\n if not localOnly:\n return self.findTaskFromList(self.allPendingTasks, host), False\n# else:\n# print repr(host), self.pendingTasksForHost\n return None, False\n\n # Respond to an offer of a single slave from the scheduler by finding a task\n def slaveOffer(self, host, availableCpus): \n if self.tasksLaunched >= self.numTasks:\n if (self.tasksFinished < self.numTasks \n and self.tasksFinished > self.numTasks *.75):\n # re-submit timeout task\n avg = self.taskEverageTime\n now = time.time()\n task = sorted((task.start, task) \n for i,task in enumerate(self.tasks) \n if not self.finished[i])[0][1]\n used = time.time() - task.start\n if used > avg * 2 and used > 10:\n if task.tried <= MAX_TASK_FAILURES:\n logger.warning(\"re-submit task %s for timeout %s\",\n task.id, used)\n task.start = time.time()\n task.tried += 1\n return task\n else:\n logger.error(\"tast %s timeout, aborting job %s\",\n task, self.id)\n self.abort(\"task %s timeout\" % task)\n return\n\n now = time.time()\n localOnly = (now - self.lastPreferredLaunchTime < LOCALITY_WAIT)\n i, preferred = self.findTask(host, localOnly)\n if i is not None:\n task = self.tasks[i]\n task.start = now\n task.tried = 0\n prefStr = preferred and \"preferred\" or \"non-preferred\"\n logger.debug(\"Starting task %d:%d as TID %s on slave %s (%s)\", \n self.id, i, task, host, prefStr)\n self.tidToIndex[task.id] = i\n self.launched[i] = True\n self.tasksLaunched += 1\n if preferred:\n self.lastPreferredLaunchTime = now\n return task\n logger.debug(\"no task found %s\", localOnly)\n\n def statusUpdate(self, tid, status, reason=None, result=None, update=None):\n logger.debug(\"job status update %s %s %s\", tid, status, reason)\n if status == TASK_FINISHED:\n self.taskFinished(tid, result, update)\n elif status in (TASK_LOST, \n TASK_FAILED, TASK_KILLED):\n self.taskLost(tid, status, reason)\n\n def taskFinished(self, tid, result, update):\n i = self.tidToIndex[tid]\n if not self.finished[i]:\n self.finished[i] = True\n self.tasksFinished += 1\n task = self.tasks[i]\n task.used = time.time() - task.start\n self.total_used += task.used\n logger.info(\"Task %s finished in %.2fs (%d/%d)\",\n tid, task.used, self.tasksFinished, self.numTasks)\n from schedule import Success\n self.sched.taskEnded(task, Success(), result, update)\n if self.tasksFinished == self.numTasks:\n ts = [t.used for t in self.tasks]\n tried = [t.tried for t in self.tasks]\n logger.info(\"Job %d finished in %ss: min=%s, avg=%s, max=%s, maxtry=%s\",\n self.id, time.time()-self.start, \n min(ts), sum(ts)/len(ts), max(ts), max(tried))\n self.sched.jobFinished(self)\n else:\n logger.info(\"Ignoring task-finished event for TID %d \"\n + \"because task %d is already finished\", tid, i)\n\n def taskLost(self, tid, status, reason):\n index = self.tidToIndex[tid]\n if not self.finished[index]:\n logger.warning(\"Lost TID %s (task %d:%d) %s\", tid, self.id, index, reason)\n self.launched[index] = False\n self.tasksLaunched -= 1\n\n from schedule import FetchFailed\n if isinstance(reason, FetchFailed):\n logger.warning(\"Loss was due to fetch failure from %s\",\n reason.serverUri)\n self.sched.taskEnded(self.tasks[index], reason, None, None)\n self.finished[index] = True\n self.tasksFinished += 1\n if self.tasksFinished == self.numTasks:\n self.sched.jobFinished(self)\n return\n logger.warning(\"re-enqueue the task as pending for a max number of retries\")\n if status == TASK_FAILED:\n logger.warning(\"task %s failed with: %s\", \n self.tasks[index], reason and reason.message)\n self.addPendingTask(index)\n self.sched.requestMoreResources()\n if status in (TASK_FAILED, TASK_LOST):\n self.numFailures[index] += 1\n if self.numFailures[index] > MAX_TASK_FAILURES:\n logger.error(\"Task %d failed more than %d times; aborting job\", index, MAX_TASK_FAILURES)\n self.abort(\"Task %d failed more than %d times\" \n % (index, MAX_TASK_FAILURES))\n\n else:\n logger.warning(\"Ignoring task-lost event for TID %d \"\n +\"because task %d is already finished\")\n\n def abort(self, message):\n logger.error(\"abort the job: %s\", message)\n self.failed = True\n self.causeOfFailure = message\n self.sched.jobFinished(self)\n self.sched.shutdown()\n","sub_path":"dpark/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":8254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"129264902","text":"# Copyright 2015 Janos Czentye \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nImplements the platform and POX dependent logic for the Service Adaptation\nSublayer.\n\"\"\"\nimport httplib\nimport os\nfrom subprocess import Popen\n\nfrom escape.nffg_lib.nffg import NFFG, NFFGToolBox\nfrom escape.orchest.ros_API import InstantiationFinishedEvent, \\\n BasicUnifyRequestHandler\nfrom escape.service import LAYER_NAME, log as log # Service layer logger\nfrom escape.service.element_mgmt import ClickManager\nfrom escape.service.sas_orchestration import ServiceOrchestrator\nfrom escape.util.api import AbstractAPI, RESTServer, AbstractRequestHandler, \\\n RequestStatus, RequestScheduler\nfrom escape.util.config import CONFIG\nfrom escape.util.conversion import NFFGConverter\nfrom escape.util.domain import BaseResultEvent\nfrom escape.util.mapping import PreMapEvent, PostMapEvent, ProcessorError\nfrom escape.util.misc import schedule_delayed_as_coop_task, \\\n schedule_as_coop_task, VERBOSE, quit_with_ok, \\\n get_global_parameter, quit_with_error\nfrom escape.util.stat import stats\nfrom pox.lib.revent.revent import Event\n\nSCHEDULED_SERVICE_REQUEST_DELAY = CONFIG.get_sas_request_delay()\n\n\nclass InstantiateNFFGEvent(Event):\n \"\"\"\n Event for passing NFFG (mapped SG) to Orchestration layer.\n \"\"\"\n\n def __init__ (self, nffg, resource_nffg):\n \"\"\"\n Init.\n\n :param nffg: NF-FG need to be initiated\n :type nffg: :class:`NFFG`\n :return: None\n \"\"\"\n super(InstantiateNFFGEvent, self).__init__()\n self.nffg = nffg\n self.resource_nffg = resource_nffg\n stats.add_measurement_end_entry(type=stats.TYPE_SERVICE, info=LAYER_NAME)\n\n\nclass GetVirtResInfoEvent(Event):\n \"\"\"\n Event for requesting virtual resource info from Orchestration layer.\n \"\"\"\n\n def __init__ (self, sid):\n \"\"\"\n Init.\n\n :param sid: Service layer ID\n :type sid: int\n :return: None\n \"\"\"\n super(GetVirtResInfoEvent, self).__init__()\n # service layer ID\n self.sid = sid\n\n\nclass ServiceRequestHandler(BasicUnifyRequestHandler):\n \"\"\"\n Request Handler for Service Adaptation SubLayer.\n\n .. warning::\n This class is out of the context of the recoco's co-operative thread\n context! While you don't need to worry much about synchronization between\n recoco tasks, you do need to think about synchronization between recoco task\n and normal threads. Synchronisation is needed to take care manually: use\n relevant helper function of core object: `callLater`/`raiseLater` or use\n `schedule_as_coop_task` decorator defined in util.misc on the called\n function.\n \"\"\"\n # Bind HTTP verbs to UNIFY's API functions\n request_perm = {\n 'GET': ('ping', 'version', 'operations', 'topology', 'status'),\n 'POST': ('ping', 'sg', 'topology'),\n # 'DELETE': ('sg',),\n 'PUT': ('sg',)\n }\n \"\"\"Bind HTTP verbs to UNIFY's API functions\"\"\"\n # Statically defined layer component to which this handler is bounded\n # Need to be set by container class\n bounded_layer = 'service'\n \"\"\"Statically defined layer component to which this handler is bounded\"\"\"\n static_prefix = \"escape\"\n # Logger name\n LOGGER_NAME = \"U-Sl\"\n \"\"\"Logger name\"\"\"\n log = log.getChild(\"[%s]\" % LOGGER_NAME)\n # Use Virtualizer format\n virtualizer_format_enabled = False\n \"\"\"Use Virtualizer format\"\"\"\n # Default communication approach\n DEFAULT_DIFF = True\n \"\"\"Default communication approach\"\"\"\n # Bound function\n API_CALL_RESOURCE = 'api_sas_get_topology'\n API_CALL_REQUEST = 'api_sas_sg_request'\n\n def __init__ (self, request, client_address, server):\n \"\"\"\n Init.\n\n :param request: request type\n :type request: str\n :param client_address: client address\n :type client_address: str\n :param server: server object\n :type server: :any:`BaseHTTPServer.HTTPServer`\n :return: None\n \"\"\"\n AbstractRequestHandler.__init__(self, request, client_address, server)\n\n def status (self, params):\n \"\"\"\n Return status of the given request.\n\n :param params:\n :return:\n \"\"\"\n message_id = params.get('message-id')\n if not message_id:\n self.send_error(code=httplib.BAD_REQUEST, message=\"message-id is missing\")\n return\n code, result = self._proceed_API_call('api_sas_status', message_id)\n if not result:\n self.send_acknowledge(code=code, message_id=message_id)\n self.log.debug(\"Responded status code: %s\" % code)\n else:\n self.send_json_response(code=code, data=result)\n self.log.debug(\"Responded status code: %s, data: %s\" % (code, result))\n\n def topology (self, params):\n \"\"\"\n Provide internal topology description\n\n Same functionality as \"get-config\" in UNIFY interface.\n\n :return: None\n \"\"\"\n self.log.debug(\"Call %s function: topology\" % self.LOGGER_NAME)\n # Forward call to main layer class\n resource = self._proceed_API_call(self.API_CALL_RESOURCE)\n self._topology_view_responder(resource_nffg=resource,\n message_id=params.get(self.MESSAGE_ID_NAME))\n self.log.debug(\"%s function: topology ended!\" % self.LOGGER_NAME)\n\n def sg (self, params):\n \"\"\"\n Main API function for Service Graph initiation.\n\n Same functionality as \"get-config\" in UNIFY interface.\n\n Bounded to POST HTTP verb.\n\n :return: None\n \"\"\"\n self.log.debug(\"Call %s function: sg\" % self.LOGGER_NAME)\n nffg = self._service_request_parser()\n if nffg:\n if nffg.service_id is None:\n nffg.service_id = nffg.id\n nffg.id = params[self.MESSAGE_ID_NAME]\n self.log.debug(\"Set NFFG id: %s\" % nffg.id)\n nffg.metadata['params'] = params\n self.server.scheduler.schedule_request(id=nffg.id,\n layer=self.bounded_layer,\n function=self.API_CALL_REQUEST,\n service_nffg=nffg, params=params)\n self.send_acknowledge(message_id=params[self.MESSAGE_ID_NAME])\n self.log.debug(\"%s function: sg ended!\" % self.LOGGER_NAME)\n\n\nclass ServiceLayerAPI(AbstractAPI):\n \"\"\"\n Entry point for Service Adaptation Sublayer.\n\n Maintain the contact with other UNIFY layers.\n\n Implement the U - Sl reference point.\n \"\"\"\n # Defined specific name for core object as pox.core.<_core_name>\n _core_name = LAYER_NAME\n \"\"\"Defined specific name for core object \"\"\"\n # Layer id constant\n LAYER_ID = \"ESCAPE-\" + LAYER_NAME\n \"\"\"Layer id constant\"\"\"\n # Events raised by this class\n _eventMixin_events = {InstantiateNFFGEvent, GetVirtResInfoEvent, PreMapEvent,\n PostMapEvent}\n \"\"\"Events raised by this class\"\"\"\n # Dependencies\n dependencies = ('orchestration',)\n \"\"\"Layer dependencies\"\"\"\n\n def __init__ (self, standalone=False, **kwargs):\n \"\"\"\n .. seealso::\n :func:`AbstractAPI.__init__() `\n \"\"\"\n log.info(\"Starting Service Layer...\")\n # Mandatory super() call\n self.last_sg = NFFG(id=0, name='empty')\n # Set element manager\n self.__sid = None\n self.elementManager = None\n self.service_orchestrator = None\n \"\"\":type ServiceOrchestrator\"\"\"\n self.gui_proc = None\n super(ServiceLayerAPI, self).__init__(standalone, **kwargs)\n\n def initialize (self):\n \"\"\"\n .. seealso::\n :func:`AbstractAPI.initialize() `\n \"\"\"\n log.debug(\"Initializing Service Layer...\")\n self.__sid = CONFIG.get_service_layer_id()\n if self.__sid is not None:\n log.debug(\"Setup ID for Service Layer: %s\" % self.__sid)\n else:\n self.__sid = self.LAYER_ID\n log.error(\n \"Missing ID of Service Layer from config. Using default value: %s\" %\n self.__sid)\n # Set element manager\n self.elementManager = ClickManager()\n # Init central object of Service layer\n self.service_orchestrator = ServiceOrchestrator(self)\n # Read input from file if it's given and initiate SG\n if self._sg_file:\n try:\n stats.init_request_measurement(request_id=self._sg_file)\n service_request = self._read_data_from_file(self._sg_file)\n log.info(\"Graph representation is loaded successfully!\")\n if service_request.startswith('{'):\n log.debug(\"Detected format: JSON - Parsing from NFFG format...\")\n nffg = NFFG.parse(raw_data=service_request)\n elif service_request.startswith('<'):\n log.debug(\"Detected format: XML - Parsing from Virtualizer format...\")\n converter = NFFGConverter(domain=\"INTERNAL\", logger=log,\n unique_bb_id=False,\n unique_nf_id=CONFIG.ensure_unique_vnf_id())\n nffg = converter.parse_from_Virtualizer(vdata=service_request)\n else:\n log.warning(\"Detected unexpected format...\")\n return\n if nffg.mode is not None:\n log.info('Detected mapping mode in NFFG: %s' % nffg.mode)\n else:\n nffg.mode = NFFG.MODE_ADD\n log.info(\"No mapping mode has been detected in NFFG! \"\n \"Set default mode: %s\" % nffg.mode)\n log.info(\"Schedule service request delayed by %d seconds...\"\n % SCHEDULED_SERVICE_REQUEST_DELAY)\n stats.set_request_id(request_id=nffg.id)\n self.api_sas_sg_request_delayed(service_nffg=nffg)\n except (ValueError, IOError, TypeError) as e:\n log.error(\n \"Can't load service request from file because of: \" + str(e))\n quit_with_error(msg=str(e), logger=log)\n else:\n # Init REST-API if no input file is given\n self._initiate_rest_api()\n # Init GUI\n if self._gui:\n self._initiate_gui()\n log.info(\"Service Layer has been initialized!\")\n\n def post_up_hook (self, event):\n \"\"\"\n Perform tasks after ESCAPE is up.\n\n :param event: event object\n :type event: :class:`UpEvent`\n :return: None\n \"\"\"\n log.debug(\"Call post Up event hook for layer: %s\" % self._core_name)\n if not self._sg_file:\n self.rest_api.ping_response_code = self.rest_api.POST_UP_PING_CODE\n log.debug(\"Setup 'ping' response code: %s for REST-API: %s\"\n % (self.rest_api.ping_response_code, self.rest_api.api_id))\n\n def shutdown (self, event):\n \"\"\"\n .. seealso::\n :func:`AbstractAPI.shutdown() `\n\n :param event: event object\n \"\"\"\n log.info(\"Service Layer is going down...\")\n if hasattr(self, 'rest_api') and self.rest_api:\n log.debug(\"REST-API: %s is shutting down...\" % self.rest_api.api_id)\n # self.rest_api.stop()\n if self.gui_proc:\n log.debug(\"Shut down GUI process - PID: %s\" % self.gui_proc.pid)\n self.gui_proc.terminate()\n\n def _initiate_rest_api (self):\n \"\"\"\n Initialize and set up REST API in a different thread.\n\n :return: None\n \"\"\"\n # set bounded layer name here to avoid circular dependency problem\n handler = CONFIG.get_sas_api_class()\n handler.bounded_layer = self._core_name\n params = CONFIG.get_sas_agent_params()\n # can override from global config\n if 'prefix' in params:\n handler.prefix = params['prefix']\n if 'unify_interface' in params:\n handler.virtualizer_format_enabled = params['unify_interface']\n address = (params.get('address'), params.get('port'))\n self.rest_api = RESTServer(handler, *address)\n self.rest_api.api_id = handler.LOGGER_NAME = \"U-Sl\"\n handler.log.info(\"Init REST-API for %s on %s:%s!\" % (\n self.rest_api.api_id, address[0], address[1]))\n self.rest_api.virtualizer_params = params.get('virtualizer_params', {})\n self.rest_api.start()\n handler.log.debug(\"Enforced configuration for %s: interface: %s\" % (\n self.rest_api.api_id,\n \"UNIFY\" if handler.virtualizer_format_enabled else \"Internal-NFFG\"))\n\n def _initiate_gui (self):\n \"\"\"\n Initiate and set up GUI.\n\n :return: None\n \"\"\"\n # TODO - set up and initiate MiniEdit here???\n devnull = open(os.devnull, 'r+')\n gui_path = os.path.abspath(os.getcwd() + \"/gui/gui.py\")\n self.gui_proc = Popen(gui_path, stdin=devnull, stdout=devnull,\n stderr=devnull, close_fds=True)\n log.info(\"GUI has been initiated!\")\n\n def _handle_SGMappingFinishedEvent (self, event):\n \"\"\"\n Handle SGMappingFinishedEvent and proceed with :class:`NFFG\n ` instantiation.\n\n :param event: event object\n :type event: :any:`SGMappingFinishedEvent`\n :return: None\n \"\"\"\n self._proceed_to_instantiate_NFFG(event.nffg)\n\n ##############################################################################\n # UNIFY U - Sl API functions starts here\n ##############################################################################\n\n # noinspection PyUnusedLocal\n @schedule_as_coop_task\n def api_sas_sg_request (self, service_nffg, *args, **kwargs):\n \"\"\"\n Initiate service graph in a cooperative micro-task.\n\n :param service_nffg: service graph instance\n :type service_nffg: :class:`NFFG`\n :return: None\n \"\"\"\n self.__proceed_sg_request(service_nffg=service_nffg)\n\n # noinspection PyUnusedLocal\n @schedule_delayed_as_coop_task(delay=SCHEDULED_SERVICE_REQUEST_DELAY)\n def api_sas_sg_request_delayed (self, service_nffg, *args, **kwargs):\n \"\"\"\n Initiate service graph in a cooperative micro-task.\n\n :param service_nffg: service graph instance\n :type service_nffg: :class:`NFFG`\n :return: None\n \"\"\"\n return self.__proceed_sg_request(service_nffg=service_nffg)\n\n def __proceed_sg_request (self, service_nffg):\n \"\"\"\n Initiate a Service Graph (UNIFY U-Sl API).\n\n :param service_nffg: service graph instance\n :type service_nffg: :class:`NFFG`\n :return: None\n \"\"\"\n log.getChild('API').info(\"Invoke request_service on %s with SG: %s \" %\n (self.__class__.__name__, service_nffg))\n stats.add_measurement_start_entry(type=stats.TYPE_SERVICE, info=LAYER_NAME)\n # Check if mapping mode is set globally in CONFIG\n mapper_params = CONFIG.get_mapping_config(layer=LAYER_NAME)\n if 'mode' in mapper_params and mapper_params['mode'] is not None:\n mapping_mode = mapper_params['mode']\n log.info(\"Detected mapping mode from configuration: %s\" % mapping_mode)\n elif service_nffg.mode is not None:\n mapping_mode = service_nffg.mode\n log.info(\"Detected mapping mode from NFFG: %s\" % mapping_mode)\n else:\n mapping_mode = None\n log.info(\"No mapping mode was detected!\")\n self.__sg_preprocessing(nffg=service_nffg)\n # Store request if it is received on REST-API\n if hasattr(self, 'rest_api') and self.rest_api:\n log.getChild('API').debug(\"Store received NFFG request info...\")\n msg_id = self.rest_api.request_cache.cache_request_by_nffg(\n nffg=service_nffg)\n if msg_id is not None:\n self.rest_api.request_cache.set_in_progress(id=msg_id)\n log.getChild('API').debug(\"Request is stored with id: %s\" % msg_id)\n else:\n log.getChild('API').debug(\"No request info detected.\")\n try:\n if CONFIG.get_mapping_enabled(layer=LAYER_NAME):\n # Initiate service request mapping\n mapped_nffg = self.service_orchestrator.initiate_service_graph(\n service_nffg)\n else:\n log.warning(\"Mapping is disabled! Skip instantiation step...\")\n mapped_nffg = service_nffg\n mapped_nffg.status = NFFG.MAP_STATUS_SKIPPED\n log.debug(\"Mark NFFG status: %s!\" % mapped_nffg.status)\n # Rewrite REMAP mode for backward compatibility\n if mapped_nffg is not None and mapping_mode == NFFG.MODE_REMAP:\n mapped_nffg.mode = mapping_mode\n log.debug(\"Rewrite mapping mode: %s into mapped NFFG...\" %\n mapped_nffg.mode)\n else:\n log.debug(\n \"Skip mapping mode rewriting! Mode remained: %s\" % mapping_mode)\n log.getChild('API').debug(\"Invoked request_service on %s is finished\" %\n self.__class__.__name__)\n # If mapping is not threaded and finished with OK\n if mapped_nffg is not None and not \\\n self.service_orchestrator.mapper.threaded:\n self._proceed_to_instantiate_NFFG(mapped_nffg)\n self.last_sg = mapped_nffg\n else:\n log.warning(\"Something went wrong in service request initiation: \"\n \"mapped service data is missing!\")\n self.__handle_mapping_result(nffg_id=service_nffg.id, fail=True)\n self._handle_InstantiationFinishedEvent(\n event=InstantiationFinishedEvent(\n id=service_nffg.id,\n result=InstantiationFinishedEvent.MAPPING_ERROR))\n except ProcessorError as e:\n self.__handle_mapping_result(nffg_id=service_nffg.id, fail=True)\n self._handle_InstantiationFinishedEvent(\n event=InstantiationFinishedEvent(\n id=service_nffg.id,\n result=InstantiationFinishedEvent.REFUSED_BY_VERIFICATION,\n error=e))\n\n @staticmethod\n def __sg_preprocessing (nffg):\n \"\"\"\n Preprocess given :class:`NFFG` based on request mode.\n\n :param nffg: received service request\n :type nffg: :class:`NFFG`\n :return: modified request\n :rtype: :class:`NFFG`\n \"\"\"\n if nffg.mode == NFFG.MODE_DEL:\n log.debug(\"Explicitly mark NF nodes in DELETE request...\")\n for nf in nffg.nfs:\n nf.operation = NFFG.OP_DELETE\n log.debug(\"%s --> %s\" % (nf.id, nf.operation))\n return nffg\n\n def __handle_mapping_result (self, nffg_id, fail):\n \"\"\"\n Perform necessary task for callback and cache functionality based on mapping\n result.\n\n :param nffg_id: request ID\n :type nffg_id: str or int\n :param fail: mapping result\n :type fail: bool\n :return: None\n \"\"\"\n if not (hasattr(self, 'rest_api') and self.rest_api):\n return\n log.getChild('API').debug(\"Cache request status...\")\n req_status = self.rest_api.request_cache.get_request_by_nffg_id(nffg_id)\n if req_status is None:\n log.getChild('API').debug(\"Request status is missing for NFFG: %s! \"\n \"Skip result processing...\" % nffg_id)\n return\n log.getChild('API').debug(\"Process mapping result...\")\n message_id = req_status.message_id\n if message_id is not None:\n if fail:\n self.rest_api.request_cache.set_error_result(id=message_id)\n else:\n self.rest_api.request_cache.set_success_result(id=message_id)\n ret = self.rest_api.invoke_callback(message_id=message_id)\n if ret is None:\n log.getChild('API').debug(\"No callback was defined!\")\n else:\n log.getChild('API').debug(\n \"Callback: %s has invoked with return value: %s\" % (\n req_status.get_callback(), ret))\n RequestScheduler().set_orchestration_finished(id=nffg_id)\n\n def __get_sas_resource_view (self):\n \"\"\"\n Return with the resource view of SAS layer.\n\n :return: resource view\n :rtype: :any:`AbstractVirtualizer`\n \"\"\"\n return self.service_orchestrator.virtResManager.virtual_view\n\n def api_sas_get_topology (self):\n \"\"\"\n Return with the topology description.\n\n :return: topology description requested from the layer's Virtualizer\n :rtype: :class:`NFFG`\n \"\"\"\n log.getChild('[U-Sl]').debug(\"Requesting Virtualizer for REST-API...\")\n # Get or if not available then request the layer's Virtualizer\n sas_virt = self.__get_sas_resource_view()\n if sas_virt is not None:\n log.getChild('[U-Sl]').debug(\"Generate topo description...\")\n # return with the virtual view as an NFFG\n return sas_virt.get_resource_info()\n else:\n log.getChild('[U-Sl]').error(\n \"Virtualizer(id=%s) assigned to REST-API is not found!\" %\n self.rest_api.api_id)\n\n def api_sas_status (self, message_id):\n \"\"\"\n Return the state of a request given by ``message_id``.\n\n Function is not invoked in coop-microtask, only write-type operations\n must not be used.\n\n :param message_id: request id\n :type message_id: str or int\n :return: state\n :rtype: str\n \"\"\"\n status = self.rest_api.request_cache.get_domain_status(id=message_id)\n if status == RequestStatus.SUCCESS:\n return 200, None\n elif status == RequestStatus.UNKNOWN:\n return 404, None\n elif status == RequestStatus.ERROR:\n return 500, status\n else:\n # PROCESSING or INITIATED\n return 202, None\n\n def _proceed_to_instantiate_NFFG (self, mapped_nffg):\n \"\"\"\n Send NFFG to Resource Orchestration Sublayer in an implementation-specific\n way.\n\n General function which is used from microtask and Python thread also.\n\n This function contains the last steps before the mapped NFFG will be sent\n to the next layer.\n\n :param mapped_nffg: mapped Service Graph\n :type mapped_nffg: :class:`NFFG`\n :return: None\n \"\"\"\n # Rebind requirement link fragments for lower layer mapping\n mapped_nffg = NFFGToolBox.rebind_e2e_req_links(nffg=mapped_nffg, log=log)\n # Log verbose mapping result in unified way (threaded/non-threaded)\n log.log(VERBOSE,\n \"Mapping result of Service Layer:\\n%s\" % mapped_nffg.dump())\n # Sending mapped SG / NF-FG to Orchestration layer as an Event\n # Exceptions in event handlers are caught by default in a non-blocking way\n sas_res = self.__get_sas_resource_view().get_resource_info()\n self.raiseEventNoErrors(InstantiateNFFGEvent, mapped_nffg, sas_res)\n log.getChild('API').info(\n \"Generated NF-FG: %s has been sent to Orchestration...\" % mapped_nffg)\n\n ##############################################################################\n # UNIFY Sl - Or API functions starts here\n ##############################################################################\n\n # noinspection PyUnusedLocal\n def _handle_MissingVirtualViewEvent (self, event):\n \"\"\"\n Request virtual resource info from Orchestration layer (UNIFY Sl - Or API).\n\n Invoked when a :class:`MissingVirtualViewEvent` raised.\n\n Service layer is identified with the sid value automatically.\n\n :param event: event object\n :type event: :any:`MissingVirtualViewEvent`\n :return: None\n \"\"\"\n log.getChild('API').debug(\n \"Send request(with layer ID: %s) to Orchestration \"\n \"layer...\" % self.__sid)\n self.raiseEventNoErrors(GetVirtResInfoEvent, self.__sid)\n\n def _handle_VirtResInfoEvent (self, event):\n \"\"\"\n Save requested virtual resource info as an :class:`AbstractVirtualizer\n `.\n\n :param event: event object\n :type event: :any:`VirtResInfoEvent`\n :return: None\n \"\"\"\n log.getChild('API').debug(\"Received : %s from %s layer\" % (\n event.virtualizer, str(event.source._core_name).title()))\n self.service_orchestrator.virtResManager.virtual_view = event.virtualizer\n\n def _handle_InstantiationFinishedEvent (self, event):\n \"\"\"\n Receive the result of the instantiated NFFG and save it.\n\n :param event: event object\n :type event: :any:`InstantiationFinishedEvent`\n :return: None\n \"\"\"\n if not BaseResultEvent.is_error(event.result):\n log.getChild('API').info(\n \"Service request(id=%s) has been finished successfully with result: %s!\"\n % (event.id, event.result))\n else:\n log.getChild('API').error(\n \"Service request(id=%s) has been finished with error result: %s!\" %\n (event.id, event.result))\n if not event.is_pending(event.result):\n self.__handle_mapping_result(nffg_id=event.id,\n fail=event.is_error(event.result))\n # Quit ESCAPE if test mode is active\n if get_global_parameter(name=\"QUIT_AFTER_PROCESS\"):\n stats.finish_request_measurement()\n quit_with_ok(\"Detected QUIT mode! Exiting ESCAPE...\")\n","sub_path":"escape/escape/service/sas_API.py","file_name":"sas_API.py","file_ext":"py","file_size_in_byte":24272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"364392627","text":"#2019/9/7\nimport sys\nclass ListNode(object):\n\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n\n def insert(self,node,x):\n if not node:\n head = ListNode(x)\n head.next = head\n return head\n\n cur,prev = node,None\n while True:\n prev = cur\n cur = cur.next\n if x >= prev.val and x <= cur.val:\n break\n\n if (prev.val>cur.val) and (x>prev.val or x 4:\n break\n\n","sub_path":"lintcode/第六层/599_向循环有序链表插入节点.py","file_name":"599_向循环有序链表插入节点.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"419415385","text":"from ctypes import CDLL, byref, get_errno, c_long, c_ulong\nfrom os import fork, execl, WIFSTOPPED, waitpid, kill, strerror\nfrom .__c_defs import *\n\n\ndef get_reg_64(regs: user_regs_struct, name: str) -> int:\n reg_name, mask = reg_mask_map[name]\n reg = getattr(regs, reg_name)\n reg_val = reg & mask\n if not mask & 0xff:\n reg_val <<= 8\n\n return reg_val\n\n\ndef set_reg_64(regs: user_regs_struct, name: str, value: int)\\\n -> user_regs_struct:\n reg_name, mask = reg_mask_map[name]\n if not mask & 0xff:\n value <<= 8\n\n reg_old = getattr(regs, reg_name)\n reg_new = (reg_old & (0xffffffffffffffff ^ mask)) | value\n setattr(regs, reg_name, reg_new)\n return regs\n\n\nclass Breakpoint:\n def __init__(self, dbg, addr: int, permanent: bool = False):\n self.__address = addr\n self.__patched_byte = dbg.read_from_addr(addr, 1)\n self.__permanent = permanent\n dbg.write_to_addr(addr, b\"\\xcc\")\n\n @property\n def patched_byte(self) -> bytes:\n return self.__patched_byte\n\n @property\n def address(self) -> int:\n return self.__address\n\n @property\n def permanent(self) -> bool:\n return self.__permanent\n\n @permanent.setter\n def permanent(self, value: bool) -> None:\n if not (value is True or value is False):\n raise TypeError(\"type bool expected\")\n else:\n self.__permanent = value\n\n\nclass Hook(Breakpoint):\n def __init__(self, dbg, addr: int, func, permanent: bool = True,\n silent: bool = False):\n self.__name = func.__name__\n self.__procedure = func\n self.__silent = silent\n super().__init__(dbg, addr, permanent=permanent)\n\n @property\n def name(self):\n return self.__name\n\n @property\n def silent(self):\n return self.__silent\n\n @silent.setter\n def silent(self, silent: bool):\n self.__silent = silent\n\n @property\n def procedure(self):\n return self.__procedure\n\n @procedure.setter\n def procedure(self, func):\n if not callable(func):\n raise TypeError(\"{0} is not callable\".format(type(func)))\n else:\n self.__procedure = func\n self.__name = func.__name__\n\n\nclass DebuggerException(Exception):\n def __init__(self, msg: str = \"\"):\n self.__str__ = msg\n super().__init__()\n\n\nclass BreakpointHit(Exception):\n def __init__(self, bp):\n self.__str__ = \"Breakpoint hit\"\n self.__bp = bp\n super().__init__()\n\n @property\n def breakpoint(self):\n return self.__bp\n\n\nclass DebuggerBase:\n def __init__(self, ignore_ptrace_errors: bool = True):\n self.__libc_ptrace = CDLL(\"libc.so.6\", use_errno=True).ptrace\n self.__breakpoints = list()\n self.__child_alive = False\n self.__regs = user_regs_struct()\n self.__ignore_ptrace_errors = ignore_ptrace_errors\n self.__restore = None\n self.__child_pid = None\n\n def __del__(self):\n if self.__child_alive:\n kill(self.__child_pid, 9)\n\n def __ptrace(self, *args) -> c_long:\n result = self.__libc_ptrace(*args)\n errno = get_errno()\n\n if errno != 0 and not self.__ignore_ptrace_errors:\n raise OSError(errno, strerror(errno))\n return result\n\n def __debugger_handover(self):\n # restore permanent breakpoints\n if self.__restore:\n self.add_breakpoint(self.__restore)\n self.__restore = None\n\n # wait for the child to finish, refresh regs and check for\n # breakpoint\n _, s = waitpid(self.__child_pid, 0)\n\n if WIFSTOPPED(s):\n self.__regs = self.__get_regs()\n restore = self.__ignore_ptrace_errors\n self.__ignore_ptrace_errors = True\n if self.__regs.rip-1 in self.breakpoints:\n self.__breakpoint_hook()\n self.__ignore_ptrace_errors = restore\n else:\n self.__child_alive = False\n\n def __breakpoint_hook(self):\n rip_reset = self.__regs.rip - 1\n bp = self.breakpoints[rip_reset]\n self.__breakpoints.remove(bp)\n\n self.write_to_addr(rip_reset, bp.patched_byte)\n self.set_reg(\"rip\", rip_reset)\n\n if bp.permanent:\n self.__restore = bp\n else:\n self.__restore = None\n\n raise BreakpointHit(bp)\n\n def load(self, path: str, *args):\n if self.__child_alive:\n raise ChildProcessError(\"Already tracing a program\")\n\n pid = fork()\n if not pid:\n self.__ptrace(PTRACE_TRACEME, 0, 0, 0)\n args = [path] if not args else args\n\n # turn off address space randomisation for child process\n pers = CDLL(\"libc.so.6\").personality(c_ulong(0xffffffff))\n CDLL(\"libc.so.6\").personality(pers | ADDR_NO_RANDOMIZE)\n errno = get_errno()\n if errno != 0:\n print(strerror(errno))\n\n execl(path, *args)\n else:\n self.__child_pid = pid\n self.__child_alive = True\n waitpid(self.__child_pid, 0)\n self.__regs = self.__get_regs()\n\n def step(self):\n if not self.__child_alive:\n raise ChildProcessError(\"Child not running\")\n self.__ptrace(PTRACE_SINGLESTEP, self.__child_pid, 0, 0)\n self.__debugger_handover()\n\n def continue_(self):\n if not self.__child_alive:\n raise ChildProcessError(\"Child not running\")\n self.__ptrace(PTRACE_CONT, self.__child_pid, 0, 0)\n self.__debugger_handover()\n\n def __get_regs(self):\n self.__ptrace(PTRACE_GETREGS, self.__child_pid, 0, byref(self.__regs))\n return self.__regs\n\n def get_reg(self, name: str):\n return get_reg_64(self.__regs, name)\n\n def set_reg(self, name: str, value: int):\n self.__regs = set_reg_64(self.__regs, name, value)\n\n self.__ptrace(PTRACE_SETREGS, self.__child_pid, 0,\n byref(self.__regs))\n\n def read_from_addr(self, addr: int, length: int) -> bytes:\n data = b''\n while len(data) < length:\n le_bytes = self.__ptrace(PTRACE_PEEKTEXT, self.__child_pid,\n addr, 0)\n data += bytes([0x000000ff & (le_bytes >> i*8) for i in range(4)])\n addr += 4\n return data[:length]\n\n # for some reason, PTRACE_PEEKTEXT reads 4 bytes while PTRACE_POKETEXT\n # writes 8 bytes. this makes things a little more complicated\n def write_to_addr(self, addr: int, data: bytes):\n length = len(data)\n # calculate number of bytes that must be read and appended to data\n # such that len(data) is a multiple of 8\n overlap = 8 - (length % 8) if length % 8 > 0 else 0\n\n # add the required padding to data\n if overlap != 0:\n o_start = int(length / 8) + 8 - overlap\n padding = self.read_from_addr(addr + o_start, overlap)\n data = data[:o_start] + padding\n\n # write the data word by word\n for i in range(0, len(data), 8):\n self.__ptrace(PTRACE_POKETEXT, self.__child_pid,\n addr + i,\n c_long(int.from_bytes(data[i:i+8], \"little\")))\n\n def new_breakpoint(self, address: int, permanent: bool = False):\n bp = Breakpoint(self, address, permanent=permanent)\n add_breakpoint(bp)\n\n def add_breakpoint(self, breakpoint):\n if breakpoint not in self.breakpoints:\n self.__breakpoints.append(breakpoint)\n else:\n msg = \"Breakpoint at 0x{0:x} already set\"\n raise DebuggerException(msg.format(bp.address))\n\n @property\n def child_running(self):\n return self.__child_alive\n\n @property\n def breakpoints(self):\n return {bp.address: bp for bp in self.__breakpoints}\n\n @property\n def child_pid(self):\n return self.__child_pid\n\n @property\n def ignore_ptrace_errors(self):\n return self.__ignore_ptrace_errors\n\n @ignore_ptrace_errors.setter\n def ignore_ptrace_errors(self, v):\n if v:\n self.__ignore_ptrace_errors = True\n else:\n self.__ignore_ptrace_errors = False\n\n\nclass DebuggerExtended(DebuggerBase):\n def __handle_breakpoint(self, bp):\n if hasattr(bp, \"procedure\"):\n bp.procedure(self)\n\n if not hasattr(bp, \"procedure\") or not bp.silent:\n raise BreakpointHit(bp)\n\n def continue_(self):\n try:\n super().continue_()\n except BreakpointHit as hit:\n self.__handle_breakpoint(hit.breakpoint)\n\n # if no BreakpointHit exception was thrown, continue\n self.continue_()\n\n def step(self):\n try:\n super().step()\n except BreakpointHit as hit:\n self.__handle_breakpoint(hit.breakpoint)\n\n def hook(self, addr, permanent: bool = True, silent: bool = False):\n def _hook(func):\n hook = Hook(self, addr, func, permanent=permanent, silent=silent)\n self.add_breakpoint(hook)\n return hook\n return _hook\n\n def stepping(self):\n while self.child_running:\n self.step()\n yield self.get_reg(\"rip\")\n","sub_path":"debugger/__Debugger.py","file_name":"__Debugger.py","file_ext":"py","file_size_in_byte":9266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"140434392","text":"\"\"\"\nPurpose: Detect Feature using Harris operator\nAuthor: Mohamed Hosny Ahmed\nDate: 10 / 4 / 2016\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport myopencv\nimport cvarthmetics\n\n\nclass HarrisDetector:\n\n def __init__(self, image):\n self.img = image\n self.rows, self.cols, self.channels = img.shape\n\n # initialize data\n self.tmpImg = np.zeros((self.rows, self.cols), np.float32)\n self.Ix2 = np.zeros((self.rows, self.cols), np.float32)\n self.Iy2 = np.zeros((self.rows, self.cols), np.float32)\n self.Ixy2 = np.zeros((self.rows, self.cols), np.float32)\n self.H = np.zeros((2, 2), np.float32)\n self.myCV = 0\n self.R = 0\n self.flag = 1\n self.calc_harris_operator()\n\n def calc_harris_operator(self):\n # check if we are in this method\n print ('>> calc_harris_operator')\n\n # 1- Compute gradient at x, y\n self.myCV = myopencv.cvUtiliy(self.img)\n self.Ix2 = self.myCV.calc_changes('x', 3)\n self.Iy2 = self.myCV.calc_changes('y', 3)\n\n # 2- Compute Ix^2, Iy^2, Ixy^2\n self.Ix2 = np.multiply(self.Ix2, self.Ix2)\n self.Iy2 = np.multiply(self.Iy2, self.Iy2)\n self.Ixy2 = np.multiply(self.Ix2, self.Iy2)\n\n # 3- Sum all pixels by bluring image by one to get summation with window 3x3\n self.Ix2 = self.myCV.summ_pixel_window(self.Ix2, 3)\n self.Iy2 = self.myCV.summ_pixel_window(self.Iy2, 3)\n self.Ixy2 = self.myCV.summ_pixel_window(self.Ixy2, 3)\n\n # 4- Define H(x,y) matrix\n for row in range(0, self.rows):\n for col in range(0, self.cols):\n self.H[0][0] = self.Ix2[row][col]\n self.H[0][1] = self.Ixy2[row][col]\n self.H[1][0] = self.Ixy2[row][col]\n self.H[1][1] = self.Iy2[row][col]\n\n # 5- Compute R = det(H(wx,y)) - K*Trace(H(x,y))^2\n self.R = self.harris_response(self.H)\n if self.R < -10000:\n self.tmpImg[row, col] = float(self.R)\n else:\n self.tmpImg[row, col] = 0.0\n\n self.tmpImg = np.array(self.tmpImg, np.float32)\n self.tmpImg = cvarthmetics.Arthmetics.get_local_maxima(self.tmpImg)\n\n return self.tmpImg\n\n # get harris response\n def harris_response(self, H):\n # check if we are in this method\n if self.flag == 1:\n print('>> harris_response')\n self.flag = 0\n\n trace = cv2.trace(H)\n response = cv2.determinant(H) - 0.04 * np.power(trace[0], 2)\n return response\n\n # return harris index's\n def get_harris(self):\n # check if we are in this method\n print('>> get_harris')\n x = self.tmpImg * self.img\n return self.tmpImg * self.img\n\n\nif __name__ == '__main__':\n\n x=0\n img = cv2.imread('/home/prof/Work_Space/CV/Assignment_3_CV/grad.png')\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n harris = HarrisDetector(image=gray)\n c = harris.get_harris()\n\n # print c.max()\n xx = c > 0.004*c.max()\n img[xx] = [0, 0, 255]\n\n cv2.imshow('img', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","sub_path":"harris_detector.py","file_name":"harris_detector.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"154578762","text":"\"\"\"\nThis library process the etherpad logs.\nAuthor: Pankaj\nDate: 9/09/2019\n\n\"\"\"\n\n# import package\nimport pandas as pd\nimport datetime\n\n\n\nclass etherLogAnalyzer(object):\n \"\"\"\n init function initialize the etherLogAnalyzer object.\n it takes one parameter the file name as\n \"\"\"\n def __init__(self, file_name):\n self.file_name = file_name\n\n try:\n self.file = pd.read_csv(file_name,names=['timestamp','ip','action','oldlen','newlen','changeset','charbank','noadd','noremove'])\n print('File loaded successfully....')\n\n self.file['timestamp'] = pd.to_datetime(self.file['timestamp'])\n #print('Setting timestamp as index...')\n self.file = self.file.set_index(pd.DatetimeIndex(self.file['timestamp']))\n\n except Exception as e:\n print('Error occured while opening the file',str(e))\n\n def getDuration(self):\n #self.file['timestamp'] = pd.to_datetime(self.file['timestamp'],format=\"%Y-%m-%d %I:%M:%S\")\n self.file['timestamp'] = pd.to_datetime(self.file['timestamp'])\n df1=self.file\n return str(df1.timestamp[df1.shape[0]-1]-df1.timestamp[0])\n\n\n # return all the text generated in Etherpad\n\n def getAllText(self):\n return self.file.charbank.tolist()\n\n \"\"\"\n This function will return the number of total ip recorded in the log file.\n \"\"\"\n\n def getAuthorCount(self):\n return len(self.file.ip.unique())\n\n \"\"\"\n This function returns the list of Author's IP recorded in the log file.\n \"\"\"\n\n def getAuthorIP(self):\n return self.file.ip.unique()\n\n \"\"\"\n Logs are recorded in same file for all the pads, therefore this function will seperate the log file\n on the basis of group. It reuires parameter e.g. group name and group ips.\n @params: group_name (String): name of group\n group_ips (List): list containing ips belong to that group\n Return type: Pandas dataframe.\n \"\"\"\n\n def getLogForGroup(self,group_ips):\n temp_df = self.file[self.file.ip.isin(group_ips)]\n return temp_df\n\n \"\"\"\n This function will generate statistics for each author in the group. These statistics are in form of number of addition\n and deletion along with time.\n @params:\n ip (String): ip address for which you want to see the stats\n timescale (String): it specify the time window for aggregating statistics.\n Possible values: Alias Description\n B business day frequency\n C custom business day frequency (experimental)\n D calendar day frequency\n W weekly frequency\n M month end frequency\n BM business month end frequency\n CBM custom business month end frequency\n MS month start frequency\n BMS business month start frequency\n CBMS custom business month start frequency\n Q quarter end frequency\n BQ business quarter endfrequency\n QS quarter start frequency\n BQS business quarter start frequency\n A year end frequency\n BA business year end frequency\n AS year start frequency\n BAS business year start frequency\n BH business hour frequency\n H hourly frequency\n T, min minutely frequency\n S secondly frequency\n L, ms milliseonds\n U, us microseconds\n N nanoseconds\n plot(Boolean): Specify True if you want to plot the graph\n\n\n Return type: Dataframe\n\n\n \"\"\"\n\n def generateWindowWiseStats(self,window_size='30S',ips=[]):\n\n # Computer number of char added or deleted\n #print(\"IP\",ips)\n tempdf = self.file.copy()\n #print(tempdf.shape)\n temp = tempdf.loc[tempdf['ip'].isin(ips)]\n temp['addition'] = temp['newlen']-temp['oldlen']\n temp['deletion'] = temp['oldlen']-temp['newlen']\n mask = temp['addition']<0\n mask2 = temp['deletion']<0\n temp.loc[mask,'addition']=0\n temp.loc[mask2,'deletion']=0\n\n\n\n #self.file['timestamp'] = pd.to_datetime(self.file['timestamp'],format=\"%Y-%m-%d %I:%M:%S\")\n\n\n\n df1=temp.copy()\n\n # Computing timedelta\n time_delta = pd.to_timedelta(window_size)\n\n # Creating empty dataframe\n final = pd.DataFrame(columns=['timestamp','u1_add','u1_del','u1_text','u2_add','u2_del','u2_text','u3_add','u3_del','u3_text','u4_add','u4_del','u4_text'])\n\n if df1.shape[0] != 0:\n cur_ts = df1.timestamp[0]\n else:\n print(\"Empty frame\")\n return final\n\n\n while cur_ts < df1.timestamp[df1.shape[0]-1]:\n\n next_ts = cur_ts + time_delta\n\n temp_log_df = df1.between_time(datetime.datetime.time(cur_ts),datetime.datetime.time(next_ts),include_start=True,include_end=False)\n\n\n entry = self.extractFeatures(cur_ts,temp_log_df,ips)\n\n #final = final.append({'timestamp':entry['timestamp'],'u1_add':entry['u1_add'],'u1_del':entry['u1_del'],'u1_text':entry['u1_text'],'u2_add':entry['u2_add'],'u2_del':entry['u2_del'],'u2_text':entry['u2_text'],'u3_add':entry['u3_add'],'u3_del':entry['u3_del'],'u3_text':entry['u3_text'],'u4_add':entry['u4_add'],'u4_del':entry['u4_del'],'u4_text':entry['u4_text'],'u1_speak':entry['u1_speak'],'u2_speak':entry['u2_speak'],'u3_speak':entry['u3_speak'],'u4_speak':entry['u4_speak'],'speak_sequence':entry['speak_sequence']},ignore_index=True)\n final = final.append(entry,ignore_index=True)\n\n cur_ts = next_ts\n final.to_csv('Final.csv',index=False)\n return final\n\n\n def extractFeatures(self,timestamp,log_df, no_ip):\n # features\n user1_addition = 0\n user1_deletion = 0\n user1_text = \"\"\n\n user2_addition = 0\n user2_deletion = 0\n user2_text = \"\"\n\n user3_addition = 0\n user3_deletion = 0\n user3_text = \"\"\n\n user4_addition = 0\n user4_deletion = 0\n user4_text = \"\"\n\n\n def concatenate_list_data(list):\n\n result= ''\n for element in list:\n if str(element) != 'nan':\n result += str(element)\n return result\n\n\n u1 = log_df.loc[log_df['ip']==no_ip[0],:]\n u2 = log_df.loc[log_df['ip']==no_ip[1],:]\n u3 = log_df.loc[log_df['ip']==no_ip[2],:]\n u4 = log_df.loc[log_df['ip']==no_ip[3],:]\n\n\n user1_addition = u1.addition.sum()\n user1_deletion = u1.deletion.sum()\n user1_text = concatenate_list_data(u1.charbank.tolist())\n\n user2_addition = u2.addition.sum()\n user2_deletion = u2.deletion.sum()\n user2_text = concatenate_list_data(u2.charbank.tolist())\n\n user3_addition = u3.addition.sum()\n user3_deletion = u3.deletion.sum()\n user3_text = concatenate_list_data(u3.charbank.tolist())\n\n user4_addition = u4.addition.sum()\n user4_deletion = u4.deletion.sum()\n user4_text = concatenate_list_data(u4.charbank.tolist())\n\n\n\n\n return {'timestamp':timestamp,'u1_add':user1_addition,'u1_del':user1_deletion,'u1_text':user1_text,'u2_add':user2_addition,'u2_del':user2_deletion,'u2_text':user2_text,'u3_add':user3_addition,'u3_del':user3_deletion,'u3_text':user3_text,'u4_add':user4_addition,'u4_del':user4_deletion,'u4_text':user4_text}\n\n\n\n\n def generateStatsForAuthor(self,ip,plot=False,timescale='30S'):\n temp = self.file.copy()\n temp = temp.loc[temp['ip']==ip,:]\n temp['addition'] = temp['newlen']-temp['oldlen']\n temp['deletion'] = temp['oldlen']-temp['newlen']\n mask = temp['addition']<0\n mask2 = temp['deletion']<0\n temp.loc[mask,'addition']=0\n temp.loc[mask2,'deletion']=0\n stat = temp.groupby(pd.Grouper(freq=timescale)).sum()\n if plot:\n stat[['addition','deletion']].plot(kind='bar')\n plt.title('Stats for User:'+ip)\n return stat\n","sub_path":"etherLogAnalyzer.py","file_name":"etherLogAnalyzer.py","file_ext":"py","file_size_in_byte":8390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"415684319","text":"\n#Code to run automatic fish feeder\nimport RPi.GPIO as GPIO\nimport time\n\nimport datetime\n\n#twitter config\nfrom twython import Twython\n\nfrom auth import (\n consumer_key,\n consumer_secret,\n access_token,\n access_token_secret\n)\n\ntwitter = Twython(\n consumer_key,\n consumer_secret,\n access_token,\n access_token_secret\n)\n\n\n\n\n#auto feeder\n\nfor i in range(3):\n\n time.sleep(5)\n GPIO.setmode(GPIO.BOARD)\n\n control_pins=[7,11,13,15]\n\n for pin in control_pins:\n GPIO.setup(pin, GPIO.OUT)\n GPIO.output(pin,0)\n\n halfstep_seq = [\n [1,0,0,0],\n [1,1,0,0],\n [0,1,0,0],\n [0,1,1,0],\n [0,0,1,0],\n [0,0,1,1],\n [0,0,0,1],\n [1,0,0,1]\n ]\n\n\n for j in range(512):\n for halfstep in range(8):\n for pin in range(4):\n GPIO.output(control_pins[pin], halfstep_seq[halfstep][pin])\n time.sleep(0.001)\n\n GPIO.cleanup()\n\n now = str(datetime.datetime.now())\n message= \"Hello Chum! %s %d\" % (now,i+1)\n\n twitter.update_status(status=message)\n\n print(\"Tweeted: %s %s %d\" % (message, now, i+1))\n\n\n","sub_path":"ChumBucketAuto.py","file_name":"ChumBucketAuto.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"104312889","text":"from django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import login, authenticate, logout\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nimport csv\nfrom django.conf import settings\nfrom .filters import PhageFilter\nfrom io import StringIO\nfrom io import TextIOWrapper\nfrom PhageBank.core.forms import Add_ResearchForm, AForm, AIForm, Edit_Phage_DataForm, Edit_ResearcherForm, Edit_ResearchForm, Edit_IsolationDataForm, Edit_Experiment_Form\nfrom PhageBank.core.forms import SignUpForm, UploadFileForm, LinkForm, LoginForm, Add_Phage_DataForm, Add_ResearcherForm, Add_Experiment_Form,Isolation_Form\nfrom PhageBank.core.models import PhageData, PreData, ExperimentData, IsolationData\nfrom django.forms.formsets import BaseFormSet\nfrom django.forms.formsets import formset_factory\nfrom django.forms import inlineformset_factory\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.template.loader import render_to_string\nfrom django.http import JsonResponse\nfrom django.template import RequestContext\nfrom django.contrib.messages import get_messages\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib import messages\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import PasswordChangeForm\n\nimport json\nimport os\nfrom csvvalidator import *\nimport datetime\nimport sqlite3\nimport pandas as pd\n\ndef count(dest_dir):\n count = 0;\n for filename in os.listdir(dest_dir):\n if filename.endswith(\".png\") or filename.endswith(\".jpg\") or filename.endswith(\".jpeg\"):\n count=count+1;\n continue\n return count\n\ndef list_path(dest_dir):\n list_path = [];\n for filename in os.listdir(dest_dir):\n if filename.endswith(\".png\") or filename.endswith(\".jpg\") or filename.endswith(\".jpeg\"):\n list_path.append(filename)\n continue\n return list_path\n\ndef logged_in_index(request):\n last_three = PhageData.objects.all().order_by('-id')[:3]\n dest_dir1=dest_dir2=dest_dir3= name1=name2=name3=\"\"\n count1 = count2 = count3 = -1\n try:\n name1 = last_three[0].phage_name\n dest_dir1 = list_path(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[0].phage_name))\n count1 = count(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[0].phage_name))\n except:\n pass\n\n try:\n name2 = last_three[1].phage_name\n dest_dir2 = list_path(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[1].phage_name))\n count2 = count(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[1].phage_name))\n\n except:\n pass\n\n try:\n name3 = last_three[2].phage_name\n dest_dir3 = list_path(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[2].phage_name))\n count3 = count(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[2].phage_name))\n\n except:\n pass\n return render(request, 'logged_in_index.html',{'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n 'phage1': name1,\n 'phage2': name2,\n 'phage3': name3,\n 'dest_dir1': dest_dir1,\n 'dest_dir2': dest_dir2,\n 'dest_dir3': dest_dir3,\n 'count1': count1,\n 'count2': count2,\n 'count3': count3\n })\n\ndef mylogout(request):\n logout(request)\n last_three = PhageData.objects.all().order_by('-id')[:3]\n dest_dir1 = dest_dir2 = dest_dir3 = name1 = name2 = name3 = \"\"\n count1 = count2 = count3 = -1\n try:\n name1 = last_three[0].phage_name\n dest_dir1 = list_path(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[0].phage_name))\n count1 = count(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[0].phage_name))\n except:\n pass\n\n try:\n name2 = last_three[1].phage_name\n dest_dir2 = list_path(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[1].phage_name))\n count2 = count(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[1].phage_name))\n\n except:\n pass\n\n try:\n name3 = last_three[2].phage_name\n dest_dir3 = list_path(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[2].phage_name))\n count3 = count(os.path.join(settings.MEDIA_ROOT, \"images\", last_three[2].phage_name))\n\n except:\n pass\n messages.success(request, 'You have successfully logged out.', extra_tags='alert')\n return render(request, 'logged_in_index.html',{'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n 'phage1': name1,\n 'phage2': name2,\n 'phage3': name3,\n 'dest_dir1': dest_dir1,\n 'dest_dir2': dest_dir2,\n 'dest_dir3': dest_dir3,\n 'count1': count1,\n 'count2': count2,\n 'count3': count3\n })\ndef signup(request):\n data = dict()\n\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n data['form_is_valid'] = True\n else:\n data['form_is_valid'] = False\n else:\n form = SignUpForm()\n\n context = {'form': form}\n data['html_form'] = render_to_string('partial_signup.html',\n context,\n request=request\n )\n return JsonResponse(data)\n\ndef mylogin(request):\n msg = dict()\n if request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n print (form.errors)\n username = request.POST['username']\n password = request.POST['password']\n if form.is_valid():\n msg['form_is_valid'] = True\n else:\n form.add_error('password', 'Please enter a correct username and password. Note that both fields are case-sensitive.')\n msg['form_is_valid'] = False\n\n if username and password:\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n msg['form_is_valid'] = True\n else:\n msg['form_is_valid'] = False\n else:\n form = AuthenticationForm()\n context = {'form': form}\n msg['html_form'] = render_to_string('partial_login.html',\n context,\n request=request\n )\n return JsonResponse(msg)\n\n\n@login_required\ndef change_password(request):\n if request.method == 'POST':\n form = PasswordChangeForm(request.user, request.POST)\n if form.is_valid():\n user = form.save()\n update_session_auth_hash(request, user)\n messages.success(request, 'Your password was successfully updated!')\n return redirect('logout')\n else:\n form = PasswordChangeForm(request.user)\n return render(request, 'change_password.html', {'form': form,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n })\n\n\ndef handle_uploaded_file(f, dest):\n with open(dest, 'wb') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n\n\n#Fill the model object in similar fashion\ndef fillExpObject(expform, phage):\n exp = ExperimentData.objects.create(expkey=phage)\n exp.expkey = phage\n exp.owner = expform.cleaned_data.get('owner')\n exp.timestamp = expform.cleaned_data.get('TimeStamp')\n exp.category = expform.cleaned_data.get('category')\n exp.short_name = expform.cleaned_data.get('short_name')\n exp.full_name = expform.cleaned_data.get('full_name')\n exp.methods = expform.cleaned_data.get('methods')\n exp.results = expform.cleaned_data.get('results')\n exp.save()\n\ndef fillExpObjectedit(expform, exp):\n exp.owner = expform.cleaned_data.get('owner')\n exp.timestamp = expform.cleaned_data.get('TimeStamp')\n exp.category = expform.cleaned_data.get('category')\n exp.short_name = expform.cleaned_data.get('short_name')\n exp.full_name = expform.cleaned_data.get('full_name')\n exp.methods = expform.cleaned_data.get('methods')\n exp.results = expform.cleaned_data.get('results')\n exp.save()\n\ndef fillIsoltionObject(isoform, phage):\n iso = IsolationData.objects.create(isokey=phage)\n iso.isokey = phage\n iso.owner_name = isoform.cleaned_data.get('owner_name')\n iso.location = isoform.cleaned_data.get('location')\n iso.type1 = isoform.cleaned_data.get('type1')\n iso.TimeStamp = isoform.cleaned_data.get('timestamp')\n iso.save()\n\ndef fillIsoltionObjectedit(isoform, iso):\n iso.owner_name = isoform.cleaned_data.get('owner_name')\n iso.location = isoform.cleaned_data.get('location')\n iso.type1 = isoform.cleaned_data.get('type')\n iso.TimeStamp = isoform.cleaned_data.get('TimeStamp')\n iso.save()\n\ndef validate_latest_phage(query_results):\n if(query_results.count()>0):\n latest = query_results.latest('id')\n return latest.phage_name\n else:\n return \"\"\n\n@login_required\ndef add_phage(request):\n if request.user.is_authenticated:\n if request.method == 'POST':\n pform = Add_Phage_DataForm(request.POST) #phage_name\n rrform = Add_ResearcherForm(request.POST)\n rform = Add_ResearchForm(request.POST) #CPT ID\n expform = Add_Experiment_Form(request.POST)\n isoform = Isolation_Form(request.POST)\n aform = AForm(request.POST, request.FILES)\n aiform = AIForm(request.POST)\n\n if pform.is_valid() and rrform.is_valid() and rform.is_valid() and expform.is_valid() and isoform.is_valid() \\\n and aform.is_valid() and aiform.is_valid():\n phagename = pform.cleaned_data.get('phage_name')\n CPTid = rform.cleaned_data.get('phage_CPT_id')\n\n #approvePhage = 1 if no duplicates in phage_name. 0 otherwise\n #approveCPTid = 1 if no duplicates in CPT id\n #duplicatePhagesPhages : list of phages due to duplicates in phage names\n #duplicatePhagesCPTid : list of CPT ids due to duplicates in phage names\n #duplicateCPTidPhages : list of phages due to duplicates in CPT ids\n #duplicateCPTidCPTid : list of duplicate CPT ids\n\n #chkDuplicatesFlag = 0\n chkDuplicatesFlag = int(request.POST['flag'])\n #chkDuplicatesFlag = 1\n\n msg = dict()\n\n if chkDuplicatesFlag==1:\n approvePhage, approveCPTid, duplicatePhagesPhages, duplicatePhagesCPTid, duplicateCPTidPhages\\\n , duplicateCPTidCPTid = checkDuplicatesInAddPhage(phagename, CPTid)\n\n print(approvePhage, approveCPTid)\n\n msg['approvePhage']=approvePhage\n msg['approveCPTid']=approveCPTid\n\n if (approvePhage==0 or approveCPTid==0):\n msg['duplicatePhagesPhages']=json.dumps(duplicatePhagesPhages)\n msg['duplicatePhagesCPTid']=json.dumps(duplicatePhagesCPTid)\n msg['duplicateCPTidPhages']=json.dumps(duplicateCPTidPhages)\n msg['duplicateCPTidCPTid']=json.dumps(duplicateCPTidCPTid)\n\n return JsonResponse(msg)\n\n pform.save()\n\n phage = PhageData.objects.get(phage_name=phagename)\n phage.phage_CPT_id = rform.cleaned_data.get('phage_CPT_id')\n phage.phage_isolator_loc = rform.cleaned_data.get('phage_isolator_loc')\n phage.phage_all_links = aiform.cleaned_data.get('link')\n phage.phage_isolator_name = rrform.cleaned_data.get('phage_isolator_name')\n phage.phage_experimenter_name = rrform.cleaned_data.get('phage_experimenter_name')\n phage.phage_submitted_user = request.user.username\n phage.phage_lab = rrform.cleaned_data.get('phage_lab')\n\n phage.save()\n fillIsoltionObject(isoform, phage)\n\n fillExpObject(expform, phage)\n # print(phage.phage_submitted_user)\n phagedoc = aform.cleaned_data.get('doc')\n phageimage = aform.cleaned_data.get('image')\n dest_dir = os.path.join(settings.MEDIA_ROOT, \"images\", phagename)\n docs_dest_dir = os.path.join(settings.MEDIA_ROOT, \"docs\", phagename)\n try:\n os.mkdir(dest_dir)\n os.mkdir(docs_dest_dir)\n except:\n pass\n dest = os.path.join(dest_dir, str(phageimage))\n docsdest = os.path.join(docs_dest_dir, str(phagedoc))\n if phageimage is None:\n pass\n else:\n handle_uploaded_file(phageimage, dest)\n if phagedoc is None:\n pass\n else:\n handle_uploaded_file(phagedoc, docsdest)\n\n # query_results = PhageData.objects.all()\n\n return JsonResponse(msg)\n\n #if the data is valid\n #render(request, 'view_phages.html', {'add_status':'true','query_results':query_results} )\n #render(request, 'view_phages.html', {'add_status':'true','query_results':query_results ,\n # 'login_status': request.user.is_authenticated,\n # 'username': request.user.username})\n\n else:\n pform.add_error(\"phage_name\",\"This field is required.\")\n rform.add_error(\"phage_CPT_id\",\"This field is required.\")\n return render(request, 'add_phage.html', {'pform': pform,\n 'rrform': rrform,\n 'rform': rform,\n 'expform': expform,\n 'isoform': isoform,\n 'aform': aform,\n 'aiform': aiform,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n })\n else:\n pform = Add_Phage_DataForm()\n rrform = Add_ResearcherForm()\n rform = Add_ResearchForm()\n expform = Add_Experiment_Form()\n isoform = Isolation_Form()\n aform = AForm()\n aiform = AIForm()\n return render(request, 'add_phage.html', {'pform': pform,\n 'rrform': rrform,\n 'rform': rform,\n 'expform': expform,\n 'isoform':isoform,\n 'aform': aform,\n 'aiform': aiform,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n })\n#this form show the phages per user\ndef my_phages(request):\n query_results = PhageData.objects.filter(phage_submitted_user=request.user.username)\n name = validate_latest_phage(query_results)\n return render(request, 'view_phages.html', {'query_results': query_results,\n 'edit_status':'false','add_status':'false',\n 'delete_status':'false','latest':name,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username\n })\n#this form shows all the phages\ndef view_phages(request):\n query_results = PhageData.objects.all()\n name = validate_latest_phage(query_results)\n return render(request, 'view_phages.html', {'query_results': query_results,\n 'edit_status': 'false', 'add_status': 'false',\n 'delete_status': 'false', 'latest': name,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username\n })\n \n \ndef about_us(request):\n query_results = PhageData.objects.all()\n name = validate_latest_phage(query_results)\n return render(request, 'about_us.html', {'query_results': query_results,\n 'edit_status': 'false', 'add_status': 'false',\n 'delete_status': 'false', 'latest': name,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username\n })\n \n\ndef peoples(request):\n query_results = PhageData.objects.all()\n name = validate_latest_phage(query_results)\n return render(request, 'peoples.html', {'query_results': query_results,\n 'edit_status': 'false', 'add_status': 'false',\n 'delete_status': 'false', 'latest': name,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username\n })\n \n\ndef articles(request):\n query_results = PhageData.objects.all()\n name = validate_latest_phage(query_results)\n return render(request, 'articles.html', {'query_results': query_results,\n 'edit_status': 'false', 'add_status': 'false',\n 'delete_status': 'false', 'latest': name,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username\n }) \n \n \ndef contact_us(request):\n query_results = PhageData.objects.all()\n name = validate_latest_phage(query_results)\n return render(request, 'contact_us.html', {'query_results': query_results,\n 'edit_status': 'false', 'add_status': 'false',\n 'delete_status': 'false', 'latest': name,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username\n }) \n \n \n@user_passes_test(lambda u: u.is_superuser, login_url='/admin/')\ndef delele_all_phages(request):\n phage = PhageData.objects.all().delete()\n query_results = PhageData.objects.all()\n return render(request, 'view_phages.html', {'query_results': query_results,\n 'edit_status':'false','add_status':'false',\n 'delete_status':'false',\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username\n })\n#this form shows a particular phage\ndef view_phage(request):\n phageName = request.GET.get('name')\n phage = PhageData.objects.get(phage_name=phageName)\n previous_names = phage.PhageName.all()\n expdata = phage.PName.all()\n isodata = phage.iso_phageName.all()\n dest_dir = os.path.join(settings.MEDIA_ROOT, \"images\", phageName)\n list_path=[]\n count = 0;\n try:\n for filename in os.listdir(dest_dir):\n if filename.endswith(\".png\") or filename.endswith(\".jpg\") or filename.endswith(\".jpeg\"):\n list_path.append(filename)\n count=count+1;\n continue\n else:\n continue\n except:\n pass\n return render(request, 'view_phage.html', {'item': phage,'previous_names':previous_names,'expdata':expdata,'isodata':isodata,\n 'login_status': request.user.is_authenticated,'dest_dir':list_path,'count':count,\n 'username': request.user.username\n })\n\n@login_required\ndef deletephages(request):\n if request.user.is_authenticated:\n x = request.GET.get('name')\n dest_dir = os.path.join(settings.MEDIA_ROOT, \"images\", x)\n docs_dest_dir = os.path.join(settings.MEDIA_ROOT, \"docs\", x)\n try:\n os.rmdir(dest_dir)\n os.rmdir(docs_dest_dir)\n except:\n pass\n phage = PhageData.objects.get(phage_name=x).delete()\n query_results = PhageData.objects.all()\n name = validate_latest_phage(query_results)\n return render(request, 'view_phages.html', {'query_results': query_results,'delete_status':'true',\n 'login_status': request.user.is_authenticated,'latest':name,\n 'username': request.user.username\n })\n else:\n #messages.error(request,'Login or signup first!')\n return render(request,'login.html',\n {'login_status': request.user.is_authenticated\n })\n\n\ndef search_phage(request):\n phage_list = PhageData.objects.all()\n request.GET._mutable = True\n print(\"$$$$\")\n if request.GET.get('submitted_year_gt'):\n #print(request.GET['submitted_year_gt'])\n if int(request.GET.get('submitted_year_gt')) < 0:\n messages.error(request, 'Invalid value for \"Year Submitted After\" entered. Setting it to 1')\n request.GET['submitted_year_gt'] = 1\n #print(request.GET['submitted_year_gt'])\n if request.GET.get('submitted_year_lt'):\n if int(request.GET.get('submitted_year_lt')) < 0:\n messages.error(request, 'Invalid value for \"Year Submitted Before\" entered. Setting it to 1')\n request.GET['submitted_year_lt'] = 1\n if request.GET.get('submitted_month_gt'):\n if int(request.GET.get('submitted_month_gt')) < 0:\n messages.error(request, 'Invalid value for \"Month Submitted After\" entered. Setting it to 1')\n request.GET['submitted_month_gt'] = 1\n if request.GET.get('submitted_month_lt'):\n if int(request.GET.get('submitted_month_lt')) < 0:\n messages.error(request, 'Invalid value for \"Month Submitted Before\" entered. Setting it to 1')\n request.GET['submitted_month_lt'] = 1\n\n phage_filter = PhageFilter(request.GET, queryset=phage_list)\n return render(request, 'search_phage.html', {'filter': phage_filter,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n })\n\ndef check_entry(name):\n print(PhageData.objects.filter(phage_name=name).count())\n if (PhageData.objects.filter(phage_name=name).count() == 0 and PreData.objects.filter(phagename=name).count()==0 ):\n return False\n else:\n return True\n\n@login_required\ndef editPhage(request):\n if request.user.is_authenticated:\n name = request.GET.get('name')\n phage = PhageData.objects.get(phage_name = name)\n isodata = IsolationData.objects.filter(isokey = phage)\n expdata = ExperimentData.objects.filter(expkey = phage)\n last = isodata.latest('id')\n last_exp = expdata.latest('id')\n pform = Edit_Phage_DataForm(request.POST, instance=phage, initial = {'phage_name':phage.phage_name })\n rrform = Edit_ResearcherForm(request.POST, instance=phage)\n rform = Edit_ResearchForm(request.POST, instance=phage)\n isoform = Edit_IsolationDataForm(request.POST)\n expform = Edit_Experiment_Form(request.POST)\n aform = AForm(request.POST, request.FILES)\n aiform = AIForm(request.POST)\n if request.method==\"POST\":\n if pform.is_valid() and rrform.is_valid() and rform.is_valid() and aform.is_valid() and aiform.is_valid()\\\n and isoform.is_valid() and expform.is_valid():\n curr_phage = pform.cleaned_data.get('phage_name')\n if(check_entry(curr_phage) and curr_phage!=name):\n return render(request, 'EditPhage.html', {'item': phage,\n 'pform': pform,\n 'rrform': rrform,'expform':expform,\n 'rform': rform,\n 'aform': aform,\n 'aiform': aiform,'duplicate':'true',\n 'isoform':isoform,'iso':last,'exp':last_exp,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n })\n phage.phage_name = curr_phage\n if(name!=phage.phage_name and PreData.objects.filter(phagename = name).count()==0):\n obj = PreData.objects.create(testkey=phage)\n obj.testkey = phage\n obj.phagename = name\n print (obj.phagename)\n obj.save()\n print (phage.PhageName.all().values())\n #phage = PhageData.objects.get(phage_name=phagename)\n phage.phage_isolator_name = rrform.cleaned_data.get('phage_isolator_name')\n phage.phage_experimenter_name = rrform.cleaned_data.get('phage_experimenter_name')\n phage.phage_CPT_id = rform.cleaned_data.get('phage_CPT_id')\n phage.phage_isolator_loc = rform.cleaned_data.get('phage_isolator_loc')\n phage.phage_all_links = aiform.cleaned_data.get('link')\n phage.phage_lab = rrform.cleaned_data.get('phage_lab')\n #isolator_data = phage.iso_phageName.objects.latest(iso_phageName)\n pform.save()\n phage.save()\n #last.delete()\n fillExpObjectedit(expform, last_exp)\n fillIsoltionObjectedit(isoform, last)\n phagedoc = aform.cleaned_data.get('doc')\n phageimage = aform.cleaned_data.get('image')\n dest_dir_old = os.path.join(settings.MEDIA_ROOT, \"images\", name)\n docs_dest_dir_old = os.path.join(settings.MEDIA_ROOT, \"docs\", name)\n dest_dir = os.path.join(settings.MEDIA_ROOT, \"images\", phage.phage_name)\n docs_dest_dir = os.path.join(settings.MEDIA_ROOT, \"docs\", phage.phage_name)\n try:\n os.rename(dest_dir_old,dest_dir)\n os.rename(docs_dest_dir_old,docs_dest_dir)\n except:\n pass\n dest = os.path.join(dest_dir, str(phageimage))\n docsdest = os.path.join(docs_dest_dir, str(phagedoc))\n if phageimage is None:\n pass\n else:\n handle_uploaded_file(phageimage, dest)\n if phagedoc is None:\n pass\n else:\n handle_uploaded_file(phagedoc, docsdest)\n query_results = PhageData.objects.all()\n lname = validate_latest_phage(query_results)\n return render(request, 'view_phages.html', {'edit_status':'true','query_results':query_results,'latest':lname,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username} )\n else:\n phage = PhageData.objects.get(phage_name=name)\n phage.save()\n return render(request, 'EditPhage.html', {'item': phage,\n 'pform': pform,\n 'rrform': rrform,'expform':expform,\n 'rform': rform,\n 'aform': aform,\n 'aiform': aiform,\n 'isoform':isoform,'iso':last,'exp':last_exp,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n })\n else:\n pform = Edit_Phage_DataForm(request.POST, instance=phage)\n rrform = Edit_ResearcherForm(request.POST, instance=phage)\n rform = Edit_ResearchForm(request.POST, instance=phage)\n isoform = Edit_IsolationDataForm(request.POST)\n expform = Edit_Experiment_Form(request.POST)\n aform = AForm()\n aiform = AIForm()\n return render(request, 'EditPhage.html', {'item': phage,\n 'pform': pform,\n 'rrform': rrform,\n 'rform': rform,\n 'aform': aform,\n 'aiform': aiform, 'isoform' : isoform,'expform':expform,\n 'iso':last,\n 'exp': last_exp,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username,\n })\n else:\n return render(request,'Login.html',\n {'login_status': request.user.is_authenticated\n })\n\n\ndef func(phagename):\n dest_dir = os.path.join(settings.MEDIA_ROOT, \"images\", phagename)\n docs_dest_dir = os.path.join(settings.MEDIA_ROOT, \"docs\", phagename)\n try:\n os.mkdir(dest_dir)\n os.mkdir(docs_dest_dir)\n except:\n pass\n\n\ndef populate(reader, request):\n fields = reader.fieldnames\n for row in reader:\n flag = 0\n obj = PhageData.objects.create()\n iso = IsolationData.objects.create(isokey = obj)\n exp = ExperimentData.objects.create(expkey = obj)\n if 'phage_name' in fields:\n name = row['phage_name']\n if not name:\n flag = 0\n elif(PhageData.objects.filter(phage_name=name).count() == 0 and PreData.objects.filter(phagename=name).count() == 0):\n obj.phage_name = name\n else:\n obj.delete()\n exp.delete()\n iso.delete()\n if (PhageData.objects.filter(phage_name=name).count() > 0):\n obj = PhageData.objects.get(phage_name=name)\n else:\n obj1 = PreData.objects.get(phagename=name)\n obj = obj1.testkey\n\n isodata = IsolationData.objects.filter(isokey=obj)\n expdata = ExperimentData.objects.filter(expkey=obj)\n iso = isodata.latest('id')\n exp = expdata.latest('id')\n flag = 1\n if 'phage_host_name' in fields:\n obj.phage_host_name = row['phage_host_name']\n if 'phage_isolator_name' in fields:\n obj.phage_isolator_name = row['phage_isolator_name']\n if 'phage_experimenter_name' in fields:\n obj.phage_experimenter_name = row['phage_experimenter_name']\n if 'phage_CPT_id' in fields:\n obj.phage_CPT_id = row['phage_CPT_id']\n if 'phage_isolator_loc' in fields:\n obj.phage_isolator_loc = row['phage_isolator_loc']\n if 'owner_name' in fields:\n iso.owner_name = row['owner_name']\n if 'location' in fields:\n iso.location = row['location']\n if 'type' in fields:\n iso.type = row['type']\n if 'TimeStamp' in fields:\n iso.TimeStamp = row['TimeStamp']\n if 'owner' in fields:\n exp.owner = row['owner']\n if 'timestamp' in fields:\n exp.timestamp = row['timestamp']\n if 'methods' in fields:\n exp.methods = row['methods']\n if 'results' in fields:\n exp.results = row['results']\n if 'short_name' in fields:\n exp.short_name = row['short_name']\n if 'full_name' in fields:\n exp.full_name = row['full_name']\n if 'category' in fields:\n exp.category = row['category']\n obj.phage_submitted_user = request.user.username\n\n if flag == 0:\n obj.delete()\n exp.delete()\n iso.delete()\n else:\n obj.save()\n func(obj.phage_name)\n iso.save()\n exp.save()\n\n\n\n@user_passes_test(lambda u: u.is_superuser, login_url='/admin/')\ndef model_form_upload(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n paramFile = TextIOWrapper(request.FILES['file'].file, encoding=request.encoding)\n reader = csv.DictReader(paramFile,delimiter=';',skipinitialspace=True,)\n populate(reader, request)\n query_results = PhageData.objects.all()\n lname = validate_latest_phage(query_results)\n return render(request, 'view_phages.html', {'query_results': query_results,\n 'edit_status': 'false', 'add_status': 'false',\n 'delete_status': 'false','latest':lname,\n 'login_status': request.user.is_authenticated,\n 'username': request.user.username\n })\n else:\n form = UploadFileForm()\n return render(request, 'model_form_upload.html', {'form': form,'login_status': request.user.is_authenticated,\n 'username': request.user.username})\n\ndef checkDuplicatesInAddPhage(phage_name, phage_CPT_id):\n #db=sqlite3.connect('db.sqlite3')\n #params={'phage_name':phage_name, 'phage_CPT_id':phage_CPT_id}\n #q1=\"SELECT phage_name, phage_CPT_id FROM core_phagedata WHERE phage_name='{phage_name}'\"\n #rowsPhage = pd.read_sql_query(q1.format(**params), db)\n\n rowsPhage = PhageData.objects.filter(phage_name = phage_name).values('phage_name','phage_CPT_id')\n #.values() is a list of dict\n\n rowsCPTid = PhageData.objects.filter(phage_CPT_id = phage_CPT_id).values('phage_name','phage_CPT_id')\n\n duplicatePhagesPhages = [d['phage_name'] for d in rowsPhage] # rowsPhage[\"phage_name\"].values.tolist()\n #print(duplicatePhagesPhages)\n\n duplicatePhagesCPTid = [d['phage_CPT_id'] for d in rowsPhage]\n\n duplicateCPTidPhages = [d['phage_name'] for d in rowsCPTid]\n duplicateCPTidCPTid = [d['phage_CPT_id'] for d in rowsCPTid]\n\n approvePhage=1\n approveCPTid=1\n if len(rowsPhage)>0:\n approvePhage=0\n\n if len(rowsCPTid)>0:\n approveCPTid=0\n\n return approvePhage, approveCPTid, duplicatePhagesPhages, duplicatePhagesCPTid, duplicateCPTidPhages\\\n , duplicateCPTidCPTid\n\n#def checkDuplicatesInFile(decoded_file):\n# db=sqlite3.connect('db.sqlite3')\n# io_string = io.StringIO(decoded_file)\n# \n# phage_names=[]\n# \n# for line in csv.reader(io_string, delimiter=','):\n# phage_names.append(line[0])\n# \n# df=pd.read_sql_query('SELECT phage_name FROM core_phagedata',db)\n# \n# stored_phages = df[\"phage_name\"].values.tolist()\n# \n# common_phages = set(phage_names).intersection(stored_phages)\n# \n# approveFlag=1\n# if len(common_phages)>0:\n# approveFlag=0\n# \n# #print(common_phages)\n# return common_phages, approveFlag\n\n\n\n\n\n\n\n\n\n\n","sub_path":"PhageBank/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":39284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"635601146","text":"# built-in libraries\nimport datetime\n\n# external libraries\nimport pytz\n\n# internal libraries\nfrom ouroboros import Type, Image, Node\nfrom ouroboros.config import MILLI, UNIX_EPOCH\n\n# exports\n__all__= (\"dt\", \"td\",\n \"at\", \"after\", \"every\",\n \"relate\", \"iso8601\")\n\n# constants\n# ...\n\n# datetime.datetime <-> JSON\ndt = Type(\"!clock/dt\", datetime.datetime,\n lambda x: int((x - UNIX_EPOCH).total_seconds() / MILLI),\n lambda x: UNIX_EPOCH + datetime.timedelta(seconds=x * MILLI))\n\n# datetime.timedelta <-> JSON\ntd = Type(\"!clock/td\", datetime.timedelta,\n lambda x: int(x.total_seconds() / MILLI),\n lambda x: datetime.timedelta(seconds=x * MILLI))\n\n\n@Image(\".clock@at\",\n sys=Node(evs=(\"tick\",), args=(),\n ins=(), reqs=(\"t\",),\n outs=(), pros=()),\n usr=Node(evs=(), args=(),\n ins=(), reqs=(),\n outs=(\"tock\",), pros=()))\ndef at(sys, usr):\n \"\"\"at\"\"\" \n yield\n while True:\n sys_t, = sys.reqs\n yield (usr.outs((sys_t,)),)\n\n\n@Image(\".clock@after\",\n env=Node(evs=(), args=(),\n ins=(), reqs=(\"t\",),\n outs=(), pros=()),\n sys=Node(evs=(\"tick\",), args=(),\n ins=(), reqs=(\"delta_t\",),\n outs=(), pros=()),\n usr=Node(evs=(), args=(),\n ins=(), reqs=(),\n outs=(\"tock\",), pros=()))\ndef after(env, sys, usr):\n \"\"\"after\"\"\"\n yield\n while True:\n env_t, = env.reqs\n delta_t, = sys.reqs\n yield (usr.outs((env_t + delta_t,)),)\n\n\n@Image(\".clock@every\",\n env=Node(evs=(\"tick\",), args=(\"t\",),\n ins=(), reqs=(),\n outs=(), pros=()),\n sys=Node(evs=(\"tick\",), args=(\"delta_t\",),\n ins=(), reqs=(),\n outs=(\"tick\",), pros=()),\n kw=Node(evs=(), args=(),\n ins=(), reqs=(),\n outs=(\"tock\",), pros=()))\ndef every(env, sys, **kw):\n \"\"\"every\"\"\"\n env_t, = env.args\n delta_t, = sys.args\n \n yield\n while True:\n env_t += delta_t\n yield ((sys.outs((env_t,)),) +\n tuple(usr.outs((True,))\n for usr in kw.values()))\n\n\n@Image(\".clock@relate\",\n sys=Node(evs=(\"tock\",), args=(),\n ins=(), reqs=(\"t\",),\n outs=(), pros=()),\n usr=Node(evs=(), args=(),\n ins=(), reqs=(\"t\",),\n outs=(\"lt\", \"eq\", \"gt\"), pros=()))\ndef relate(sys, usr):\n \"\"\"relate\"\"\"\n evs = yield\n while True:\n sys_t, = env.reqs\n usr_t, = usr.reqs\n yield (usr.outs((sys_t < usr_t,\n sys_t == usr_t,\n sys_t > usr_t)),)\n\n\n@Image(\".clock@iso8601\",\n sys=Node(evs=(), args=(),\n ins=(), reqs=(\"t\",),\n outs=(), pros=()),\n usr=Node(evs=(\"tock\",), args=(),\n ins=(\"tock\", 8601,), reqs=(),\n outs=(8601,), pros=(\"t_dt\",)))\ndef iso8601(sys, usr):\n evs = yield\n while True:\n sys_t, = sys.reqs\n clk_e, usr_e = usr.ins()\n flag = usr_e not in evs\n if flag:\n usr.pros = (datetime.datetime.fromtimestamp\n (sys_t, tz=pytz.utc),)\n yield (usr.outs((flag or None,)),)\n","sub_path":"ob-time/ob-time/clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"159243354","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport logging\nfrom typing import List\n\n#from eco_kg.transform_utils.eol_hierarchy.eol_hierarchy import EOLheirarchyTransform\nfrom eco_kg.transform_utils.ontology import OntologyTransform\nfrom eco_kg.transform_utils.ontology.ontology_transform import ONTOLOGIES\nfrom eco_kg.transform_utils.eol_traits.eol_traits import EOLTraitsTransform\nfrom eco_kg.transform_utils.planteome.planteome import PlanteomeTransform\nfrom eco_kg.transform_utils.gene_expression_atlas.gene_expression_atlas import GeneExpressionAtlasTransform\n\n\nDATA_SOURCES = {\n #'EOLheirarchyTransform': EOLheirarchyTransform,\n 'GoTransform': OntologyTransform,\n #'HpTransform': OntologyTransform,\n 'NCBITransform': OntologyTransform,\n #'EnvoTransform' : OntologyTransform,\n 'ToTransform' : OntologyTransform,\n 'PoTransform' : OntologyTransform,\n #'PecoTransform' : OntologyTransform,\n 'EOLTraitsTransform': EOLTraitsTransform,\n 'PlanteomeTransform': PlanteomeTransform,\n 'GeneExpressionAtlasTransform':GeneExpressionAtlasTransform\n}\n\n\ndef transform(input_dir: str, output_dir: str, sources: List[str] = None) -> None:\n \"\"\"Call scripts in eco_kg/transform/[source name]/ to transform each source into a graph format that\n KGX can ingest directly, in either TSV or JSON format:\n https://github.com/NCATS-Tangerine/kgx/blob/master/data-preparation.md\n Args:\n input_dir: A string pointing to the directory to import data from.\n output_dir: A string pointing to the directory to output data to.\n sources: A list of sources to transform.\n Returns:\n None.\n \"\"\"\n if not sources:\n # run all sources\n sources = list(DATA_SOURCES.keys())\n\n for source in sources:\n if source in DATA_SOURCES:\n logging.info(f\"Parsing {source}\")\n t = DATA_SOURCES[source](input_dir, output_dir)\n if source in ONTOLOGIES.keys():\n t.run(ONTOLOGIES[source])\n else:\n t.run()","sub_path":"eco_kg/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51779132","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport os, sys, yaml, re, uuid\nimport datetime\nimport jinja2\n\nclass AsiaTokyoTimezone(datetime.tzinfo):\n def utcoffset(self, dt):\n return datetime.timedelta(hours=9)\n \n def dst(self, dt):\n return datetime.timedelta(hours=9)\n \n def tzname(self, dt):\n return 'Asia/Tokyo'\n\nTZ = AsiaTokyoTimezone()\n\nBASE_DIR = os.path.abspath(os.getcwd())\nDEFAULT_DIR = os.path.join(BASE_DIR, '_posts')\nDEFAULT_CONF_FILE = os.path.join(BASE_DIR, '_config.yml')\nTEMPLATE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'jekyll-template.md')\n\nimport argparse\n\ndef parse_args(*args):\n parser = argparse.ArgumentParser(description=\"Process some integers.\")\n parser.add_argument('title', action=\"store\")\n parser.add_argument('-t', '--timestamp', default=False, action=\"store_true\")\n parser.add_argument('-c', '--config', default=DEFAULT_CONF_FILE, action=\"store\")\n parser.add_argument('-o', '--directory', default=DEFAULT_DIR, action=\"store\")\n args = parser.parse_args(args)\n return args\n\ndef write(dst, data):\n if not os.path.exists(dst):\n with open(dst, 'w') as fp:\n fp.write(data.encode('utf8'))\n else:\n print('ERROR: File already exists.', file=sys.stderr)\n\ndef main(*args):\n args = parse_args(*args)\n timestamp = args.timestamp\n time_now = datetime.datetime.now(tz=TZ)\n time_date = time_now.strftime('%Y-%m-%d')\n title_lower = args.title.lower()\n title = re.sub(r' ', '-', title_lower)\n if timestamp:\n file_name = time_date + '-' + title + '.md'\n else:\n file_name = title + '.md'\n #dst_dir = os.path.dirname(os.path.abspath(__file__))\n dst = os.path.join(args.directory, file_name)\n with open(DEFAULT_CONF_FILE, 'r') as fp:\n config_data = fp.read()\n config_obj = yaml.load(config_data)\n with open(TEMPLATE_FILE, 'r') as fp:\n template_data = fp.read()\n template_context = {}\n template_context.update({'page': {'title': args.title,\n 'current_time': time_now,\n 'uuid': str(uuid.uuid4())}})\n template_context.update({'site': config_obj})\n template_result = jinja2.Template(template_data).render(template_context)\n print(dst)\n write(dst, template_result)\n return 0\n\nif __name__ == '__main__':\n sys.exit(main(*sys.argv[1:]))\n\n","sub_path":"jekyll_create_file.py","file_name":"jekyll_create_file.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"536601489","text":"class Cat:\r\n def __init__(self, name):\r\n self.name = name\r\n self.fed = False\r\n self.sleepy = False\r\n self.size = 0\r\n\r\n def eat(self):\r\n if self.fed:\r\n raise Exception(\"Already fed.\")\r\n self.fed = True\r\n self.sleepy = True\r\n self.size += 1\r\n\r\n def sleep(self):\r\n if not self.fed:\r\n raise Exception(\"Cannot sleep while hungry\")\r\n self.sleepy = False\r\n\r\n\r\nimport unittest\r\n\r\n\r\nclass TestCase(unittest.TestCase):\r\n def test_cat_if_size_increase_after_eating(self):\r\n cat = Cat('Akira')\r\n cat.eat()\r\n self.assertEqual(1, cat.size)\r\n\r\n def test_cat_if_fed_after_eating(self):\r\n cat = Cat('Akira')\r\n cat.eat()\r\n self.assertTrue(cat.fed)\r\n\r\n def test_cat_already_fet(self):\r\n cat = Cat('Akira')\r\n self.assertFalse(cat.fed)\r\n cat.eat()\r\n self.assertTrue(cat.fed)\r\n with self.assertRaises(Exception) as ex:\r\n cat.eat()\r\n self.assertEqual(\"Already fed.\", str(ex.exception))\r\n\r\n def test_cat_sleep_if_not_fed(self):\r\n cat = Cat('Akira')\r\n self.assertFalse(cat.fed)\r\n with self.assertRaises(Exception) as ex:\r\n cat.sleep()\r\n self.assertEqual(\"Cannot sleep while hungry\", str(ex.exception))\r\n\r\n def test_cat_is_not_sleepy_after_sleeping(self):\r\n cat = Cat('Akira')\r\n cat.eat()\r\n cat.sleep()\r\n self.assertFalse(cat.sleepy)\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"9.Testing/Lab/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"594724967","text":"from typing import Callable, List\n\nimport torch\nimport torch.nn as nn\n\nfrom torecsys.layers import InnerProductNetworkLayer, OuterProductNetworkLayer, DNNLayer\nfrom torecsys.utils.decorator import no_jit_experimental_by_namedtensor\nfrom torecsys.utils.operations import combination\nfrom . import _CtrModel\n\n\nclass ProductNeuralNetworkModel(_CtrModel):\n r\"\"\"Model class of Product Neural Network (PNN).\n\n Product Neural Network is a model using inner-product or outer-product to extract high \n dimensional non-linear relationship from interactions of feature tensors instead, where \n the process is handled by factorization machine part in Factorization-machine supported \n Neural Network (FNN).\n\n :Reference:\n\n #. `Yanru QU, 2016. Product-based Neural Networks for User Response Prediction `_.\n\n \"\"\"\n\n @no_jit_experimental_by_namedtensor\n def __init__(self,\n embed_size: int,\n num_fields: int,\n deep_layer_sizes: List[int],\n output_size: int = 1,\n prod_method: str = \"inner\",\n deep_dropout_p: List[float] = None,\n deep_activation: Callable[[torch.Tensor], torch.Tensor] = nn.ReLU(),\n **kwargs):\n r\"\"\"Initialize ProductNeuralNetworkModel\n \n Args:\n embed_size (int): Size of embedding tensor\n num_fields (int): Number of inputs' fields\n deep_layer_sizes (List[int]): Layer sizes of dense network\n output_size (int): Output size of model\n i.e. output size of dense network. \n Defaults to 1.\n prod_method (str): Method of product neural network. \n Allow: [inner, outer].\n Defaults to inner.\n deep_dropout_p (List[float], optional): Probability of Dropout in dense network. \n Defaults to None.\n deep_activation (Callable[[T], T], optional): Activation function of dense network. \n Defaults to nn.ReLU().\n \n Arguments:\n kernel_type (str): Type of kernel to compress outer-product.\n \n Attributes:\n pnn (nn.Module): Module of product neural network.\n deep (nn.Module): Module of dense layer.\n bias (nn.Parameter): Parameter of bias of field-aware factorization machine.\n\n Raises:\n ValueError: when prod_method is not in [inner, outer].\n \"\"\"\n # Refer to parent class\n super(ProductNeuralNetworkModel, self).__init__()\n\n # Initialize product network\n if prod_method == \"inner\":\n self.pnn = InnerProductNetworkLayer(num_fields=num_fields)\n elif prod_method == \"outer\":\n self.pnn = OuterProductNetworkLayer(embed_size=embed_size,\n num_fields=num_fields,\n kernel_type=kwargs.get(\"kernel_type\", \"mat\"))\n else:\n raise ValueError(\"'%s' is not allowed in prod_method. Please use ['inner', 'outer'].\")\n\n # Calculate size of inputs of dense layer\n cat_size = combination(num_fields, 2) + num_fields + 1\n\n # Initialize dense layer\n self.deep = DNNLayer(\n output_size=output_size,\n layer_sizes=deep_layer_sizes,\n inputs_size=cat_size,\n dropout_p=deep_dropout_p,\n activation=deep_activation\n )\n\n # Initialize bias parameter\n self.bias = nn.Parameter(torch.zeros((1, 1), names=(\"B\", \"O\")))\n nn.init.uniform_(self.bias.data)\n\n def forward(self, feat_inputs: torch.Tensor, emb_inputs: torch.Tensor) -> torch.Tensor:\n \"\"\"Forward calculation of ProductNeuralNetworkModel\n \n Args:\n feat_inputs (T), shape = (B, N, E = 1), dtype = torch.float: Features tensors.\n emb_inputs (T), shape = (B, N, E), dtype = torch.float: Embedded features tensors.\n \n Returns:\n T, shape = (B, O), dtype = torch.float: Output of ProductNeuralNetworkModel\n \"\"\"\n # Get batch size from emb_inputs\n b = emb_inputs.size(\"B\")\n\n # Aggregate feat_inputs on dimension N and rename dimension O to E\n # inputs: feat_inputs, shape = (B, N, E = 1)\n # output: pnn_first, shape = (B, O = N)\n pnn_first = feat_inputs.flatten([\"N\", \"E\"], \"O\")\n\n # Calculate product cross features by pnn layer \n # inputs: emb_inputs, shape = (B, N, E)\n # with output's shape = (B, NC2)\n pnn_second = self.pnn(emb_inputs)\n\n # Concat pnn_second, pnn_first and bias on dimension O\n # inputs: pnn_second, shape = (B, O = NC2)\n # inputs: pnn_first, shape = (B, O = N)\n # inputs: bias, shape = (B, O = 1)\n # output: outputs, shape = (B, O = 1)\n outputs = torch.cat([pnn_second, pnn_first, self.bias], dim=\"O\")\n\n # Calculate with deep layer forwardly\n # inputs: outputs, shape = (B, O = (NC2 + N + 1))\n # output: outputs, shape = (B, O)\n outputs = self.deep(outputs)\n\n # Drop names of outputs, since autograd doesn't support NamedTensor yet.\n outputs = outputs.rename(None)\n\n return outputs\n","sub_path":"torecsys/models/ctr/product_neural_network.py","file_name":"product_neural_network.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"395074465","text":"from __future__ import absolute_import\nimport os\nfrom celery import Celery\nfrom django.conf import settings\nfrom client.client import Job\n\n# set the default Django settings module for the 'celery' program.\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'collins.settings.dev')\napp = Celery('api')\n\n# Using a string here means the worker will not have to\n# pickle the object when using Windows.\napp.config_from_object('django.conf:settings')\napp.autodiscover_tasks(lambda: settings.INSTALLED_APPS)\n\n@app.task(bind=True)\ndef ping(self):\n return \"Pong\"\n\n@app.task(bind=True)\ndef add(self, x, y):\n return x + y\n\n@app.task(bind=True, ignore_result=False)\ndef execute_job(self, job):\n print(\"Executing Job {}\".format(job['id']))\n job = Job(json=job)\n result = job.execute()\n print(result)\n print(\"Job results are ready\")\n return result.json()\n","sub_path":"api/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"608195289","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport xlrd\nimport requests\n\n# өгөгдлүүдээ http://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/slr/frames/slr05.html \n# хаяг дээрхи Чикаго хотын гал болон гэмт хэргийн гаралтын хамаарлын \n# судалгааг агуулсан excel файлаас татаж авч уншаад numpy массив болгож хадгална\ndata_url = \"http://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/slr/excel/slr05.xls\"\nu = requests.get(data_url)\nbook = xlrd.open_workbook(file_contents=u.content, encoding_override=\"utf-8\")\nsheet = book.sheet_by_index(0)\ndata = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])\nn_samples = sheet.nrows-1\n\n# гал гаралтын тоо тэмжээг илтгэх оролтын X placeholder\nX = tf.placeholder(tf.float32, name=\"X\")\n# гэмт хэргийн гаралтын тоо хэмжээг илтгэх гаралтын Y placeholder\nY = tf.placeholder(tf.float32, name=\"Y\")\n\n# 0 утгаар цэнэглэсэн жин болон биас утгууд\nw = tf.Variable(0., name=\"weights\")\nb = tf.Variable(0., name=\"bias\")\n\n# гал гаралтын тооноос гэмт хэргийн гаралтыг тооцон олох\n# шугам регрессийн модел\nY_predicted = X*w+b\n\n# алдааны квадрат утгыг төлөөлөх loss функц\nloss = tf.square(Y-Y_predicted, name='loss')\n\n# gradient descent алгоритм хэрэглэн 0.01 хэмжээтэйгээр суралцуулж\n# loss утгыг минимумчилна\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)\n\n# регрессийн цэгүүдийг зурж харуулах\nplt.xlabel('Гал гаралтын тоо хэмжээ')\nplt.ylabel('Гэмт хэргийн гаралтын тоо')\nplt.scatter(data[:, 0], data[:, 1])\nx_plot = np.linspace(0, 50, 100)\nplt.ion() # графикийг тусдаа процесстой цонх болгон харуулах\n\nwith tf.Session() as sess:\n # шаардлагатай хувьсагчуудыг цэнэглэн зарлах, энэ тохиолдолд w болон b \n sess.run(tf.global_variables_initializer())\n # моделийг сургах\n for i in range(100): # 100 epoch\n for x, y in data:\n # loss-ийг минимумчлах train_op\n sess.run(optimizer, feed_dict={X: x, Y: y})\n # w болон b утгууд нь одоо ямар болсныг авах\n w_value, b_value = sess.run([w, b])\n print(\"weight=\", w_value, \", bias=\", b_value)\n\n # регрессийн шулууныг w болон b утгуудыг ашиглан зурах\n plt.xlabel('Гал гаралтын тоо хэмжээ')\n plt.ylabel('Гэмт хэргийн гаралтын тоо')\n plt.scatter(data[:, 0], data[:, 1])\n plt.plot(x_plot, x_plot*w_value + b_value)\n plt.show()\n plt.pause(0.01)\n plt.gcf().clear()\n\n\n","sub_path":"regression/regression_from_url.py","file_name":"regression_from_url.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"230716002","text":"#캠핑\n\nN=0\nans = []\nwhile True:\n L, P, V = map(int,input().split())\n # 연속하는 P일중 L일만 사용가능\n\n if (L == 0 and P == 0 and V == 0) or (L>=P or P>=V or L>=V) :\n break\n N +=1\n ans.append((V // P) * L + min(V%P, L))\n # print(\"Case \"+ str(i) + \": \" + str(ans))\n # print(\"Case {}: {}\".format(i,ans))\n\n\nfor i in range(N):\n print(f'Case {i+1}: {ans[i]}')\n","sub_path":"greedy/4796.py","file_name":"4796.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"392900235","text":"from PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit,QInputDialog, QApplication\n\nclass ChooseNickname(QWidget):\n def __init__(self):\n super().__init__(self)\n self.initUI()\n\n def initUI(self):\n input_box = QLineEdit()\n\napp = QApplication([])\ndialog = QInputDialog()\ndialog.show()\napp.exec_()","sub_path":"ICubE-/gui2.py","file_name":"gui2.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"433722501","text":"#!/usr/bin/env python\n\"\"\"\n================================================================================\n:mod:`photon_range` -- Estimate of electron range\n================================================================================\n\n.. module:: photon_range\n :synopsis: Estimate of electron range\n\n.. inheritance-diagram:: pymontecarlo.util.photon_range\n\n\"\"\"\n\n# Script information for the file.\n__author__ = \"Philippe T. Pinard\"\n__email__ = \"philippe.pinard@gmail.com\"\n__version__ = \"0.1\"\n__copyright__ = \"Copyright (c) 2014 Philippe T. Pinard\"\n__license__ = \"GPL v3\"\n\n# Standard library modules.\n\n# Third party modules.\n\n# Local modules.\n\n# Globals and constants variables.\n\ndef photon_range(e0, material, transition):\n \"\"\"\n This function returns the generated photon range in *material* at\n incident electron energy *e0* for a characteristic x ray line *transition*.\n\n Reference:\n Hovington, P., Drouin, D., Gauvin, R. & Joy, D.C. (1997).\n Parameterization of the range of electrons at low energy using\n the CASINO Monte Carlo program. Microsc Microanal 3(suppl.2),\n 885–886.\n \n :arg e0: incident electron energy (in eV)\n :arg material: material\n :arg transition: x-ray line transition\n \n :return: photon range (in meters)\n \"\"\"\n if transition.z not in material.composition:\n raise ValueError('%s is not in material' % transition.symbol)\n if transition.energy_eV > e0:\n return 0.0\n\n z = transition.z\n ck = 43.04 + 1.5 * z + 5.4e-3 * z ** 2\n cn = 1.755 - 7.4e-3 * z + 3.0e-5 * z ** 2\n density = material.density_g_cm3\n\n e0 = e0 / 1e3\n ec = transition.energy_eV / 1e3\n\n return ck / density * (e0 ** cn - ec ** cn) * 1e-9\n","sub_path":"pymontecarlo/util/photon_range.py","file_name":"photon_range.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"625661917","text":"import sys\n#sys.stdin=open(\"input.txt\", \"rt\")\n\ns=input()\nn=0\n\nfor i in range(len(s)):\n if ord(s[i])>=48 and ord(s[i])<=57:\n n*=10\n n+=(ord(s[i])-48)\n\ncnt=0\nfor i in range(1,n+1):\n if n%i==0:\n cnt+=1\n\nprint(n)\nprint(cnt)","sub_path":"section3/2. 숫자만 추출.py","file_name":"2. 숫자만 추출.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302962549","text":"# Globals #\n\n\nimport sys\n\nsys.path.insert(0, \"modules\")\n\n# Project modules\nfrom model import Model\nimport preprocessing as pp\nimport analysis\nimport scraper\n\n# System modules\nimport os.path\nimport pandas as pd\n\ntry:\n if sys.argv[1] == \"-o\":\n OPTIMIZE = sys.argv[2] == \"True\"\n else:\n print(\"Invalid arguments.\")\n sys.exit()\nexcept IndexError:\n print(\"Missing arguments.\")\n sys.exit()\n\n\n# Data Bus #\n\n\nprint(\"Fetching data\")\n\nprice_data = scraper.fetch_data(os.path.dirname(os.getcwd()) + \"/data/price_data.csv\")\nblockchain_data = scraper.fetch_data(os.path.dirname(os.getcwd()) + \"/data/blockchain_data.csv\")\n#coindesk_headlines = pd.read_csv(os.path.dirname(os.getcwd()) + \"/data/test_scores.csv\", sep=\",\")\n\n# Preprocessing #\n\n\nprint(\"Preprocessing\")\n\ndata = (\n price_data.pipe(pp.calculate_indicators)\n .pipe(pp.merge_datasets, other_sets=[blockchain_data]) # [blockchain_data, coindesk_headlines]\n .pipe(pp.binarize_labels)\n .pipe(pp.fix_null_vals)\n .pipe(pp.add_lag_variables, lag=3)\n .pipe(pp.power_transform)\n )\nx_train, x_test, y_train, y_test = pp.split(data, test_size=.2, balanced=True)\n\n\n# Exploratory Analysis #\n\n\nprint(\"Analyzing features\")\n\n#print(data.describe())\nanalysis.plot_corr_matrix(data)\n\n\n# Fitting Models #\n\n\nprint(\"Fitting models\")\n\nlog_reg = Model(\n estimator=\"LogisticRegression\",\n train_set=(x_train, y_train),\n test_set=(x_test, y_test),\n select_features=\"RecursiveFE\",\n optimize=OPTIMIZE\n )\nrand_forest = Model(\n estimator=\"RandomForest\",\n train_set=(x_train, y_train),\n test_set=(x_test, y_test),\n select_features=\"RecursiveFE\",\n optimize=OPTIMIZE\n )\ngrad_boost = Model(\n estimator=\"GradientBoosting\",\n train_set=(x_train, y_train),\n test_set=(x_test, y_test),\n select_features=\"RecursiveFE\",\n optimize=OPTIMIZE\n )\n\n\n# Evaluation #\n\n\nprint(\"Evaluating\")\n\n# Logistic Regression\nprint(\"\\tLogistic Regression Estimator\")\nlog_reg.plot_cnf_matrix()\nlog_reg.cross_validate(method=\"Holdout\")\nlog_reg.cross_validate(\n method=\"RollingWindow\",\n data=data,\n window_size=.9,\n test_size=.1\n )\n\n# Random Forest\nprint(\"\\tRandom Forest Classifier\")\nrand_forest.plot_cnf_matrix()\nrand_forest.cross_validate(method=\"holdout\")\nrand_forest.cross_validate(\n method=\"RollingWindow\",\n data=data,\n window_size=.9,\n test_size=.1\n )\n\n# Gradient Boosting\nprint(\"\\tGradient Boosting Classifier\")\ngrad_boost.plot_cnf_matrix()\ngrad_boost.cross_validate(method=\"holdout\")\ngrad_boost.cross_validate(\n method=\"RollingWindow\",\n data=data,\n window_size=.9,\n test_size=.1\n )\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141940352","text":"import logging\n\nfrom flask import Flask, render_template\nfrom flask_restful import Api\nfrom flask_socketio import SocketIO\n\nfrom .api import *\nfrom ..modules.db import session_manager, unpack_declarative\nfrom ..modules.comm_interface import client_interface\nfrom ..modules.nodes import connected_nodes\nfrom ..models.db_dataschemes import *\nfrom ..models.observe import Observer\n\n# If the default logger are on, the logging library doesn't work properly\n# with the logging made by moody\n\nlogging.getLogger(\"werkzeug\").setLevel(logging.ERROR)\nlogging.getLogger(\"engineio\").setLevel(logging.ERROR)\nlogging.getLogger(\"socketio\").setLevel(logging.ERROR)\n\n\n# Observer/socketio/restful stuff\n#\n# Define the update behaviour for the default observers\n# so that it forwards the changes to the socketio interface\n\ninterface = Flask(__name__)\nsocketio = SocketIO(interface)\napi = Api(interface)\n\napi.add_resource(SituationListApi, \"/situation\")\napi.add_resource(SituationApi, \"/situation/\")\n\napi.add_resource(ActuatorGroupApi, \"/actuatorgroup\")\napi.add_resource(ActionListApi, \"/actuatorgroup/\")\napi.add_resource(ActionApi, \"/action/\")\n\napi.add_resource(SituationActionMappingsApi, \"/mappings\")\napi.add_resource(SituationActionMappingApi, \"/mapping\")\n\napi.add_resource(NeuralDatasetsApi, \"/neuraldatasets\")\napi.add_resource(NeuralDatasetApi, \"/neuraldataset/\")\napi.add_resource(NeuralCollectApi, \"/neuralcollect\")\napi.add_resource(NeuralPredictApi, \"/neuralpredict\")\n\n\ndef _update(**kwargs):\n global socketio\n # Check for the correctness of the Observer pattern usage\n if \"nodes\" not in kwargs:\n raise ValueError(\"Nodes should be passed through the notify_observer/update functions.\")\n socketio.emit(\"changed\", {'data': kwargs[\"nodes\"]._asdict()}, namespace=\"/listen\")\n\n\nconnected_nodes_observer = Observer()\nconnected_nodes_observer.update = _update\nconnected_nodes.add_observer(connected_nodes_observer)\n\n\n# Flask routing\n@interface.route(\"/\")\ndef adm():\n return render_template(\"admin.html\", title=\"Moody Administration Panel\")\n\n\n@interface.route(\"/discover\")\ndef discover():\n # Delete the nodes currently saved in the session\n connected_nodes.clear()\n client_interface().discover()\n return \"\", 200\n\n\n@interface.route(\"/settings\")\ndef settings():\n return render_template(\"settings.html\")\n\n\n@interface.route(\"/situations\")\ndef situations():\n with session_manager() as session:\n situation_data = session.query(Situation.situation_id, Situation.situation_name).all()\n situaction_data = session.query(SituationSetting, Situation.situation_name, Action.action_name)\\\n .join(Situation, SituationSetting.situation_id == Situation.situation_id)\\\n .join(Action, SituationSetting.action_id == Action.action_id).all()\n return render_template(\"situations.html\", situations=situation_data, situactions=situaction_data)\n\n\n@interface.route(\"/actions\")\ndef actions():\n with session_manager() as session:\n grps = session.query(NodeMeta).join(Node). \\\n filter(Node.node_metadata == NodeMeta.nodemeta_id). \\\n filter(Node.node_type == \"actuator\").all()\n group_data = unpack_declarative(grps)\n return render_template(\"actions.html\", groups=group_data)\n\n\n# TODO only show and work with datasets including the types connected at the moment\n@interface.route(\"/neuralinf\")\ndef neuralinf():\n with session_manager() as session:\n neuralmeta_data = session.query(NeuralMeta).all()\n return render_template(\"neuralinf.html\", datasets=neuralmeta_data)\n\n\n@interface.route(\"/linker/\")\ndef linker(linker_id):\n try:\n int(linker_id)\n except ValueError:\n return \"\", 404\n\n with session_manager() as session:\n situation_data = session.query(Situation.situation_id, Situation.situation_name).all()\n grp = session.query(NodeMeta).get(linker_id)\n res = session.query(Action.action_id, Action.action_name, Action.action_value) \\\n .join(NodeMeta).filter(Action.action_metadata == linker_id).all()\n return render_template(\"linker.html\", group=grp, actions=res, situations=situation_data)\n\n\n@interface.route(\"/nodes\", methods=[\"GET\"])\ndef get_connected():\n try:\n elements = [elem._asdict() for elem in connected_nodes.nodes]\n except KeyError:\n return \"[]\", 200\n else:\n return json.dumps(elements), 200\n","sub_path":"moodysg/interface/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618909259","text":"import argparse\n\ndef fasta_reader(filename):\n\n\tinfile = open(filename)\n\tseqs = {}\n\n\tfor line in infile:\n\t\tname = line.strip()[1:] # remove leading '>'\n\t\tseq = next(infile).strip()\n\t\tseqs[name] = seq\n\n\treturn seqs\n\ndef tab_reader(filename):\n\tinfile = open(filename)\n\tseqs = {}\n\n\tfor line in infile:\n\t\tname, seq = line.strip().split('\\t')\n\t\tseqs[name] = seq\n\t\tseqs[name] = seq\n\n\treturn seqs\n\ndef csv_reader(filename):\n\tinfile = open(filename)\n\tseqs = {}\n\n\tfor line in infile:\n\t\tname, seq = line.strip().split(',')\n\t\tseqs[name] = seq\n\n\treturn seqs\n\ndef fasta_writer(filename, seqs):\n\toutfile = open(filename, 'w')\n\t\n\tfor x in seqs:\n\t\toutfile.write('>'+x+'\\n'+seqs[x]+'\\n')\n\n\toutfile.close()\n\ndef tab_writer(filename, seqs):\n\toutfile = open(filename, 'w')\n\t\n\tfor x in seqs:\n\t\toutfile.write(x+'\\t'+seqs[x]+'\\n')\n\n\toutfile.close()\n\ndef csv_writer(filename, seqs):\n\toutfile = open(filename, 'w')\n\t\n\tfor x in seqs:\n\t\toutfile.write(x+','+seqs[x]+'\\n')\n\n\toutfile.close()\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Switch between either csv,tab or fasta formats')\n\tparser.add_argument('filename', help='Name of input file')\n\tparser.add_argument('input_type', help='Type of input file')\n\tparser.add_argument('output_type', help='Type of output file')\n\tparser.add_argument('output_name', help='Name of output file')\n\n\targs = parser.parse_args()\n\n\tinput_filename = args.filename\n\toutput_type = args.output_type\n\tinput_type = args.input_type\n\toutput_name = args.output_name\n\n\tif input_type == 'fasta':\n\t\tseqs = fasta_reader(input_filename)\n\telif input_type == 'csv':\n\t\tseqs = csv_reader(input_filename)\n\telif input_type == 'tab':\n\t\tseqs = tab_reader(input_filename)\n\telse:\n\t\traise ValueError('Input type must be csv, tab or fasta')\n\n\tif output_type == 'fasta':\n\t\tfasta_writer(output_name, seqs)\n\telif output_type == 'csv':\n\t\tcsv_writer(output_name, seqs)\n\telif output_type == 'tab':\n\t\ttab_writer(output_name, seqs)\n\telse:\n\t\traise ValueError('Output type must be csv, tab or fasta')\n\n","sub_path":"format_converter.py","file_name":"format_converter.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"218544491","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 22 17:19:30 2019\r\nThis workshop largely focuses on classification techniques that are used in sentiment analysis. \r\nRemember sentiment analysis consists of 3 main steps.\r\n The first is the sourcing and collection of textual data. \r\n The second step is the training and classification of the textual data to obtain the sentiment scores. \r\n The 3rd step which will be covered on Day 4 is the visualisation and communication of the sentiment scores.\r\n@author: isswan\r\n\"\"\"\r\n###############################\r\n#Data Prepration \r\n# Set your working directory\r\nfrom os import getcwd, chdir\r\nimport pandas as pd\r\nimport pickle as pk\r\nfpath = getcwd()\r\nprint (fpath)\r\n# Change your path here\r\nchdir(fpath) \r\n\r\n\r\n#######################################################################\r\n#reading in another set of data\r\nposlines = open(fpath+\"\\\\Data\\\\rt-polarity-utf8.pos\",'r').read().splitlines()\r\nneglines = open(fpath+\"\\\\Data\\\\rt-polarity-utf8.neg\",'r').read().splitlines()\r\n\r\nprint (\"No of positive reviews \" + str(len(poslines)))\r\nprint (\"No of negative reviews \" + str(len(neglines)))\r\n\r\n\r\n# There is a total of 5331 positives and negatives\r\n# Lets take the first N as training set, and leave the rest for validation\r\nN=4800\r\nposlinesTrain = poslines[:N]\r\nneglinesTrain = neglines[:N]\r\nposlinesTest = poslines[N:]\r\nneglinesTest = neglines[N:]\r\n\r\n# Create the train set and the test set by attaching labels to text to form a \r\n# list of tupes (sentence, label). Labels are 1 for positive, -1 for negatives\r\ntrainset = [(x,1) for x in poslinesTrain] + [(x,-1) for x in neglinesTrain]\r\ntestset = [(x,1) for x in poslinesTest] + [(x,-1) for x in neglinesTest]\r\n#######################################################################\r\n#build a Lexicon Classifier (I)\r\n# We use it for a Lexicon classifier which is essentially count good and bad words from the reviews. \r\n# The model learns the all the frequencies of a paticular word appearing in Pos/Neg group\r\n\r\nposwords = {} # this dictionary will store counts for every word in positives\r\nnegwords = {} # and negatives\r\nfor line, label in trainset: # for every sentence and its label\r\n\tfor word in line.split(): # for every word in the sentence\r\n\t\t# increment the counts for this word based on the label\r\n #Finaly we have the dictionrary:\r\n # for each word, how many times does it appear in Pos/Neg group \r\n\t\tif label == 1: poswords[word] = poswords.get(word,0) + 1\r\n\t\telse: negwords[word] = negwords.get(word, 0) + 1\r\n \r\nprint (\"No of negative words in trainset \" + str(len(negwords)))\r\nprint (\"No of positive words in trainset \" + str(len(poswords)))\r\n\r\nposFreqs = {k: poswords[k] for k in list(poswords)[:5]}\r\nprint (posFreqs)\r\nnegFreqs = {k: negwords[k] for k in list(negwords)[:5]}\r\nprint (negFreqs)\r\n\r\n#######################################################################\r\n#The classifier will make judgement based on the posFreq(w)/(posFreq(w)+negFreq(w))\r\n#Apply the classifier on top of testing dataset\r\n\r\nwrong = 0 # will store the number of misclassifications\r\npred_list = []\r\nactual = []\r\nfor line, label in testset:\r\n\ttotpos, totneg = 0.0,0.0\r\n\tfor word in line.split():\r\n\t\t# Get the (+1 smooth'd) number of counts this word occurs in each class\r\n\t\t#smoothing is done in case this word isn't in train set, so that there\r\n\t\t# is no danger in dividing by 0 later when we do a/(a+b)\r\n\t\ta = poswords.get(word, 0.0) + 1.0\r\n\t\tb = negwords.get(word, 0.0) + 1.0\r\n\t\t#increment our score counter for each class, based on this word\r\n\t\ttotpos+=a/(a+b)\r\n\t\ttotneg+=b/(a+b)\r\n\t#create prediction based on counter values\r\n\tprediction=1\r\n\tif totneg>totpos: prediction = -1\r\n\tpred_list.append(prediction)\r\n\tactual.append(label)\r\n\tif prediction!=label:\r\n\t\twrong+=1\r\n\t\tprint ('ERROR: %s posscore = %.2f negscore=%.2f' % (line, totpos, totneg))\r\n\telse:\r\n\t\tpass\r\n #print 'CORRECT: %s posscore=%.2f negscore=%.2f' % (line, totpos, totneg)\r\n \r\nprint ('error rate is %f' % (1.0*wrong/len(testset),))\r\nprint ('No of wrongs ' + str(wrong))\r\nprint ('Size of test set ' + str(len(testset)))\r\n\r\n\"\"\"\r\nerror rate is 0.209981\r\nNo of wrongs 223\r\nSize of test set 1062\r\n\r\nNote down the error rate. The 'correct' rate is already quite high for a simple lexicon classifier. \r\nRead through some of the wrongly classified ones and can you understand why they are wrongly classified?\r\n What do you think a high score should be? \r\nERROR: it's a big idea , but the film itself is small and shriveled . posscore = 7.01 negscore=6.99\r\nERROR: the story alone could force you to scratch a hole in your head . posscore = 7.34 negscore=6.66\r\n\"\"\"\r\n######################################################################\r\n#NLTK Classifier\r\n#In this section, we do the same for a lexicon classifier. \r\n#This time round, we use as the training set a labelled corpus \"Sentiwordnet.txt\" from NLTK. \r\n#The NLTK is a popular open-source text mining tool in Python. \r\n#Other popular tools include the Stanford NLP and OpenNLP.\r\nimport nltk\r\n#nltk.downoad('wordnet')\r\n#nltk.downoad('sentiwordnet')\r\n#nltk.downoad('punkt')\r\n\r\nfrom nltk.corpus import sentiwordnet as swn\r\nfrom scipy import mean\r\nfrom nltk.tokenize import word_tokenize as wt\r\n\r\n\r\nsynsets = swn.senti_synsets('fast')\r\n \r\nfor syn in swn.senti_synsets('fast'):\r\n print (str(syn))\r\n\r\n##Caculate the overall polarity of given word \r\n ## mean of Pos/Neg score by averaging the polarity of all the synonyms \r\n ## max by selecting the max\r\ndef get_pos_neg_score(word, metric):\r\n posi=[0.0]\r\n negi=[0.0]\r\n synsets = swn.senti_synsets(word)\r\n for syn in synsets:\r\n posi.append(syn.pos_score())\r\n negi.append(syn.neg_score())\r\n if metric == \"Mean\":\r\n pos = mean(posi)\r\n neg = mean(negi)\r\n else:\r\n pos = max(posi)\r\n neg = max(negi)\r\n return pos, neg\r\n\r\nget_pos_neg_score('fast','Mean')\r\n\r\n##############################################################################################\r\n#using NLTK instead of training corpus to build the classifier posScore(sent) ? negScore(sent)\r\n\r\npred = []\r\nactual = []\r\nfor line, label in testset:\r\n pos_rev = neg_rev = 0 \r\n for word in wt(line):\r\n pos, neg = get_pos_neg_score(word, \"Mean\")\r\n pos_rev+=pos\r\n neg_rev+=neg\r\n if pos_rev>neg_rev:\r\n lab=1\r\n else:\r\n lab=-1\r\n pred.append(lab)\r\n actual.append(label)\r\n \r\nactuals = pd.Series(actual)\r\npredicted = pd.Series(pred)\r\nprint (actuals)\r\nprint (predicted)\r\n\r\n# Confusion Matrix\r\ncm1=pd.crosstab(actuals, predicted, rownames=['Actuals'], colnames=['Predicted'], margins=True)\r\ncm1\r\n\r\n#precision score and recall scores\r\nfrom sklearn.metrics import precision_score, recall_score\r\n\r\n#Accuracy is lower than the first lexicon classifier 79% Why?\r\nmat1 = cm1.to_numpy()\r\naccuracy = float(mat1[0,0]+mat1[1,1])/mat1[2,2]\r\nprint('Accuracy: {0:0.3f}'.format(accuracy))\r\n\r\nprecision = precision_score(actuals, predicted)\r\nprint('Precision score: {0:0.3f}'.format(precision))\r\nrecall = recall_score(actuals, predicted)\r\nprint('Recall score: {0:0.3f}'.format(recall))\r\n\r\n#This workshop is based on some simple Lexicon classifiers. \r\n#Can you explain the pros and cons of this simple method now?\r\n\r\n\r\n","sub_path":"Lectures/Day 2/workshop/selected-downloads (26)/LexiconBasedClassifiers.py","file_name":"LexiconBasedClassifiers.py","file_ext":"py","file_size_in_byte":7240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"638400479","text":"#! python3\n# openURLs.py - opens several preset URLs by examining a text file of URLs\n# Usage - openURLs.py [presetName]\n # -l, --list\n # -h, --help \n # --setdefault [presetName]\n\n\n\n# Functions\n # open a list of presets based on group/\"playlist\" name\n # opens a text file in the default directory for presets \n # save a preset of URL links, with a name\n # option to assign a preset as the default\n # make it print the list and ask which one to save \n # list all preset names and their links\n\nimport webbrowser, sys, os, shelve\n\n# make a directory where the script is located to hold preset text files \nos.makedirs(os.path.join(sys.path[0], \"URL Presets\"), exist_ok=True)\nos.chdir(os.path.join(sys.path[0], \"URL Presets\"))\n\nflags = [\"-l\", \"--list\", \"--setdefault\", \"-h\", \"--help\"]\nallPresets = []\n\ndef openPresets(preset):\n if not os.path.isfile(preset + \".txt\"):\n print(\"Preset not found. Use --setdefault to reconfigure.\")\n os.system(\"pause\") \n sys.exit(1)\n listOfURLs = open(preset + \".txt\")\n for URL in listOfURLs.readlines():\n try: \n webbrowser.open(URL)\n except Exception as exc:\n print(\"Failed to open \" + URL + \"\\nError: \" + str(exc)) \n\ndef listPresets():\n if len(allPresets) == 0:\n print(\"No presets found in \" + os.getcwd())\n os.system(\"pause\")\n sys.exit(1)\n print(\"List of Available Presets:\")\n for i in range(len(allPresets)):\n print(str(i + 1) + \". \" + allPresets[i])\n\ndef askToSelectPreset():\n while(True):\n print(\"\\nSelect a preset or type 'q' to quit: \", end = \"\")\n choice = input()\n if choice == 'q':\n sys.exit() \n if choice.isdigit():\n choice = int(choice) - 1\n if choice < 0 or choice >= len(allPresets):\n print(\"Please type a valid preset name or number.\")\n continue\n return allPresets[choice]\n else:\n if choice not in allPresets:\n print(\"Please type a valid preset name or number.\")\n continue\n else:\n return choice\n\ndef setDefaultPreset():\n listPresets()\n default = askToSelectPreset()\n shelf = shelve.open(\"default_preset\")\n shelf['default'] = default\n print(\"Set \" + default + \" as the default preset.\\n\")\n shelf.close()\n os.system(\"pause\")\n sys.exit()\n \n\ndef scanForPresets():\n for file in os.listdir(\".\"):\n if file.endswith(\".txt\"):\n preset = file.rstrip(\".txt\")\n allPresets.append(preset)\n\n \ndef printUsage():\n print(\"\"\"Usage - openURLs.py [presetName]\nOpens multiple URLs by reading a text file.\nText files consist of URLs separated by a new line and are\nfound in the 'URL Presets' directory. \n\n--setdefault (presetName)\n-l, --list\n-h, --help\n\"\"\")\n\n# Find all presets \nscanForPresets()\n\n# load default preset, if available \nif len(sys.argv) == 1:\n if os.path.isfile(\"default_preset.bak\") and os.path.isfile(\"default_preset.dat\") and os.path.isfile(\"default_preset.dir\"):\n shelf = shelve.open(\"default_preset\")\n preset = shelf[\"default\"]\n openPresets(preset)\n shelf.close()\n else:\n printUsage()\n print(\"\\nNo default preset currently found. Add default preset? (Y/N) \", end =\"\")\n if input().lower() == 'y':\n setDefaultPreset()\n \n sys.exit()\n\n#--help or invalid response \nif sys.argv[1] not in (flags + allPresets) or sys.argv[1] == \"-h\" or sys.argv[1] == \"--help\":\n printUsage()\n os.system(\"pause\")\n sys.exit(1)\n\nif sys.argv[1] in allPresets:\n openPresets(sys.argv[1])\n\n# Set the default preset\nif sys.argv[1] == '--setdefault':\n setDefaultPreset()\n \n \n# List all presets and prompt which one to open \nif sys.argv[1] == \"-l\" or sys.argv[1] == \"--list\":\n listPresets()\n preset = askToSelectPreset()\n openPresets(preset)\n","sub_path":"URL Presets/openURLs.py","file_name":"openURLs.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84489430","text":"# http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab5.html\r\n\r\n# Упражнение №2. Задачи посложнее\r\n# =================================\r\n\r\n# Переставьте соседние элементы в списке. Задача решается в три строки.\r\ns = \"1 2\"\r\ns = \"1\"\r\ns = \"1 2 3 4 5 6 7\"\r\ns = \"\"\r\ns = \"1 2 3 4 5 6\"\r\nL = s.split()\r\n\r\nlast = len(L) - 1 if len(L) % 2 else len(L)\r\nL[:last:2], L[1:last:2] = L[1:last:2], L[:last:2]\r\nprint(*L)\r\n\r\n\r\n# Выполните циклический сдвиг элементов списка вправо.\r\ns = \"1 2 3 4 5\"\r\nL = s.split()\r\nprint(*(L[-1:] + L[:-1]))\r\n\r\n# Выведите элементы, которые встречаются в списке только один раз.\r\n# Элементы нужно выводить в том порядке, в котором они встречаются в списке.\r\ns = \"1 2 2 3 3 3 5 6 6\"\r\nL = s.split()\r\nprint(*[el for el in L if L.count(el) == 1])\r\n\r\n# Определите, какое число в этом списке встречается чаще всего. Если таких\r\n# чисел несколько, выведите любое из них.\r\ns = \"1 2 2 3 3 4 4 5 6 6 3 4\"\r\nL = s.split()\r\nprint(max([L.count(el) for el in L]))\r\n","sub_path":"4_arithmetics_and_lists/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80492867","text":"## This file is part of Invenio.\n## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.\n##\n## Invenio is free software; you can redistribute it and/or\n## modify it under the terms of the GNU General Public License as\n## published by the Free Software Foundation; either version 2 of the\n## License, or (at your option) any later version.\n##\n## Invenio is distributed in the hope that it will be useful, but\n## WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY 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 Invenio; if not, write to the Free Software Foundation, Inc.,\n## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n\n__revision__ = \"$Id$\"\n\n ## Description: function Send_APP_Mail\n ## This function send an email informing the original\n ## submitter of a document that the referee has approved/\n ## rejected the document. The email is also sent to the\n ## referee for checking.\n ## Author: T.Baron\n ## PARAMETERS:\n ## newrnin: name of the file containing the 2nd reference\n ## addressesAPP: email addresses to which the email will\n ## be sent (additionally to the author)\n ## categformatAPP: variable needed to derive the addresses\n ## mentioned above\n\nimport os\nimport re\n\nfrom invenio.config import CFG_SITE_NAME, \\\n CFG_SITE_URL, \\\n CFG_SITE_SUPPORT_EMAIL, \\\n CFG_CERN_SITE, \\\n CFG_SITE_RECORD\nfrom invenio.access_control_admin import acc_get_role_users, acc_get_role_id\nfrom invenio.dbquery import run_sql\nfrom invenio.websubmit_config import CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN\nfrom invenio.mailutils import send_email\nfrom invenio.errorlib import register_exception\nfrom invenio.search_engine import print_record\nfrom invenio.websubmit_functions.JOBSUBMIT_Mail_Submitter import CFG_WEBSUBMIT_JOBS_SUPPORT_EMAIL, \\\n CFG_WEBSUBMIT_JOBS_FROMADDR, \\\n email_footer\n\nCFG_WEBSUBMIT_RECORD_OWNER_EMAIL = \"270__m\"\n\ndef JOBSUBMIT_Send_APP_Mail(parameters, curdir, form, user_info=None):\n \"\"\"\n This function send an email informing the original submitter of a\n document that the referee has approved/ rejected the document.\n\n Parameters:\n\n * addressesAPP: email addresses of the people who will receive\n this email (comma separated list). this parameter may contain\n the string. In which case the variable computed from\n the [categformatAFP] parameter replaces this string.\n eg.: \"-email@cern.ch\"\n\n * categformatAPP contains a regular expression used to compute\n the category of the document given the reference of the\n document.\n eg.: if [categformatAFP]=\"TEST--.*\" and the reference\n of the document is \"TEST-CATEGORY1-2001-001\", then the computed\n category equals \"CATEGORY1\"\n\n * emailFile: Name of the file containing the email of the\n submitter of the document\n\n * newrnin: Name of the file containing the 2nd reference of the\n document (if any).\n\n * decision_file: Name of the file containing the decision of the\n document.\n\n * comments_file: Name of the file containing the comments of the\n document.\n\n * edsrn: Name of the file containing the reference of the\n document.\n \"\"\"\n global titlevalue,authorvalue,sysno,rn\n doctype = form['doctype']\n titlevalue = titlevalue.replace(\"\\n\",\" \")\n authorvalue = authorvalue.replace(\"\\n\",\"; \")\n # variables declaration\n categformat = parameters['categformatAPP']\n otheraddresses = parameters['addressesAPP']\n newrnpath = parameters['newrnin']\n ## Get the name of the decision file:\n try:\n decision_filename = parameters['decision_file']\n except KeyError:\n decision_filename = \"\"\n ## Get the name of the comments file:\n try:\n comments_filename = parameters['comments_file']\n except KeyError:\n comments_filename = \"\"\n\n ## Now try to read the comments from the comments_filename:\n if comments_filename in (None, \"\", \"NULL\"):\n ## We don't have a name for the comments file.\n ## For backward compatibility reasons, try to read the comments from\n ## a file called 'COM' in curdir:\n if os.path.exists(\"%s/COM\" % curdir):\n try:\n fh_comments = open(\"%s/COM\" % curdir)\n comment = fh_comments.read()\n fh_comments.close()\n except IOError:\n ## Unable to open the comments file\n exception_prefix = \"Error in WebSubmit function \" \\\n \"Send_APP_Mail. Tried to open \" \\\n \"comments file [%s/COM] but was \" \\\n \"unable to.\" % curdir\n register_exception(prefix=exception_prefix)\n comment = \"\"\n else:\n comment = comment.strip()\n else:\n comment = \"\"\n else:\n ## Try to read the comments from the comments file:\n if os.path.exists(\"%s/%s\" % (curdir, comments_filename)):\n try:\n fh_comments = open(\"%s/%s\" % (curdir, comments_filename))\n comment = fh_comments.read()\n fh_comments.close()\n except IOError:\n ## Oops, unable to open the comments file.\n comment = \"\"\n exception_prefix = \"Error in WebSubmit function \" \\\n \"Send_APP_Mail. Tried to open comments \" \\\n \"file [%s/%s] but was unable to.\" \\\n % (curdir, comments_filename)\n register_exception(prefix=exception_prefix)\n else:\n comment = comment.strip()\n else:\n comment = \"\"\n\n ## Now try to read the decision from the decision_filename:\n if decision_filename in (None, \"\", \"NULL\"):\n ## We don't have a name for the decision file.\n ## For backward compatibility reasons, try to read the decision from\n ## a file called 'decision' in curdir:\n if os.path.exists(\"%s/decision\" % curdir):\n try:\n fh_decision = open(\"%s/decision\" % curdir)\n decision = fh_decision.read()\n fh_decision.close()\n except IOError:\n ## Unable to open the decision file\n exception_prefix = \"Error in WebSubmit function \" \\\n \"Send_APP_Mail. Tried to open \" \\\n \"decision file [%s/decision] but was \" \\\n \"unable to.\" % curdir\n register_exception(prefix=exception_prefix)\n decision = \"\"\n else:\n decision = decision.strip()\n else:\n decision = \"\"\n else:\n ## Try to read the decision from the decision file:\n try:\n fh_decision = open(\"%s/%s\" % (curdir, decision_filename))\n decision = fh_decision.read()\n fh_decision.close()\n except IOError:\n ## Oops, unable to open the decision file.\n decision = \"\"\n exception_prefix = \"Error in WebSubmit function \" \\\n \"Send_APP_Mail. Tried to open decision \" \\\n \"file [%s/%s] but was unable to.\" \\\n % (curdir, decision_filename)\n register_exception(prefix=exception_prefix)\n else:\n decision = decision.strip()\n\n if os.path.exists(\"%s/%s\" % (curdir,newrnpath)):\n fp = open(\"%s/%s\" % (curdir,newrnpath))\n newrn = fp.read()\n fp.close()\n else:\n newrn = \"\"\n # Document name\n res = run_sql(\"SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s\", (doctype,))\n docname = res[0][0]\n # retrieve category\n categformat = categformat.replace(\"\", \"([^-]*)\")\n m_categ_search = re.match(categformat, rn)\n if m_categ_search is not None:\n if len(m_categ_search.groups()) > 0:\n ## Found a match for the category of this document. Get it:\n category = m_categ_search.group(1)\n else:\n ## This document has no category.\n category = \"unknown\"\n else:\n category = \"unknown\"\n\n # Creation of the mail for the referee\n otheraddresses = otheraddresses.replace(\"\",category)\n addresses = \"\"\n if otheraddresses != \"\":\n addresses += otheraddresses\n else:\n addresses = re.sub(\",$\",\"\",addresses)\n\n ## Add the record's submitter(s) into the list of recipients:\n # The submitters email address is read from the file specified by 'emailFile'\n try:\n fp = open(\"%s/%s\" % (curdir,parameters['emailFile']))\n addresses += fp.read().replace (\"\\n\",\" \")\n fp.close()\n except:\n pass\n\n if decision == \"approve\":\n mailtitle = \"%s has been approved\" % rn\n mailbody = \"The submitted job listing with reference number %s has been fully approved.\" % (rn,)\n mailbody += \"\\n\\nIt will soon become visible in the INSPIRE-HEP Jobs database - <%s/Jobs>\" % (CFG_SITE_URL,)\n else:\n mailtitle = \"%s has been rejected\" % rn\n mailbody = \"The %s %s has been rejected.\" % (docname,rn)\n if rn != newrn and decision == \"approve\" and newrn != \"\":\n mailbody += \"\\n\\nIts new reference number is: %s\" % newrn\n mailbody += \"\\n\\nTitle: %s\\n\\nAuthor(s): %s\\n\\n\" % (titlevalue,authorvalue)\n if comment != \"\":\n mailbody += \"Comments from the referee:\\n%s\\n\" % comment\n # Send mail to referee\n send_email(fromaddr=CFG_WEBSUBMIT_JOBS_FROMADDR, toaddr=addresses, subject=mailtitle, \\\n content=mailbody, footer=email_footer(support_email=CFG_WEBSUBMIT_JOBS_SUPPORT_EMAIL), copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)\n return \"\"\n","sub_path":"websubmit/JOBSUBMIT_Send_APP_Mail.py","file_name":"JOBSUBMIT_Send_APP_Mail.py","file_ext":"py","file_size_in_byte":10305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"307481470","text":"from api.exceptions import OmdbApiResponseException\nfrom api.externalapihandler.external_api_handler import ExternalApiHandler\n\n\nclass OmdbApiHandler(ExternalApiHandler):\n\n def __init__(self, api_key):\n self.base_url = 'http://www.omdbapi.com/'\n self.poster_url = 'http://img.omdbapi.com/'\n super().__init__(api_key)\n\n def get_movie(self, title):\n parameters = {'apikey': self.api_key, 't': title}\n result = self._get(self.base_url, parameters)\n if result.get('Error'):\n raise OmdbApiResponseException(\n 'Error encountered when getting movie from OMDb: {}'.format(result.get('Error')))\n return result\n","sub_path":"api/externalapihandler/omdb_api_handler.py","file_name":"omdb_api_handler.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384307558","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 12 09:09:07 2020\n\n@author: marie\n\"\"\"\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nimport setup.preprocessing as preprocessing\n\nimport time\nimport pandas as pd\nimport os.path\n\nfrom ast import literal_eval\n\n\n\n#%%\ndef set_model_parameters(model, typ, epochs, change_architecture, adaptive_pooling,\n X, Y, featuresize = None, data_dir = r\"/home/fr/fr_fr/fr_mw263\"):\n \n if (typ == 4):\n results = pd.read_csv(os.path.join(data_dir, f\"output/grid_search/grid_search_results_{model}4.csv\"))\n elif (typ == 2):\n if adaptive_pooling:\n results = pd.read_csv(os.path.join(data_dir, f\"output/grid_search/adaptive_pooling/grid_search_results_{model}2.csv\"))\n featuresize = results[\"featuresize\"]\n else:\n results = pd.read_csv(os.path.join(data_dir, f\"output/grid_search/grid_search_results_{model}2.csv\"))\n else:\n results = pd.read_csv(os.path.join(data_dir, f\"output/grid_search/grid_search_results_{model}2.csv\"))\n \n best_model = results.iloc[results['mae_val'].idxmin()].to_dict()\n \n if change_architecture == True:\n best_model[\"activation\"] == nn.Sigmoid\n \n hidden_dims = literal_eval(best_model[\"hiddensize\"])\n \n if featuresize is None:\n dimensions = [X.shape[1]]\n else:\n dimensions = []\n for hdim in hidden_dims:\n dimensions.append(hdim)\n dimensions.append(Y.shape[1])\n \n hparams = {\"batchsize\": int(best_model[\"batchsize\"]), \n \"epochs\":epochs, \n \"history\": int(best_model[\"history\"]), \n \"hiddensize\":hidden_dims,\n \"learningrate\":best_model[\"learningrate\"]}\n \n model_design = {\"dimensions\": dimensions,\n \"activation\": eval(best_model[\"activation\"][8:-2]),\n \"featuresize\":featuresize}\n \n return hparams, model_design\n\n \n#%% Train the model with hyperparameters selected after random grid search:\n \ndef train_network(model,typ, site, epochs, q, adaptive_pooling, dropout_prob = 0.0, change_architecture = False, \n traindata_perc = None, featuresize = None, \n save = True, data_dir = r\"/home/fr/fr_fr/fr_mw263\"):\n \n \"\"\"\n Takes the best found model parameters and trains a MLP with it.\n \n Args:\n X, Y (numpy array): Feature and Target data. \\n\n model_params (dict): dictionary containing all required model parameters. \\n\n epochs (int): epochs to train the model. \\n\n splits (int): How many splits will be used in the CV. \\n\n eval_set (numpy array): if provided, used for model evaluation. Default to None.\n \n Returns:\n running_losses: epoch-wise training and validation errors (rmse and mae) per split.\\n\n y_tests: Target test set on which the model was evaluated on per split.\\n\n y_preds: Network predictions per split.\\n\n performance (pd.DataFrame): Data frame of model parameters and final training and validation errors.\\n\n \"\"\"\n X, Y = preprocessing.get_splits(sites = [site],\n years = [2001,2002,2003,2004,2005,2006, 2007],\n datadir = os.path.join(data_dir, \"scripts/data\"), \n dataset = \"profound\",\n simulations = None)\n\n X_test, Y_test = preprocessing.get_splits(sites = [site],\n years = [2008],\n datadir = os.path.join(data_dir, \"scripts/data\"), \n dataset = \"profound\",\n simulations = None)\n \n eval_set = {\"X_test\":X_test, \"Y_test\":Y_test}\n \n hparams, model_design = set_model_parameters(model, typ, epochs, change_architecture, adaptive_pooling, X, Y)\n \n start = time.time()\n \n data_dir = os.path.join(data_dir, f\"output/models/{model}{typ}\")\n \n if adaptive_pooling:\n data_dir = os.path.join(data_dir, r\"adaptive_pooling\")\n\n if dropout_prob == 0.0:\n data_dir = os.path.join(data_dir, r\"nodropout\")\n else:\n data_dir = os.path.join(data_dir, r\"dropout\")\n \n if not traindata_perc is None:\n data_dir = os.path.join(data_dir, f\"data{traindata_perc}perc\")\n \n if change_architecture:\n data_dir = os.path.join(data_dir, f\"sigmoidActivation\")\n \n dev = __import__(f\"setup.dev_{model}\", fromlist=[\"selected\"])\n \n running_losses,performance, y_tests, y_preds = dev.train_model_CV(hparams, model_design, \n X, Y, \n eval_set, dropout_prob,\n data_dir, save)\n end = time.time()\n \n # performance returns: rmse_train, rmse_test, mae_train, mae_test in this order.\n performance = np.mean(np.array(performance), axis=0)\n rets = [(end-start), \n hparams[\"hiddensize\"], hparams[\"batchsize\"], hparams[\"learningrate\"], hparams[\"history\"], model_design[\"activation\"], \n performance[0], performance[1], performance[2], performance[3]]\n results = pd.DataFrame([rets], \n columns=[\"execution_time\", \"hiddensize\", \"batchsize\", \"learningrate\", \"history\", \"activation\", \"rmse_train\", \"rmse_val\", \"mae_train\", \"mae_val\"])\n results.to_csv(os.path.join(data_dir, r\"selected_results.csv\"), index = False)\n \n # Save: Running losses, ytests and ypreds.\n np.save(os.path.join(data_dir, \"running_losses.npy\"), running_losses)\n np.save(os.path.join(data_dir, \"y_tests.npy\"), y_tests)\n np.save(os.path.join(data_dir, \"y_preds.npy\"), y_preds)\n \n #return(running_losses, y_tests, y_preds)\n ","sub_path":"python/setup/wrapper_training.py","file_name":"wrapper_training.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425927349","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager\nfrom django.conf import settings\nfrom django.core.signing import Signer\nfrom django.template import engines, Context\nfrom django.urls import reverse\nfrom django.db.models import Count\n\nsigner = Signer()\ndt_engine = engines['django'].engine\n\n# Данная sмодель заменит модель пользователя User, используемую по умолчанию.\n# Данная замена должна быть отражена в настройках проекта: AUTH_USER_MODEL = 'user.models.AdvUser'.\n# Замен производится с целью расширения стандартной модели с помощью дополнительных методов и атрибутов.\n'''\nclass AdvUserManager(AbstractUserManager):\n #pass\n\n def normalize_email(self, email):\n if email.strip() == '':\n return None\n return email.lower()\n'''\nclass AdvUser(AbstractUser):\n #objects = AdvUserManager()\n\n class Meta(AbstractUser.Meta):\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи (расширенная модель)'\n ordering = ['-date_joined']\n unique_together = ['email']\n\n def __str__(self):\n return self.username\n\n def confirm(self):\n self.is_active = True\n self.save()\n\n def get_email_context(self):\n host = settings.HOST_NAME\n sign = signer.sign(self.username)\n link = host + reverse('user:registration_confirmed', kwargs={'sign': sign})\n return Context({'confirmation_link': link})\n\n def send_confirmation_email(self):\n context = self.get_email_context()\n text_body = dt_engine.get_template('emails/registration_confirmation.txt').render(context=context)\n html_body = dt_engine.get_template('emails/registration_confirmation.html').render(context=context)\n self.email_user(subject='Mailer: Подтверждение регистрации', message=text_body, html_message=html_body)\n","sub_path":"django/user/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291739368","text":"import unittest\r\nfrom main import upload_file\r\ntoken = input(\"Введите токен\")\r\nclass TestFails(unittest.TestCase):\r\n def test_wrong_upload_file(self):\r\n import requests\r\n upload_file(\"Fight\", token)\r\n response = requests.get(\"https://cloud-api.yandex.net/v1/disk/resources/files\", params={\"limit\": 1000},\r\n headers={\"Authorization\": token})\r\n status_code = response.status_code\r\n self.assertNotEqual(status_code, 200)\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n\r\n\r\n","sub_path":"TestFails.py","file_name":"TestFails.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353694067","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 14 16:42:06 2018\n\n@author: AshwinAmbal\n\nDescription: The code below is used to extract required data from the file \ndevset_textTermsPerPOI.txt and write the required information in a database type\nformat into a csv file. The column header in the written file would signify the\nuser id's of the various users and the row headers would be annotations.\nEg:\n [Annotations LocID1 LocID2 LocID3]\n [\"wicked\" ID1 ID2 ID3]\n [...... .... .... ...]\n\"\"\"\n\nimport csv\n\n# Opening file to read from\nfile1 = open(\"C:\\\\MWDB Project\\\\devset\\\\desctxt\\\\devset_textTermsPerPOI.txt\",\"r\", encoding=\"utf8\")\nlist_of_lines = file1.readlines()\nids = list()\n\n#Reading all image id's into 'ids'\nfor row in list_of_lines:\n loc_id = \"\"\n words = row.split()\n for word in words:\n if '\"' not in word:\n loc_id += word + \" \"\n else:\n loc_id = \"_\".join(loc_id.split())\n break\n ids.append(loc_id)\n\n# Converting existing file to one in which the first set of words before the \n# annotations are replaced with _ between those words for uniform access \n# devset_textTermsPerPOIEdited.csv ===> devset_textTermsPerPOI.csv\nnew_lines = list()\nfor i, row in enumerate(list_of_lines):\n w = 0\n words = row.split()\n new_line = list()\n for word in words:\n if '\"' in word:\n break\n w += 1\n new_line.append(ids[i])\n for j in range(w, len(words)):\n new_line.append(words[j])\n new_lines.append(new_line)\n\n\nwith open(\"C:\\\\MWDB Project\\\\Code\\\\CSV\\\\Task_3\\\\devset_textTermsPerPOIEdited.csv\", 'w', encoding = 'utf8', newline='') as outcsv: \n #configure writer to write standard csv file\n writer = csv.writer(outcsv, delimiter = ',', quotechar = \"'\")\n for item in new_lines:\n #Write item to outcsv\n writer.writerow(item)\n\nlist_of_lines = list()\ncsvfile = open(\"C:\\\\MWDB Project\\\\Code\\\\CSV\\\\Task_3\\\\devset_textTermsPerPOIEdited.csv\",\"r\", encoding=\"utf8\")\nreader = csv.reader(csvfile, delimiter=',', quotechar = \"'\") \nfor row in reader:\n list_of_lines.append(row)\n\n# Reading all annotations into 'annotation'\nannotation = list()\nfor line in list_of_lines:\n for i in range(1, len(line), 4):\n line[i] = line[i].replace(\"\\'\", \" \")\n line[i] = line[i].replace('\"', '')\n annotation.append(line[i])\n\nannotation = list(set(annotation))\n\n# Making a dictionary of annotation mapping to the index in which it occurs in the\n# list 'annotation'\ndict_annot = dict()\nfor i, annot in enumerate(annotation):\n dict_annot[annot] = i\n\n# Reading line by line from the file and writing the UserID and their corresponding\n# tf, df and tf-idf values as rows and finally taking a transpose of the matrix\n# formed to get the required database schema mentioned above.\nannot_values_tf = [[\"Annotations\"] + annotation]\nannot_values_df = [[\"Annotations\"] + annotation]\nannot_values_idf = [[\"Annotations\"] + annotation]\nfor line in list_of_lines:\n flag = 0\n values_tf = [0] * len(annotation)\n values_df = [0] * len(annotation)\n values_idf = [0] * len(annotation)\n for i in range(1, len(line), 4):\n line[i] = line[i].replace(\"\\'\", \" \")\n line[i] = line[i].replace('\"', '')\n values_tf[dict_annot[line[i]]] = (int(line[i + 1]))\n values_df[dict_annot[line[i]]] = (int(line[i + 2]))\n values_idf[dict_annot[line[i]]] = (float(line[i + 3]))\n annot_values_tf.append([line[0]] + values_tf)\n annot_values_df.append([line[0]] + values_df)\n annot_values_idf.append([line[0]] + values_idf)\n\nfinal_annot_tf = list(map(list, zip(*annot_values_tf)))\nfinal_annot_df = list(map(list, zip(*annot_values_df)))\nfinal_annot_idf = list(map(list, zip(*annot_values_idf)))\n\n# Writing the schema into csv files for future access\nwith open(\"C:\\\\MWDB Project\\\\Code\\\\CSV\\\\Task_3\\\\TF_Loc.csv\", 'w', encoding = 'utf8', newline='') as outcsv: \n #configure writer to write standard csv file\n writer = csv.writer(outcsv, delimiter=',')\n for item in final_annot_tf:\n #Write item to outcsv\n writer.writerow(item)\n \nwith open(\"C:\\\\MWDB Project\\\\Code\\\\CSV\\\\Task_3\\\\DF_Loc.csv\", 'w', encoding = 'utf8', newline='') as outcsv: \n #configure writer to write standard csv file\n writer = csv.writer(outcsv, delimiter=',')\n for item in final_annot_df:\n #Write item to outcsv\n writer.writerow(item)\n \nwith open(\"C:\\\\MWDB Project\\\\Code\\\\CSV\\\\Task_3\\\\TF_IDF_Loc.csv\", 'w', encoding = 'utf8', newline='') as outcsv: \n #configure writer to write standard csv file\n writer = csv.writer(outcsv, delimiter=',')\n for item in final_annot_idf:\n #Write item to outcsv\n writer.writerow(item)","sub_path":"Code/Tasks/CSV_Writer_DB_Locations.py","file_name":"CSV_Writer_DB_Locations.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"348632524","text":"from django.shortcuts import render, redirect, reverse\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework.status import (\n HTTP_400_BAD_REQUEST,\n HTTP_404_NOT_FOUND,\n HTTP_200_OK,\n HTTP_403_FORBIDDEN,\n HTTP_500_INTERNAL_SERVER_ERROR,\n HTTP_401_UNAUTHORIZED,\n HTTP_201_CREATED\n)\nfrom rest_framework import generics\nfrom core.models import *\nfrom customer.api.serializers import *\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nimport datetime\n# Create your views here.\n\ntoday = datetime.date.today()\n\n@api_view([\"POST\"])\ndef addToCart(request):\n return Response({\"response\": \"Rating successfully\"}, status=200)\n #if request.method == 'POST':\n # cart = Cart()\n # print('hiiiiiiiiiiiiiiiiii')\n # cart.qr_code = QRCode.objects.get(qr_code_id=\"hjws5tbp\")\n # cart.menu_item = MenuItem.objects.get(id=request.POST['menu'])\n # cart.save()\n # return redirect(reverse('customer:index'))\n \nclass myCart(APIView):\n def post(self, request):\n if request.data:\n serializer = AddToCartSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n \n try:\n qr_code = QRCode.objects.get(qr_code_id=request.data['qr_code'])\n menuitem = MenuItem.objects.get(id=request.data['menuitem'])\n if Cart.objects.filter(qr_code = qr_code, menu_item = menuitem, is_active=True).exists():\n cart = Cart.objects.get(qr_code=qr_code, menu_item = menuitem, is_active=True)\n qty = cart.quantity\n cart.quantity = qty + int(request.data['quantity'])\n cart.date_updated = today\n cart.save()\n \n else:\n serializer.save(qr_code=qr_code, menu_item=menuitem)\n \n return Response({'status':HTTP_201_CREATED,\"data\":[],'message':'Added to bag'})\n except:\n return Response({'status':HTTP_400_BAD_REQUEST,'data':[],\"message\":\"Incorrect QR Code or Menu\"})\n else:\n return Response({'status':HTTP_500_INTERNAL_SERVER_ERROR,'data':[],\"message\":\"Something went wrong. Please try again later\"})\n\n def get(self, request, qrcode_id=None):\n if qrcode_id == None:\n return Response({'status':HTTP_403_FORBIDDEN,'data':[],\"message\": \"QR Code id not present\"})\n\n elif len(qrcode_id) <= 0:\n return Response({'status':HTTP_401_UNAUTHORIZED,'data':[],\"message\": \"Invalid QR Code\"})\n\n elif len(qrcode_id) >= 0:\n try:\n qr_object = QRCode.objects.get(qr_code_id=qrcode_id)\n cart = Cart.objects.filter(is_active=True,qr_code=qr_object).order_by('id')\n if cart.exists():\n serializer = ListCartSerializer(cart, many=True, context={\"request\": request})\n return Response({'status':HTTP_200_OK,\"data\": serializer.data,'message':'OK'})\n else:\n return Response({'status':HTTP_404_NOT_FOUND,'data':[],\"message\": \"No data\"}, )\n except:\n return Response({'status':HTTP_400_BAD_REQUEST,'data':[],\"message\":\"Incorrect QR Code \"})\n\n else:\n return Response({'status':HTTP_500_INTERNAL_SERVER_ERROR,'data':[],\"message\":\"Something went wrong. Please try again later\"})","sub_path":"emenudsp/customer/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"454998267","text":"from gibson.envs.env_modalities import CameraRobotEnv, BaseRobotEnv\nfrom gibson.envs.env_bases import *\nfrom gibson.core.physics.robot_locomotors import VirtualCamera\nfrom transforms3d import quaternions\nimport os\nimport numpy as np\nimport sys\nimport pybullet as p\nfrom gibson.core.physics.scene_stadium import SinglePlayerStadiumScene\nimport pybullet_data\nimport cv2\n\nCALC_OBSTACLE_PENALTY = 1\n\ntracking_camera = {\n 'yaw': 20,\n 'z_offset': 0.5,\n 'distance': 1,\n 'pitch': -20\n}\n\ntracking_camera_top = {\n 'yaw': 20, # demo: living room, stairs\n 'z_offset': 0.5,\n 'distance': 1,\n 'pitch': -20\n}\n\nclass VirtualCameraEnv(CameraRobotEnv):\n \"\"\"Specfy navigation reward\n \"\"\"\n def __init__(self, config, gpu_idx=0):\n #self.config = self.parse_config(config)\n self.config = config\n print(self.config[\"envname\"])\n assert(self.config[\"envname\"] == self.__class__.__name__ or self.config[\"envname\"] == \"TestEnv\")\n CameraRobotEnv.__init__(self, self.config, gpu_idx,\n scene_type=\"building\",\n tracking_camera=tracking_camera)\n\n self.robot_introduce(VirtualCamera(self.config, env=self))\n self.scene_introduce()\n self.gui = self.config[\"mode\"] == \"gui\"\n self.total_reward = 0\n self.total_frame = 0\n assert(self.config[\"envname\"] == self.__class__.__name__ or self.config[\"envname\"] == \"TestEnv\")\n\n def add_text(self, img):\n font = cv2.FONT_HERSHEY_SIMPLEX\n x,y,z = self.robot.body_xyz\n r,p,ya = self.robot.body_rpy\n cv2.putText(img, 'x:{0:.4f} y:{1:.4f} z:{2:.4f}'.format(x,y,z), (10, 20), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA)\n cv2.putText(img, 'ro:{0:.4f} pth:{1:.4f} ya:{2:.4f}'.format(r,p,ya), (10, 40), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA)\n cv2.putText(img, 'potential:{0:.4f}'.format(self.potential), (10, 60), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA)\n cv2.putText(img, 'fps:{0:.4f}'.format(self.fps), (10, 80), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA)\n return img\n\n def _rewards(self, action=None, debugmode=False):\n return [0]\n\n def _termination(self, debugmode=False):\n return False\n\n def _reset(self):\n self.total_frame = 0\n self.total_reward = 0\n obs = CameraRobotEnv._reset(self)\n return obs\n","sub_path":"gibson/envs/camera_env.py","file_name":"camera_env.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"537071029","text":"from bs4 import BeautifulSoup as bs\nimport requests\nimport psycopg2\n\nglobus_page = requests.get(\n url = 'https://globus-online.kg/catalog/ovoshchi_frukty_orekhi_zelen/'\n).text\n\ndata = bs(globus_page, 'html.parser')\n\nconnection = psycopg2.connect(\n dbname = 'globus',\n user = 'postgres',\n password = '0709045683kgg',\n host = 'localhost'\n)\ncursor = connection.cursor()\n\n# create = '''CREATE TABLE vegetables (\n# user_id SERIAL PRIMARY KEY,\n# image_link VARCHAR(300) NOT NULL,\n# product_name VARCHAR(300) NOT NULL,\n# price VARCHAR(300) NOT NULL\n# );'''\n# cursor.execute(create)\n# cursor.connection.commit()\n\n\nview_showcase = data.find('div', attrs={ 'id': 'view-showcase'})\n\nall_card = view_showcase.find_all('div', class_= 'list-showcase__part-main')\n\nfor card in all_card:\n image = card.find('div', class_='list-showcase__picture').a.img.get('src')\n name_of_product = card.find('div', class_='list-showcase__name-rating').a.text\n price = card.find('div', class_='list-showcase__prices').find('span', class_='c-prices__value js-prices_pdv_ГЛОБУС Розничная').text\n print(name_of_product)\n\n\n a = f'''INSERT INTO vegetables (image_link, product_name, price)\n VALUES (\\'{image}\\', \\'{name_of_product}\\', \\'{price}\\');'''\n \n cursor.execute(a)\n connection.commit()","sub_path":"veget_parsers.py","file_name":"veget_parsers.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"74868589","text":"import requests\nfrom pyquery import PyQuery\nfrom mymodule import stats_word\n\n\n# 通过url获取文本并分析\ndef stats (url) :\n response = requests.get(url)\n # 提取微信公众号正文\n document = PyQuery (response.text)\n content = document ('#js_content').text() \n # 统计前100词频\n statList = stats_word.stats_text(content,100)\n statString = ''.join(str(i) for i in statList)\n\n return statString\n","sub_path":"19100101/Shawn/d12_training1.py","file_name":"d12_training1.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"477933273","text":"__author__ = \"Kamil Markowiak\"\n__copyright__ = \"Copyright 2018, 4imp Kamil Markowiak\"\n__license__ = \"GPL\"\n__email__ = \"kamil.markowiak@protonmail.com\"\n\nfrom variables import folder_tmp, wpisy, result_no_blank_lines, line_numbers\nimport re\n\n\ndef NumeryLiniiDoPodzialu():\n Wpisy_file = folder_tmp+wpisy\n Output_file = folder_tmp+result_no_blank_lines\n test1 = open(Wpisy_file, 'w')\n licznik = re.compile('^[0-9]+\\s?\\.\\s?[Ww]')\n with open(Output_file, 'r') as plik:\n numery_linii_do_podzialu = []\n with open(folder_tmp+line_numbers, 'w') as output:\n for line_i, line in enumerate(plik, 1):\n if licznik.search(line):\n output.write(\"%d\\n\" % line_i)\n test1.write(\"%s\\n\" % line)\n numery_linii_do_podzialu.append(line_i)\n return numery_linii_do_podzialu\n test1.close()\n","sub_path":"csv_record_separator.py","file_name":"csv_record_separator.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232682488","text":"#!/usr/bin/env python\n# coding: utf-8\nimport pandas as pd \nimport numpy as np \nfrom scipy.special import comb \nimport math\nfrom operator import mul\nimport neal \nimport dimod \nimport random \nimport matplotlib.pyplot as plt \nimport timeit\nimport time\nfrom itertools import combinations\n\n\ndef calc_marginals(df): \n return np.array([ \n sum(df['Y']), \n np.dot(df['Y'], df['SEX']), \n np.dot(df['Y'], df['AOP']), \n ]) \n\n\ndef make_Hamiltonian(df):\n t_list = calc_marginals(df)\n \n N=len(df)\n dup_list = [(i, i) for i in range(N)]\n comb_list = [(i, j) for i in range(N) for j in range(i+1, N)]\n \n lin_Y = [1-2*t_list[0] for (i, _) in dup_list] #同じy同士\n quad_Y = [2 for (i, j) in comb_list] #異なるy同士\n num_Y = t_list[0]**2 #数字の二乗\n \n SEX = df['SEX'].iloc\n lin_SEX = [(SEX[i] - 2 * t_list[1]) * SEX[i] for (i, _) in dup_list]\n quad_SEX = [2*SEX[i] * SEX[j] for (i, j) in comb_list]\n num_SEX = t_list[1]**2\n \n AOP = df['AOP'].iloc\n lin_AOP = [(AOP[i] - 2 * t_list[2]) * AOP[i] for (i, _) in dup_list]\n quad_AOP = [2*AOP[i] * AOP[j] for (i, j) in comb_list]\n num_AOP = t_list[2]**2\n \n lin_list = [sum(lin) for lin in zip(lin_Y, lin_SEX, lin_AOP)]\n lin = {i: lin_list[i] for (i, _) in dup_list}\n \n #quad\n quad_values = [sum(quad) for quad in zip(quad_Y, quad_SEX, quad_AOP)]\n quad = {ij: quad_values[n] for (n, ij) in enumerate(comb_list)}\n \n #num\n num = num_Y + num_SEX + num_AOP\n \n return dimod.BinaryQuadraticModel(lin, quad, num, dimod.Vartype.BINARY)#dic, dic, num\n\n\ndef make_res_data(df, num_reads):\n sa_sampler = neal.sampler.SimulatedAnnealingSampler()\n initial_states = df['Y'].values.tolist()\n bqm = make_Hamiltonian(df)\n res = sa_sampler.sample(\n bqm, num_reads=num_reads, \n initial_states=initial_states, \n initial_states_generator='tile'\n ) \n return res\n\ndef find_valid_y(res): \n valid_y_list= [] \n valid_y_num= 0\n occurrence_list = []\n this_time_y_list = []\n for y_info in list(res.record):\n if y_info[1]==0.:\n this_time_y = list(y_info[0])\n if all([this_time_y != p for p in valid_y_list]): \n valid_y_list.append(this_time_y)\n valid_y_num += 1\n occurrence_list.append(1)\n this_time_y_list.append(this_time_y)\n else:\n i = this_time_y_list.index(this_time_y)\n occurrence_list[i] += 1\n return valid_y_list, valid_y_num, occurrence_list\n\n\ndef y_num_hist(df, valid_y_list, path):\n LI = list(df['LI'])\n hist_dic = {}\n for valid_y in valid_y_list:\n t1 = int(np.dot(LI, valid_y))\n if t1 in hist_dic.keys():\n hist_dic[t1] += 1\n else:\n hist_dic[t1] = 1\n \n \n x = [i for i in list(hist_dic.keys())]\n plt.xlabel('value of t1')\n plt.ylabel('number of samples')\n plt.bar(x, list(hist_dic.values()))\n plt.xticks(x, x)\n plt.savefig(path)\n plt.show()\n return hist_dic\n\ndef occurence_hist(occurrence_list, plot_path):\n x = [i for i in range(len(occurrence_list))]\n plt.xlabel('each sample')\n plt.ylabel('number of the occurrence')\n plt.bar(x, occurrence_list)\n ax = plt.gca()\n ax.axes.xaxis.set_visible(False)\n plt.savefig(plot_path)\n return plt.show()\n \ndef time_num_y(df, num_reads, path):\n time_list = []\n time_0 = time.time() \n sa_sampler = neal.sampler.SimulatedAnnealingSampler()\n \n initial_states = df['Y'].values.tolist()\n t_list = calc_marginals(df)\n \n valid_y_list= [] \n valid_y_num= 0\n bqm = make_Hamiltonian(df)\n res = sa_sampler.sample(\n bqm, num_reads=num_reads, \n initial_states=initial_states, \n initial_states_generator='tile'\n ) \n for y_info in list(res.record):\n if y_info[1]==0.:\n if len(valid_y_list)==0:\n valid_y_list.append(list(y_info[0]))\n valid_y_num += 1\n time_1 = time.time()\n elapsed_time = time_1 - time_0\n time_list.append(elapsed_time)\n \n elif all(list(y_info[0]) != p for p in valid_y_list): \n valid_y_list.append(list(y_info[0]))\n valid_y_num += 1\n time_1 = time.time()\n elapsed_time = time_1 - time_0\n time_list.append(elapsed_time)\n \n valid_y_num_list = [i for i in range(1, valid_y_num+1)]\n \n plt.xlabel('time')\n plt.ylabel('number of hits')\n plt.plot(time_list, valid_y_num_list)\n plt.savefig(path)\n plt.show()\n return valid_y_list, valid_y_num_list, time_list\n\n\ndef p_value_transition(df, num_reads, output_path) :\n sa_sampler = neal.sampler.SimulatedAnnealingSampler()\n \n initial_states = df['Y'].values.tolist()\n t_list = calc_marginals(df)\n t1 = int(np.dot(df['Y'], df['LI']))\n t1_y = 0\n p_dic = {}\n \n valid_y_num= 0\n valid_y_list = []\n bqm = make_Hamiltonian(df)\n res = sa_sampler.sample(\n bqm, num_reads=num_reads, \n initial_states=initial_states, \n initial_states_generator='tile'\n )\n \n \n for y_info in list(res.record):\n if y_info[1]==0.:\n valid_y = list(y_info[0]) \n if all(valid_y != p for p in valid_y_list):\n valid_y_num += 1\n valid_y_list.append(valid_y)\n if int(np.dot(valid_y, list(df['LI'])))==t1:\n t1_y += 1\n p_dic[valid_y_num] = t1_y/valid_y_num\n \n plt.xlabel('number of hits')\n plt.ylabel('p value')\n plt.plot(list(p_dic.keys()), list(p_dic.values()))\n plt.savefig(output_path)\n plt.show()\n \n return valid_y_num, valid_y_list, p_dic\n\n\ndef test_find_valid_y():\n df = pd.read_csv('../../input/ost20.csv', sep=',', index_col=0)\n valid_y_list, valid_y_num = find_valid_y(df, num_reads = 10)\n return valid_y_list, valid_y_num\n\n\n\ndef test_validity(canditate_list):\n df1 = pd.read_csv('../../input/ost20.csv', sep=',',index_col=0)\n df2 = pd.read_csv('../../input/ost20.csv', sep=',',index_col=0)\n new_y = np.array(canditate_list)\n df2['Y'] = new_y\n t_list1 = calc_marginals(df1)\n t_list2 = calc_marginals(df2)\n print(t_list1)\n print(t_list2)\n assert np.all(t_list1[[0,2]] == t_list2[[0,2]])\n\n","sub_path":"202011/scripts/functions/Neal_exact_test_functions.py","file_name":"Neal_exact_test_functions.py","file_ext":"py","file_size_in_byte":7053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327906164","text":"# MediaPipePose\nimport cv2\nimport mediapipe as mp\nimport math\nimport os\nimport requests\n\nclass Point:\n x = 0\n y = 0\n\n# 각도가 성공 기준에 들어갈 경우에는, len 값을 올려주어 이 len 값을 기준으로 score를 매길 예정.\nready_success_len = swing_success_len = finish_success_len = 0\n# 피드백 문구로 넣을 예정.\nready_feedback = swing_feedback = finish_feedback = \"\"\n# 측정하지 못했을 경우에는 1을 return하는 변수\nisErrorSwing = isErrorReady = isErrorFinish = 0 # true or false\n\n#p1, p2, p3 세 점을 입력받아 p2 중심으로 각도를 return하는 함수.\ndef Angle(P1, P2, P3):\n a = math.sqrt(math.pow(P1.x - P2.x, 2) + math.pow(P1.y - P2.y, 2))\n b = math.sqrt(math.pow(P2.x - P3.x, 2) + math.pow(P2.y - P3.y, 2))\n c = math.sqrt(math.pow(P1.x - P3.x, 2) + math.pow(P1.y - P3.y, 2))\n angle = math.acos((a * a + b * b - c * c) / (2 * a * b))\n return (angle * 180) / PI\n\n#p11, p12의 중심점, p2, p3의 각도를 return하는 함수.\ndef Angle2(P11, P12, P2, P3):\n P1 = Point()\n P1.x = (P11.x + P12.x) / 2\n P1.y = (P11.y + P12.y) / 2\n a = math.sqrt(math.pow(P1.x - P2.x, 2) + math.pow(P1.y - P2.y, 2))\n b = math.sqrt(math.pow(P2.x - P3.x, 2) + math.pow(P2.y - P3.y, 2))\n c = math.sqrt(math.pow(P1.x - P3.x, 2) + math.pow(P1.y - P3.y, 2))\n angle = math.acos((a * a + b * b - c * c) / (2 * a * b))\n return (angle * 180) / PI\n\n#피타코라스 활용 거리 return 함수\ndef Distance(P1,P2):\n distance = math.sqrt(pow(P1.x - P2.x, 2)+pow(P1.y - P2.y, 2))\n return distance\n\n# 각 각도에 대하여 ox 판별하는 함수. (eval_ready, eval_swing, eval_finish)\n# rs : 해당 각도\n# skeleton : 각 각도에 대한 한글명\n# minNum, maxNum : 스켈레톤에 최솟값, 최댓값\ndef eval_ready(rs, skeleton, minNum, maxNum):\n global ready_success_len, ready_feedback, isErrorReady\n if skeleton == \"keyCheck\":\n if rs < 110:\n isErrorReady = 1\n ready_success_len = 0\n return\n if minNum < rs < maxNum:\n ready_success_len += 1\n else:\n if ready_feedback == \"\":\n ready_feedback = skeleton\n else:\n ready_feedback = ready_feedback + \", \" + skeleton\n\ndef eval_swing(rs, skeleton, minNum, maxNum):\n global swing_success_len, swing_feedback, isErrorSwing\n if skeleton == \"keyCheck\":\n if rs < 110:\n isErrorSwing = 1\n swing_success_len = 0\n return\n if minNum < rs < maxNum:\n swing_success_len += 1\n else:\n if swing_feedback == \"\":\n swing_feedback = skeleton\n else:\n swing_feedback = swing_feedback + \", \" + skeleton\n\ndef eval_finish(rs, skeleton, minNum, maxNum):\n global finish_success_len, finish_feedback, isErrorFinish\n if skeleton == \"keyCheck\":\n if rs < 110:\n isErrorFinish = 1\n finish_success_len = 0\n return\n if minNum < rs < maxNum:\n finish_success_len += 1\n else:\n if finish_feedback == \"\":\n finish_feedback = skeleton\n else:\n finish_feedback = finish_feedback + \", \" + skeleton\n\nmp_drawing = mp.solutions.drawing_utils\nmp_pose = mp.solutions.pose\nPI = 3.1415926535\nnum = -1\n\n#프로 자세기반 기준 점수.\nBASESCORE_READY = [72.53, 69.72, 72.47, 85.34, 172.4, 173.95]\nBASESCORE_SWING = [156.0, 170.63, 169.8, 131.81, 138.6]\nBASESCORE_FINISH = [144.31, 162.99]\n\nDATA_DIR = os.getcwd() + \"/images\"\nIMAGE_FILES = os.listdir(DATA_DIR)\nIMAGE_FILES.sort()\nprint(IMAGE_FILES)\nlength1 = length4 = 0\nlength2 = length5 = 0\nlength3 = length6 = 0\n\nwith mp_pose.Pose(\n static_image_mode=True,\n model_complexity=2,\n min_detection_confidence=0.5) as pose:\n for idx, file in enumerate(IMAGE_FILES):\n if (file.find('drive') == -1): continue\n else: num += 1\n file = DATA_DIR + '/' + file\n image = cv2.imread(file)\n image_height, image_width, _ = image.shape\n\n # Convert the BGR image to RGB before processing.\n results = pose.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n if not results.pose_landmarks:\n if(file.find('first') != -1) : isErrorReady = 1\n elif(file.find('second') != -1) : isErrorSwing = 1\n elif(file.find('third') != -1) : isErrorFinish = 1\n continue\n annotated_image = image.copy()\n ll = [] # 각 번호마다의 위치를 저장하기 위한 임시 배열.\n for id, lm in enumerate(results.pose_landmarks.landmark):\n h, w, c = image.shape\n p = Point()\n p.x = int(lm.x * w)\n p.y = int(lm.y * h)\n ll.append(p)\n cv2.putText(annotated_image, str(id), (p.x, p.y), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 0), 1)\n\n # Draw pose landmarks on the image.\n mp_drawing.draw_landmarks(\n annotated_image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)\n cv2.imwrite('images_result/annotated_image' + str(num) + '.png', annotated_image)\n if (file.find('first') != -1):\n one = Angle2(ll[23], ll[24], ll[27], ll[28])\n two = Angle2(ll[23], ll[24], ll[28], ll[27])\n three = Angle(ll[12], ll[11], ll[13])\n four = Angle(ll[11], ll[12], ll[14])\n five = Angle(ll[11], ll[13], ll[15])\n six = Angle(ll[12], ll[14], ll[16])\n length1 = Distance(ll[0], ll[25])\n eval_ready(round(one, 2), \"왼발\", 65, 89)\n eval_ready(round(two, 2), \"오른발\", 61, 89)\n eval_ready(round(three, 2), \"왼쪽 어깨\", 50, 93)\n eval_ready(round(four, 2), \"오른쪽 어깨\", 60, 92)\n eval_ready(round(five, 2), \"왼쪽 팔꿈치\", 155, 180)\n eval_ready(round(six, 2), \"오른쪽 팔꿈치\", 160, 180)\n eval_ready(round(length1, 2), \"keyCheck\", 0, 0)\n\n if (file.find('second') != -1):\n ones = Angle(ll[12], ll[24], ll[26])\n twos = Angle(ll[24], ll[26], ll[28])\n threes = Angle(ll[23], ll[25], ll[27])\n fours = Angle(ll[11], ll[12], ll[14])\n fives = Angle(ll[12], ll[14], ll[16])\n length2 = Distance(ll[0], ll[25])\n eval_swing(round(ones, 2), \"오른쪽 허리\", 140, 180)\n eval_swing(round(twos, 2), \"오른쪽 무릎\", 167, 180)\n eval_swing(round(threes, 2), \"왼쪽 무릎\", 165, 180)\n eval_swing(round(fours, 2), \"오른쪽 어깨\", 110, 175)\n eval_swing(round(fives, 2), \"오른쪽 팔꿈치\", 70, 155)\n eval_swing(round(length2, 2), \"keyCheck\", 0, 0)\n\n if (file.find('third') != -1):\n onef = Angle(ll[24], ll[26], ll[28])\n twof = Angle(ll[12], ll[24], ll[26])\n length3 = Distance(ll[0], ll[25])\n eval_finish(round(onef, 2), \"오른쪽 무릎\", 125, 180)\n eval_finish(round(twof, 2), \"오른쪽 허리\", 155, 175)\n eval_finish(round(length3, 2), \"keyCheck\", 0, 0)\n\n rDict = {6: 'Perfect', 5: 'Good', 4: 'Good', 3: 'Notbad', 2: 'Fail', 1: 'Fail', 0: 'Fail'}\n sDict = {5: 'Perfect', 4: 'Good', 3: 'Good', 2: 'Notbad', 1: 'Fail', 0: 'Fail'}\n fDict = {2: 'Perfect', 1: 'Notbad', 0: 'Fail'}\n\n # print('본 프로그램은 아이언, 드라이브 모두에 적용됩니다.')\n # print('---------- 준비 자세 ----------')\n # print('결과 : ', rDict[ready_success_len])\n # print('아쉬운 자세 : ', ready_feedback)\n # print(ready_success_len)\n # print('---------- 스윙 자세 ----------')\n # print('결과 : ', sDict[swing_success_len])\n # print('아쉬운 자세 : ', swing_feedback)\n # print(swing_success_len)\n # print('---------- 피니시 자세 ----------')\n # print('결과 : ', fDict[finish_success_len])\n # print('아쉬운 자세 : ', finish_feedback)\n # print(finish_success_len)\n\n result = {'ready_result': rDict[ready_success_len], 'ready_feedback': ready_feedback,\n 'swing_result': sDict[swing_success_len], 'swing_feedback': swing_feedback,\n 'finish_result': fDict[finish_success_len], 'finish_feedback': finish_feedback\n , 'isErrorReady': isErrorReady, 'isErrorSwing': isErrorSwing, 'isErrorFinish': isErrorFinish\n , 'length1': length1, 'length2': length2, 'length3': length3\n }\n resultText = {\"resultText\": result}\n # print(length1)\n # print(length2)\n # print(length3)\n print(result)\n res = requests.post('http://localhost:5000/api/feedbackdata', json=resultText)","sub_path":"getDriveImageScore.py","file_name":"getDriveImageScore.py","file_ext":"py","file_size_in_byte":8567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51943270","text":"from django.shortcuts import render, HttpResponse, _get_queryset\nfrom django.shortcuts import render, redirect, get_object_or_404, render_to_response\nfrom .forms import WikiPostsModel, WikiPostsForm, RelatedModel, RelatedForm, AuthorModel, AuthorForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import views as auth_views\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import ObjectDoesNotExist\nimport operator\nimport re\nfrom django.db.models import Q\n\n\n# function to show all entries at index\ndef index(request):\n allEntries = WikiPostsModel.objects.all()\n context = {\n \"allEntries\": allEntries\n }\n\n return render(request, 'Project2App/index.html', context)\n\n\n\n# function is redundanf...might delete...\ndef allEntries(request):\n entry_list = WikiPostsModel.objects.all()\n context = {'entry_list': entry_list}\n return render(request, 'Project2App/allEntries.html', context)\n\n# function to allow entering new wiki posts if user is logged in\n@login_required\ndef yourEntries(request):\n # If the current person is logged in, do the code below\n if request.user.is_authenticated:\n # This puts the logged in user entry into the variable author\n author= AuthorModel.objects.get(id=1)\n # This will grab all of the entries for the logged in user using the variable you just created\n allEntries = WikiPostsModel.objects.filter(foreignkeyToAuthor=author).order_by('id')\n # If the user is not logged in...\n else:\n # Make all Entries blank because you need this because both the index.html page is expecting a allEntries variable\n allEntries = \"\"\n context = {\"allEntries\": allEntries}\n return render(request, \"Project2App/yourEntries.html\", context)\n\n\n\n# This page will provide a form to add users\ndef createUser(request):\n # POST Request\n # If the form is being pushed to this function\n if request.method == \"POST\":\n print(request.method)\n # This will put all the user's information from the HTML page into this new form variable\n form = AuthorForm(request.POST)\n # Run all the validation on this form\n if form.is_valid():\n # Save the form's information in the model\n form.save()\n # Create a new Django User entry\n User.objects.create_user(request.POST[\"username\"], request.POST[\"password1\"], request.POST[\"password2\"])\n return redirect(\"index\")\n else:\n context = {\n \"errors\": form.errors,\n \"form\": form\n }\n return render(request, \"Project2App/createUser.html\", context)\n\n\n # GET Request\n else:\n # This will create a blank form using AuthorForm\n form = AuthorForm()\n context = {\"form\": form}\n return render(request, \"Project2App/createUser.html\", context)\n\n\n# Allows the edit of user information\ndef editUser(request, username):\n user = get_object_or_404(User, pk=username)\n edit_form = AuthorForm(request.POST or None, instance=AuthorModel)\n if edit_form.is_valid():\n edit_form.save()\n return redirect('index')\n\n return render(request, 'Project2App/createUser.html', {'userform': edit_form})\n\n# this function will delete a user\ndef deleteuser(request, username):\n user = get_object_or_404(User, pk=username)\n if request.method == 'POST':\n user.delete()\n return redirect('index')\n\n return render(request, 'Project2App/delete.html', {'selecteduser': user})\n\n\n# this function allow only logged in users to add new wiki posts\n@login_required()\ndef addNewEntry(request):\n # This will create a blank form using CollectorForm\n form = WikiPostsForm()\n context = {\n \"form\": form\n }\n return render(request, \"Project2App/addNewEntry.html\", context)\n\n\ndef gotNewEntryInfo(request):\n # This will put all the user's information from the HTML page into this new form variable\n form = WikiPostsForm(request.POST)\n # This puts the logged in user entry into the variable collector\n author = AuthorModel.objects.get(username=request.user)\n\n # create a wiki post entry from the logged in user\n if form.is_valid():\n # Created a new WikiPostModel entry usin the user's form information that was passed using the request.POST\n WikiPostsModel.objects.create(postTitle=request.POST[\"postTitle\"], postText=request.POST[\"postText\"],\n createdDateTime=request.POST[\"createdDateTime\"],\n lastUpdatedDateTime=request.POST[\"lastUpdatedDateTime\"],\n optionalPostImage=request.POST[\"optionalPostImage\"],\n foreignKeyToAuthor=author)\n return redirect(\"index\")\n else:\n context = {\"form\": form, \"errors\": form.errors}\n return render(request, \"Project2App/addNewEntry.html\", context)\n\n\n# this function allows the edit of wiki post entries\ndef editEntries(request, wikipostsID):\n # Grab an exact entry of the WikiPostsModel using the primary key\n editExistingWikiPost = get_object_or_404(WikiPostsModel, pk=wikipostsID)\n\n # Post method\n if request.method == \"POST\":\n # This will fill in the form with the user's information and use the exact WikiPostsModel with primary key\n form = WikiPostsForm(request.POST, instance=editExistingWikiPost)\n if form.is_valid():\n form.save()\n else:\n print(\"Form is not valid\")\n return redirect(\"index\")\n\n # Get method\n # Grabbed the exact wikipost form using the existing WikiPosts model using the primary key from earlier\n form = WikiPostsForm(instance=editExistingWikiPost)\n context = {\n \"form\": form,\n \"wikipostsID\": wikipostsID\n }\n return render(request, \"Project2App/editEntries.html\", context)\n\n# function to delete wiki posts\ndef deleteEntries(request, wikipostsID):\n deleteThisWikiPost = get_object_or_404(WikiPostsModel, pk=wikipostsID)\n deleteThisWikiPost.delete()\n return redirect(\"index\")\n\n# function to delete related entries\ndef relatedEntries(request):\n related_list = RelatedModel.objects.all()\n context = {\n \"related_list\": related_list\n }\n return render(request, 'Project2App/index.html', context)\n\n# function to add a related entry\ndef addRelated(request):\n # This will create a blank form using CollectorForm\n form = RelatedForm()\n context = {\n \"form\": form\n }\n return render(request, \"Project2App/addRelated.html\", context)\n\n\ndef gotRelatedInfo(request):\n # Put all the user's info from the HTML page into a new form variable\n form = RelatedForm(request.POST)\n # Put the logged in user's related entry into variable\n wikipost = WikiPostsModel.objects.get(postTitle=request.user)\n # create a related entry from the logged in user...\n if form.is_valid():\n RelatedModel.objects.create(itemTitle=request.POST[\"itemTitle\"], itemText=request.POST[\"itemText\"],\n createdDateTime=request.POST[\"createdDateTime\"],\n lastUpdatedDateTime=request.POST[\"lastUpdatedDateTime\"],\n optionalPostImage=request.POST[\"optionalPostImage\"], foreignKeyToUser=User)\n return redirect(\"index\")\n else:\n context = {\"form\": form, \"errors\": form.errors}\n return render(request, \"Project2App/addRelated.html\", context)\n\n\ndef editRelated(request, relatedID):\n # Grab an exact entry of the RelatedModel using the primary key\n editExistingRelated = get_object_or_404(RelatedModel, pk=relatedID)\n\n # Post method\n if request.method == \"POST\":\n # This will fill in the form with the user's information and use the exact RelatedModel with primary key\n form = RelatedForm(request.POST, instance=editExistingRelated)\n if form.is_valid():\n form.save()\n else:\n print(\"Form is not valid\")\n return redirect(\"index\")\n\n # Get method\n # Grabbed the exact related form using the existing Related model using the primary key from earlier\n form = RelatedForm(instance=editExistingRelated)\n context = {\n \"form\": form,\n \"relatedID\": relatedID\n }\n return render(request, \"Project2App/editRelated.html\", context)\n\n#function to delete a related entry\ndef deleteRelated(request, relatedID):\n deleteThisRelated = get_object_or_404(RelatedModel, pk=relatedID)\n deleteThisRelated.delete()\n return redirect(\"index\")\n\n#function to search wiki posts\ndef searchPosts(request):\n return HttpResponse(\"search here\")\n","sub_path":"Project2/Project2App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366139849","text":"########################################################################################################\nimport hashlib, sys, os\n########################################################################################################\ndef hash(path, email_type):\n\tfilenames=os.listdir(path)\n\ttry:\n\t\tos.makedirs(\"/home/eward/Downloads/Dataset\")\n\texcept OSError:\n\t\tpass\n\tfor filename in filenames:\n\t\tcurrent_file=open(path+filename, \"r+\")\n\t\tparsed_file=open(\"/home/eward/Downloads/Dataset/\"+email_type+\"_\"+filename, \"w\")\n\t\tparsed_file.write(email_type+\"\\n\")\n\t\tfor line in current_file.readlines():\n\t\t\tz=line.split(\" \")\n\t\t\tz[0]=z[0].encode(\"UTF-8\")\n\t\t\thashed_word=hashlib.md5(z[0])\n\t\t\tparsed_file.write(hashed_word.hexdigest()+\" \"+str(z[1])+\" \\n\")\n\t\t\tdel hashed_word\n\t\tcurrent_file.close()\n\t\tparsed_file.close()\n\t\t\ndef main():\n\thash(sys.argv[1], sys.argv[2])\n\nif __name__==\"__main__\":\n\tmain()\n\n\n\t\n\t\t\n\t\n\t\n\n","sub_path":"hasher.py","file_name":"hasher.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"272178416","text":"from .global_config import *\n\n# store all variables from global config\ncontext_vars = vars()\n\n# folders\nnoisy_folder = 'noisy'\nnot_noisy_folder = 'notNoisy'\n\n# file or extensions\npost_image_name_separator = '___'\n\n# variables\nfeatures_choices_labels = ['static', 'svd_reconstruction', 'fast_ica_reconstruction', 'ipca_reconstruction']\n\n# parameters\nkeras_epochs = 30\nkeras_batch = 32\nval_dataset_size = 0.2\n\nkeras_img_size = (200, 200)","sub_path":"config/cnn_config.py","file_name":"cnn_config.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"31816763","text":"#!/usr/bin/env python\nfrom pylab import *\norigin = 'lower'\n#origin = 'upper'\n\n# The following controls only interior masking.\ntest_masking = False # There is a bug in filled contour masking with\n # interior masks.\n\nif test_masking:\n # Use a coarse grid so only a few masked points are needed.\n delta = 0.5\nelse:\n delta = 0.025\n\nx = y = arange(-3.0, 3.01, delta)\nX, Y = meshgrid(x, y)\nZ1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)\nZ2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)\nZ = 10 * (Z1 - Z2)\n\n# interior badmask doesn't work yet for filled contours\nif test_masking:\n badmask = zeros(shape(Z))\n\n badmask[5,5] = 1\n badmask[5,6] = 1\n Z[5,5] = 0\n Z[5,6] = 0\n\n badmask[0,0] = 1\n Z[0,0] = 0\n Z = ma.array(Z, mask=badmask)\n\nnr, nc = Z.shape\n\n# put NaNs in one corner:\nZ[-nr//6:, -nc//6:] = nan\n# contourf will convert these to masked\n\n\nZ = ma.array(Z)\n# mask another corner:\nZ[:nr//6, :nc//6] = ma.masked\n\n\n# We are using automatic selection of contour levels;\n# this is usually not such a good idea, because they don't\n# occur on nice boundaries, but we do it here for purposes\n# of illustration.\nCS = contourf(X, Y, Z, 10, # [-1, -0.1, 0, 0.1],\n #alpha=0.5,\n cmap=cm.bone,\n origin=origin)\n\n# Note that in the following, we explicitly pass in a subset of\n# the contour levels used for the filled contours. Alternatively,\n# We could pass in additional levels to provide extra resolution.\n\nCS2 = contour(X, Y, Z, CS.levels[::2],\n colors = 'r',\n origin=origin,\n hold='on')\n\ntitle('Nonsense (with 2 masked corners)')\nxlabel('word length anomaly')\nylabel('sentence length anomaly')\n\n# Make a colorbar for the ContourSet returned by the contourf call.\ncbar = colorbar(CS)\ncbar.ax.set_ylabel('verbosity coefficient')\n# Add the contour line levels to the colorbar\ncbar.add_lines(CS2)\n\nfigure()\n\n# Now make a contour plot with the levels specified,\n# and with the colormap generated automatically from a list\n# of colors.\nlevels = [-2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5]\nCS3 = contourf(X, Y, Z, levels,\n colors = ('r', 'g', 'b'),\n origin=origin)\n\nCS4 = contour(X, Y, Z, levels,\n colors = ('k',),\n linewidths = (3,),\n origin = origin)\ntitle('Listed colors (with 2 masked corners)')\nclabel(CS4, fmt = '%2.1f', colors = 'w', fontsize=14)\ncolorbar(CS3)\n\nshow()\n\n","sub_path":"lang/python/algo/scipy/aLotMore/pylab_examples/contourf_demo.py","file_name":"contourf_demo.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"469192403","text":"import miscellaneous\nimport time\n\n\n\n\n\n\n\n\n\ndef execute(data, output_location):\n \"\"\"\n This function calls the appropriate functions in miscellaneous.py. Those functions will use the encrypt() function\n located below as the algorithm to actually encrypt the text. Then, the ciphertext will be returned back to\n cryptography_runner.py\n\n :param data: (string) the data to be encrypted\n :param output_location: (string) the file to write relevant information into\n :return: (string) the encrypted data\n \"\"\"\n\n\n # Obtain the encrypted text. Also write statistics and relevant info a file\n encrypted = miscellaneous.symmetric_encrypt_or_decrypt_with_general_key(data, output_location,\n \"Encryption\", \"vigenere_multiplicative\", \"encrypt\")\n\n # Return encrypted text to be written in cryptography_runner\n return encrypted\n\n\n\n\n\n# The actual algorithm to encrypt using a vigenere cipher(multiplication instead of addition)\ndef encrypt(plaintext, key, char_set_size):\n \"\"\"\n This function encrypts with a vigenere cipher that multiplies instead of adds. Done to access more characters in\n unicode. If ascii or extended_ascii, store as numbers. Otherwise, store as characters\n\n :param plaintext: (string) the plaintext to encrypt with\n :param key: (string) the string to encrypt with\n :param char_set_size: (integer) the number of characters in the character set used\n :return: (string) the encrypted text\n \"\"\"\n\n ciphertext = \"\"\n ciphertext_list = [] # for storing unicode values of the numbers (when char_set_size <= 256). Done for speed\n key_index = 0\n\n # if using unicode, then adjust the size of the char_set_size to be printable characters only (no surrogates)\n if char_set_size > 256:\n char_set_size = char_set_size - miscellaneous.SURROGATE_BOUND_LENGTH\n\n # Counter for printing purposes\n characters_done = 0\n\n for x in plaintext:\n\n characters_done += 1\n\n # figure out the unicode value for each of the characters\n uni_val_plain = ord(x)\n\n # figure out the unicode value for the right character in the key, then update for next iteration\n key_char = key[key_index]\n uni_val_key = ord(key_char)\n\n key_index = (key_index + 1) % len(key)\n\n\n # figure out the encrypted character val (un-modded)\n uni_val_encrypted = (uni_val_plain * uni_val_key)\n\n\n # if the encrypted_char would be a surrogate(unprintable), adjust by adding SURROGATE_BOUND_LENGTH\n if miscellaneous.SURROGATE_LOWER_BOUND <= uni_val_encrypted:\n encrypted_char = chr(uni_val_encrypted + miscellaneous.SURROGATE_BOUND_LENGTH)\n\n\n # Print updates\n if characters_done % 100 == 0:\n print (\"Percentage of text done: \" + str(characters_done / len(plaintext) * 100))\n\n\n # Add the encrypted character to the overall encrypted message (if using unicode)\n if char_set_size > 256:\n\n # Find the encrypted char value(modded)\n uni_val_encrypted = (uni_val_plain * uni_val_key) % char_set_size\n encrypted_char = chr(uni_val_encrypted)\n\n # Add to ciphertext\n ciphertext = ciphertext + encrypted_char\n\n # Otherwise, add the number to the overall encrypted message (list)\n else:\n ciphertext_list.append(str(uni_val_encrypted))\n\n\n # Build up ciphertext if necessary(when we were using list (when char_set_size <= 256))\n if ciphertext == \"\":\n ciphertext = \" \".join(ciphertext_list)\n\n return ciphertext\n\n\n\n\n\n","sub_path":"Encryption/vigenere_multiplicative.py","file_name":"vigenere_multiplicative.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"489427561","text":"\nfrom modules.IEnvironmentController import IEnvironmentController\nfrom python_terraform import *\nfrom modules import aws_service, splunk_sdk\nfrom tabulate import tabulate\nimport ansible_runner\n\n\nclass TerraformController(IEnvironmentController):\n\n def __init__(self, config, log, packer_amis):\n super().__init__(config, log)\n custom_dict = self.config.copy()\n rem_list = ['log_path', 'log_level', 'art_run_techniques']\n [custom_dict.pop(key) for key in rem_list]\n custom_dict['ip_whitelist'] = [custom_dict['ip_whitelist']]\n if packer_amis:\n custom_dict['use_packer_amis'] = '1'\n else:\n custom_dict['use_packer_amis'] = '0'\n custom_dict['splunk_packer_ami'] = \"packer-splunk-server-\" + self.config['key_name']\n custom_dict['phantom_packer_ami'] = \"packer-phantom-server-\" + self.config['key_name']\n custom_dict['kali_machine_packer_ami'] = \"packer-kali-machine-\" + self.config['key_name']\n custom_dict['windows_domain_controller_packer_ami'] = \"packer-windows-domain-controller-\" + self.config['key_name']\n custom_dict['windows_server_packer_ami'] = \"packer-windows-server-\" + self.config['key_name']\n custom_dict['windows_client_packer_ami'] = \"packer-windows-client-\" + self.config['key_name']\n self.terraform = Terraform(working_dir='terraform',variables=custom_dict)\n\n\n def build(self):\n self.log.info(\"[action] > build\\n\")\n return_code, stdout, stderr = self.terraform.apply(capture_output='yes', skip_plan=True, no_color=IsNotFlagged)\n if not return_code:\n self.log.info(\"attack_range has been built using terraform successfully\")\n self.list_machines()\n\n def destroy(self):\n self.log.info(\"[action] > destroy\\n\")\n return_code, stdout, stderr = self.terraform.destroy(capture_output='yes', no_color=IsNotFlagged)\n self.log.info(\"attack_range has been destroy using terraform successfully\")\n\n\n def stop(self):\n instances = aws_service.get_all_instances(self.config)\n aws_service.change_ec2_state(instances, 'stopped', self.log)\n\n\n def resume(self):\n instances = aws_service.get_all_instances(self.config)\n aws_service.change_ec2_state(instances, 'running', self.log)\n\n\n def search(self, search_name):\n instance = aws_service.get_instance_by_name(\"attack-range-splunk-server\",self.config)\n if instance['State']['Name'] == 'running':\n splunk_sdk.search(instance['NetworkInterfaces'][0]['Association']['PublicIp'],str(self.config['splunk_admin_password']), search_name, self.log)\n else:\n self.log.error('ERROR: Splunk server is not running.')\n\n\n def simulate(self, target, simulation_techniques):\n target_public_ip = aws_service.get_single_instance_public_ip(target, self.config)\n if target == 'attack-range-windows-client':\n runner = ansible_runner.run(private_data_dir='.attack_range/',\n cmdline=str('-i ' + target_public_ip + ', '),\n roles_path=\"../ansible/roles\",\n playbook='../ansible/playbooks/atomic_red_team.yml',\n extravars={'art_run_techniques': simulation_techniques, 'ansible_user': 'Administrator', 'ansible_password': self.config['win_password'], 'ansible_port': 5985, 'ansible_winrm_scheme': 'http'},\n verbosity=0)\n else:\n runner = ansible_runner.run(private_data_dir='.attack_range/',\n cmdline=str('-i ' + target_public_ip + ', '),\n roles_path=\"../ansible/roles\",\n playbook='../ansible/playbooks/atomic_red_team.yml',\n extravars={'art_run_techniques': simulation_techniques, 'ansible_user': 'Administrator', 'ansible_password': self.config['win_password']},\n verbosity=0)\n\n if runner.status == \"successful\":\n self.log.info(\"successfully executed technique ID {0} against target: {1}\".format(simulation_techniques, target))\n else:\n self.log.error(\"failed to executed technique ID {0} against target: {1}\".format(simulation_techniques, target))\n sys.exit(1)\n\n\n def list_machines(self):\n instances = aws_service.get_all_instances(self.config)\n response = []\n instances_running = False\n for instance in instances:\n if instance['State']['Name'] == 'running':\n instances_running = True\n response.append([instance['Tags'][0]['Value'], instance['State']['Name'], instance['NetworkInterfaces'][0]['Association']['PublicIp']])\n else:\n response.append([instance['Tags'][0]['Value'], instance['State']['Name']])\n print()\n print('Terraform Status\\n')\n if len(response) > 0:\n if instances_running:\n print(tabulate(response, headers=['Name','Status', 'IP Address']))\n else:\n print(tabulate(response, headers=['Name','Status']))\n else:\n print(\"ERROR: Can't find configured EC2 Attack Range Instances in AWS.\")\n sys.exit(1)\n print()\n\n\n def list_searches(self):\n instance = aws_service.get_instance_by_name(\"attack-range-splunk-server\",self.config)\n if instance['State']['Name'] == 'running':\n response = splunk_sdk.list_searches(instance['NetworkInterfaces'][0]['Association']['PublicIp'],str(self.config['splunk_admin_password']))\n if len(response) > 0:\n objects = []\n for object in response:\n objects.append([object.name])\n print()\n print('Available savedsearches in Splunk\\n')\n print(tabulate(objects, headers=['Name']))\n print()\n else:\n log.error('ERROR: Splunk server is not running.')\n","sub_path":"modules/TerraformController.py","file_name":"TerraformController.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"257782960","text":"# Solving a Large Linear System\n\nimport numpy\n\n# Set a random seed so the code below is reproducible\nnumpy.random.seed(1)\n\n# Create A and b matrices with random\nA = 10*numpy.random.rand(10,10)-5\nb = 10*numpy.random.rand(10)-5\n\n# Solve Ax = b\nsolution = numpy.linalg.solve(A,b)\nprint(solution)\n\n# To verify the solution works, show Ax - b is near 0\nsum(abs(numpy.dot(A,solution) - b))","sub_path":"Chapter 7/SolvingALargeLinearSystem.py","file_name":"SolvingALargeLinearSystem.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"653716600","text":"from twitter import OAuth, Twitter\nfrom datetime import datetime\n\n\ndef parse_date(_date):\n \"\"\"\n responseに含まれる日付をdatetimeに変換\n :param _date:a string of date\n :return:\n \"\"\"\n return datetime.strptime(_date, '%a %b %d %H:%M:%S %z %Y')\n\n\nclass TimelineHelper:\n def __init__(self, twitter):\n self.twitter = twitter\n\n def get_latest_tweet(self, screen_name=None):\n if not screen_name:\n screen_name = self.twitter.account.settings()['screen_name']\n return self.twitter.statuses.user_timeline(screen_name=screen_name, count=1)[0]\n\n def get_latest_id(self, screen_name=None):\n return self.get_latest_tweet(screen_name)['id']\n\n def next_mention(self, since_id=1, max_id=None):\n \"\"\"\n mentionの取得\n :param since_id:このidより大きいidのmentionを取得\n :param max_id: 取得対象idの最大値\n :return:\n \"\"\"\n if not max_id:\n max_id = self.get_latest_id()\n\n return self.__next_tweet(self.twitter.statuses.mentions_timeline, max_id, since_id=since_id)\n\n def next_tweet(self, screen_name=None, since_id=1, max_id=None):\n \"\"\"\n timelineの取得\n :param screen_name:指定ユーザーのtimelineを取得. 指定なしの場合, ログインアカウントのタイムラインを取得する\n :param since_id:このidより大きいidのツイートを取得\n :param max_id: 取得対象idの最大値\n :return:最新のツイートから降順に返却\n \"\"\"\n if not max_id:\n max_id = self.get_latest_id(screen_name)\n\n if not screen_name:\n screen_name = self.twitter.account.settings()['screen_name']\n return self.__next_tweet(self.twitter.statuses.user_timeline, max_id, screen_name=screen_name,\n since_id=since_id)\n\n def __next_tweet(self, timeline_api, max_id, **params):\n \"\"\"\n timelineを取得し、1件ごとyieldする\n :param timeline_api:ex. home_timeline / mention_timeline\n :param max_id:max_id\n :param params:max_id以外のapiパラメータ\n :return:a tweet object\n \"\"\"\n count = 200\n while True:\n tweets = timeline_api(max_id=max_id, count=count, **params)\n for tweet in tweets:\n yield tweet\n\n if len(tweets) < count:\n break\n max_id = tweets[-1]['id'] - 1\n\n\nif __name__ == \"__main__\":\n import os\n import settings\n\n settings.init_env()\n\n consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')\n consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')\n oauth_token = os.environ.get('TWITTER_OAUTH_TOKEN')\n oauth_secret = os.environ.get('TWITTER_OAUTH_SECRET')\n\n t = Twitter(auth=OAuth(\n oauth_token, oauth_secret, consumer_key, consumer_secret))\n helper = TimelineHelper(t)\n for tweet in helper.next_tweet(since_id=825000136252682240):\n print(tweet['text'])\n for tweet in helper.next_mention(since_id=709043705114570753):\n print(tweet['text'], tweet['id'])\n","sub_path":"twitterhelper.py","file_name":"twitterhelper.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"156359175","text":"#run directly in python 3.6 (install html2text via pip)\n\nimport pyodbc\nimport re\n\ndef left(s, amount):\n return s[:amount]\n\ndef right(s, amount):\n return s[-amount:]\n\ndef mid(s, offset, amount):\n return s[offset:offset+amount]\n\ndef isvalid_line(line):\n line=line.strip()\n\n #minimum length criteria\n if len(line)<=10:\n return 0\n #** email headers #! Links #- Line breaks #\\ Line breaks (orginal message)\n if left(line,2)=='**' or left(line,1)=='!' or left(line,1)=='-' or left(line,1)=='\\\\' or left(line,1)=='//':\n return 0\n \n #EMAIL HEADERS\n invalid_prefixes=['EMAIL:','E:','E-MAIL:','FROM:','TO:','CC:','SENT:','SUBJECT:','PHONE:','PH','OFFICE:','MOBILE:','TEL:','TEL','FAX:','DATE:','FROM:**','SENT:**','TO:**','SUBJECT:**','IMPORTANCE:','IMPORTANCE:**','RECEIVED:','RECEIVED:**']\n start_token=line.split(' ',1)[0]\n if start_token.upper() in invalid_prefixes:\n return 0\n \n #HTTP addresses\n if left(line,4).upper()=='HTTP':\n return 0\n\n #single word as a line\n if line.count(' ')<2:\n return 0\n\n #detecting semicolons for addresses in TO/CC line\n if line.count(';')>=2:\n return 0\n \n return 1\n\n\ncon=pyodbc.connect('DRIVER={SQL Server};Server=kach_saw;Database=WORKAREA;Trusted_Connection=yes;')\ncur=con.cursor()\n\nqry=\"SELECT [description] phrase FROM [WORKAREA].[MST].[t_StopPhrases] where isstopphrase=1\"\ncur.execute(qry)\nStopPhrases=cur.fetchall()\nStopPhrasesList=[row.phrase for row in StopPhrases]\n\nqry=\"SELECT ID,DESCRIPTION_CLEANED_EN TEXT FROM MST.t_SampleDES\" \ncur.execute(qry)\nrows=cur.fetchall()\n\nbatch=1\ncnt=0\nfor row in rows:\n cleanedtxt=\"\"\n for line in row.TEXT.splitlines():\n line=line.strip()\n if isvalid_line(line): #print(isvalid_line(line),'-',line)\n if line not in StopPhrasesList: \n cleanedtxt=cleanedtxt+line+\"\\n\"\n\n cur.execute(\"UPDATE [MST].[t_SampleDES] SET [description_cleaned_en_stopwords]=? WHERE ID=?\",(cleanedtxt,row.ID))\n cnt+=1\n if cnt%100==0:\n print(batch)\n con.commit()\n cnt=0\n batch+=1\n \ncon.commit()\ncon.close()\n\n\n## if isvalid_line(line):\n## print('-',line)\n## cur.execute(\"UPDATE [MST].[t_Sample] SET DESCRIPTION_CLEANED=? WHERE ID=?\",(cleansed,row.ID))\n\n\n##output=\"\".join(line.strip() for line in output.splitlines())\n\n##print(output)\n\n##for line in output.splitlines():\n## line=line.strip()\n##\n## #to eliminate disclaimer, instructions at the bottom of email\n## #if line=='* * *':\n## # break\n## print(line)\n","sub_path":"NLP_Normalization/Clear_Description_MSTRAVEL.py","file_name":"Clear_Description_MSTRAVEL.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"632500406","text":"# -*- coding: utf-8 -*-\n\"\"\"Sirepo setup script\n\n:copyright: Copyright (c) 2015-2023 RadiaSoft LLC. All Rights Reserved.\n:license: http://www.apache.org/licenses/LICENSE-2.0.html\n\"\"\"\nimport os\nimport pykern.pksetup\n\ninstall_requires = [\n \"Flask==2.0.3\",\n \"SQLAlchemy>=1.4,<2\",\n \"aenum\",\n \"asyncssh\",\n \"cryptography>=2.8\",\n \"futures\",\n \"matplotlib\",\n \"numconv\",\n \"numpy\",\n \"Pillow\",\n \"pyIsEmail\",\n \"pykern\",\n \"pytz\",\n \"requests\",\n \"tornado\",\n \"user-agents\",\n \"werkzeug==2.0.3\",\n # Optional dependencies\n # required for email login and smtp\n \"Authlib>=0.13\",\n \"dnspython\",\n # required for sbatch agent\n \"asyncssh\",\n]\nif not os.environ.get(\"no_uwsgi\", 0):\n # had a problem installing in one environment so make optional\n install_requires.append(\"uwsgi\")\n\npykern.pksetup.setup(\n author=\"RadiaSoft LLC.\",\n author_email=\"pip@sirepo.com\",\n description=\"accelerator code gui\",\n install_requires=install_requires,\n license=\"http://www.apache.org/licenses/LICENSE-2.0.html\",\n name=\"sirepo\",\n url=\"http://sirepo.com\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Web Environment\",\n \"Framework :: Flask\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Natural Language :: English\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: JavaScript\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"Topic :: Scientific/Engineering :: Physics\",\n \"Topic :: Software Development :: Libraries :: Application Frameworks\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87941818","text":"from random import randint\nfrom graphviz import Digraph\nimport seaborn as sns\n\nclass RefGraphBuilder():\n\n def __init__(self):\n pass\n\n def referencepath(self,refpath):\n self.refpath = refpath\n p = Digraph(name='REFERENCE', node_attr={'shape': 'cds', 'color': 'black', 'fillcolor': 'grey', 'fixedsize':'true'}, format='png',graph_attr={'splines': 'spline', 'rankdir': 'LR'},engine='dot',edge_attr={'arrowhead': 'vee', 'arrowsize': '0.5', 'color': 'black','penwidth':'2'})\n nw = 0\n nodedata = {}\n for i in range(1, len(self.refpath) - 1): # Has to start at one, else loopback in graph\n nw = (int(refpath[i+1][1]) - int(refpath[i][1])) / 10\n if nw < 1.2:\n nw = 1.2\n ##### Return a dictionary of node attr to work with - interactive plotting\n nodedata[str(self.refpath[i - 1][1] + self.refpath[i - 1][2])] = [\"label\", str(self.refpath[i - 1][0] + ' ' + self.refpath[i - 1][1] + ' ' + self.refpath[i - 1][2]), \"width\", str(nw)]\n #####\n p.node(self.refpath[i - 1][1] + self.refpath[i - 1][2],label=str(self.refpath[i - 1][0] + ' ' + self.refpath[i - 1][1] + ' ' + self.refpath[i - 1][2]), width = str(nw))\n #### NEED TO ADD FOR EDGES AS WELL\n p.edge(self.refpath[i - 1][1] + self.refpath[i - 1][2], self.refpath[i][1] + self.refpath[i][2])\n\n p.node(self.refpath[len(self.refpath) - 1][1] + self.refpath[len(self.refpath) - 1][2],label=str(self.refpath[len(self.refpath) - 1][0] + ' ' + self.refpath[len(self.refpath) - 1][1] + ' ' + self.refpath[len(self.refpath) - 1][2]))\n p.node(self.refpath[len(self.refpath) - 2][1] + self.refpath[len(self.refpath) - 2][2],label=str(self.refpath[len(self.refpath) - 2][0] + ' ' + self.refpath[len(self.refpath) - 2][1] + ' ' + self.refpath[len(self.refpath) - 2][2]))\n p.edge(self.refpath[len(self.refpath) - 2][1] + self.refpath[len(self.refpath) - 2][2],\n self.refpath[len(self.refpath) - 1][1] + self.refpath[len(self.refpath) - 1][2])\n\n p.node(str('REF'), label=str('Reference'), width = '1.6')\n p.node(str('REF_'), label=str('Path'))\n p.edge('REF', 'REF_')\n\n #print(nodedata)\n return p, nodedata;\n\n def variantpath(self, output,graph,loci,refpath):\n\n self.output = output\n self.graph = graph\n self.loci =loci\n self.refpath = refpath\n\n colour = sns.color_palette(\"colorblind\", desat=.5) + sns.color_palette(\"Set1\", n_colors=8, desat=.5)\n del colour[7:9]\n colour = sns.color_palette(colour)\n colour = colour.as_hex()\n\n ## newvar\n allvar = {}\n testref = [list(elem) for elem in refpath]\n ## newvar\n\n for key in self.output:\n varpath = ()\n for i in self.output[key]:\n if i[0] == self.loci[0] and int(i[1]) >= self.loci[1] and int(i[1]) <= self.loci[2]:\n varpath = sorted(\n tuple(varpath) + (([i[0], i[1], i[3]]),)) # have to convert to int for sort - see refpath\n varpath = sorted(varpath, key=lambda x: int(x[1]))\n ## newvar\n nw = 0\n temp = []\n matching = []\n ## newvar\n\n x = Digraph(name=key, node_attr={'shape': 'cds', 'color': colour[randint(0, len(colour) - 1)],'fillcolor': colour[randint(0, len(colour) - 1)]} , engine='dot',edge_attr={'arrowhead': 'vee', 'arrowsize': '0.5', 'color': colour[randint(0, len(colour) - 1)],'penwidth':'4'}) # colour can also be set to use x11 names 'red'\n\n for i in range(1, len(varpath) - 1):\n # if output[key][i][0] == loci[0] and int(output[key][i][1]) >= loci[1] and int(output[key][i][1]) <= loci[2]:\n\n nw = (int(varpath[i+1][1]) - int(varpath[i][1])) / 10\n if nw < 1.2: # have to include a maximum node size as well\n nw = 1.2\n if varpath[i - 1] in testref:\n x.node(varpath[i - 1][1] + varpath[i - 1][2],label=str(varpath[i - 1][0] + ' ' + varpath[i - 1][1] + ' ' + varpath[i - 1][2]), width=str(nw))\n matching = list(filter(lambda k: varpath[i] in allvar[k], allvar.keys()))\n if matching: # exit pathways to a reference node\n matching.append(key)\n x.edge(varpath[i - 1][1] + varpath[i - 1][2], varpath[i][1] + varpath[i][2], label=str(' - '.join(matching)), color='black', style='dotted')\n matching = []\n else:\n x.edge(varpath[i - 1][1] + varpath[i - 1][2], varpath[i][1] + varpath[i][2], label=str(key))\n\n else:\n x.node(varpath[i - 1][1] + varpath[i - 1][2],label=str(varpath[i - 1][0] + ' ' + varpath[i - 1][1] + ' ' + varpath[i - 1][2]),width=str(nw))\n matching = list(filter(lambda k: varpath[i] in allvar[k], allvar.keys()))\n if matching: ####################\n matching.append(key)\n\n x.edge(varpath[i - 1][1] + varpath[i - 1][2], varpath[i][1] + varpath[i][2],label=str(' - '.join(matching)), color='black', style='dotted')\n matching = []\n else:\n x.edge(varpath[i - 1][1] + varpath[i - 1][2], varpath[i][1] + varpath[i][2], label=str(key))\n\n\n x.node(varpath[len(varpath) - 1][1] + varpath[len(varpath) - 1][2], label=str(varpath[len(varpath) - 1][0] + ' ' + varpath[len(varpath) - 1][1] + ' ' + varpath[len(varpath) - 1][2]))\n x.node(varpath[len(varpath) - 2][1] + varpath[len(varpath) - 2][2], label=str(varpath[len(varpath) - 2][0] + ' ' + varpath[len(varpath) - 2][1] + ' ' + varpath[len(varpath) - 2][2]))\n x.edge(varpath[len(varpath) - 2][1] + varpath[len(varpath) - 2][2],varpath[len(varpath) - 1][1] + varpath[len(varpath) - 1][2])\n\n x.node(str(key), label=str(key))\n x.node(str(key + '_'), label=str('Path'))\n x.edge(str(key), str(key + '_'))\n\n temp = [_ for _ in varpath if _[2] != 'REF']\n allvar[key] = temp\n\n self.graph.subgraph(x)\n return graph","sub_path":"Dyedot_variationGraphs/class_Grapher.py","file_name":"class_Grapher.py","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"219895430","text":"import requests\r\nimport json\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nimport urllib\r\nimport datetime\r\nimport random\r\nimport csv\r\nimport time\r\nfrom pymongo import MongoClient\r\nimport threading\r\n\r\n\"\"\"\r\n 该脚本主要是 爬取百度招聘网站上的招聘信息,并将数据存入MongoDB数据库。\r\n 主要内容:\r\n (省, 市, 区, 工程标题, 工程描述, 详细地址, 工种, 开工日期, 完工日期, 薪酬金额, 接包要求 , 发布状态, 发布日期)\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\n 数据库操作\r\n\"\"\"\r\nclient = MongoClient('localhost', 27017)\r\nbaidu = client.baidu\r\ncollection = baidu.work_1210\r\n\r\n\r\ndef save_to_mongodb(work_info):\r\n try:\r\n if collection.insert_one(work_info):\r\n print('记录成功!')\r\n except Exception:\r\n print('记录失败!')\r\n\r\n##########################################################\r\n\r\n\r\ndef get_proxy():\r\n \"\"\"\r\n 根据之前代理池系统,对外提供的web访问接口,从代理池获取代理\r\n \"\"\"\r\n try:\r\n get_proxy_utl = 'http://127.0.0.1:5000/random'\r\n res = requests.get(get_proxy_utl)\r\n if res.status_code == 200:\r\n print('从代理���中获取代理IP: %s' % res.text)\r\n proxies = {'http': 'http://' + res.text}\r\n return proxies\r\n else:\r\n return None\r\n except Exception as e:\r\n print('从代理池中获取代理IP出错了!! %s' % e)\r\n return None\r\n\r\n\r\n###########################################################\r\n\"\"\"\r\n 初始化变量\r\n\"\"\"\r\nua = ['Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',\r\n 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',\r\n 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko',\r\n 'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',\r\n 'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',\r\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)',\r\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)']\r\n\r\n\r\ndef crawl(job_type, city, province, token, cookie):\r\n headers = {\r\n 'Accept': '*/*',\r\n 'Cookie': cookie,\r\n 'Referer': 'https://zhaopin.baidu.com/',\r\n 'User-Agent': random.choice(ua)\r\n }\r\n\r\n pn = 0\r\n for i in range(10):\r\n\r\n try:\r\n url = 'https://zhaopin.baidu.com/api/qzasync?query=%s&city=%s&is_adq=1&pcmod=1&token=%s&pn=%d&rn=10' % (\r\n urllib.parse.quote(job_type), urllib.parse.quote(city).replace('%', '%25'), token, pn)\r\n\r\n # url = 'https://zhaopin.baidu.com/api/qzasync?query=%E6%96%87%E5%91%98&city=%25E6%25AD%25A6%25E6%25B1%2589&is_adq=1&pcmod=1&token=%3D%3DAmS3tqY%2BaoEqFbtxmabe5aspJaXt1Zqd2kYS5kst5l&pn=10&rn=10'\r\n print(url)\r\n\r\n # 获取代理IP\r\n proxies = get_proxy()\r\n print('代理ip:', proxies)\r\n if not proxies:\r\n res = requests.get(url, headers=headers)\r\n else:\r\n res = requests.get(url, headers=headers, proxies=proxies)\r\n\r\n pn += 10\r\n print(res.status_code)\r\n data = res.json()\r\n\r\n for disp_data in data['data']['disp_data']:\r\n url = disp_data.get('loc', '')\r\n district = disp_data.get('district', '') # 区县\r\n\r\n detail_url = 'https://zhaopin.baidu.com/szzw?id=%s' % url\r\n print(detail_url)\r\n\r\n try:\r\n if not proxies:\r\n detail_res = requests.get(detail_url)\r\n else:\r\n detail_res = requests.get(detail_url, proxies=proxies)\r\n print(detail_res.status_code)\r\n if detail_res.status_code != 200:\r\n continue\r\n html = detail_res.text\r\n\r\n company = '' # 公司名称\r\n title = '' # 标题\r\n job_desc = '' # 工作描述\r\n detail_address = '' # 详细地址\r\n release_time = str(datetime.datetime.now().strftime('%Y/%m/%d')) # 开工时间(当前时间)\r\n valid_time = '' # 有效时间\r\n salary = '' # 薪水\r\n public_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) # 发布时间(当前时间)\r\n\r\n try:\r\n company = re.compile(r'class=\"bd-tt\" data-a-39d218aa>(.*?)<').findall(html)[0]\r\n company = company.replace('class=\"bd-tt\" data-a-39d218aa>', '').replace('<', '')\r\n except:\r\n company = ''\r\n\r\n try:\r\n title = re.compile(r'class=\"job-name\">(.*?)职位描述:(.*?)').findall(html)[0]\r\n job_desc = job_desc.replace('', '').replace('

', '').replace('

', '').replace(\r\n '
', '')\r\n except Exception as e:\r\n print(e)\r\n try:\r\n job_desc = re.compile(r'>

工作内容:(.*?)

').findall(html)[0]\r\n job_desc = job_desc.replace('', '').replace('

', '').replace('

', '').replace(\r\n '
', '')\r\n except:\r\n job_desc = \"招%s,要熟练工\" % job_type\r\n\r\n try:\r\n detail_address = re.compile(r'工作地址:

(.*?)

', '').replace('

', '')\r\n except Exception as e:\r\n print(e)\r\n try:\r\n detail_address = re.compile(r'

工作地点:\\D{2,6}

').findall(html)[0]\r\n detail_address = detail_address.replace('

', '').replace('

', '')\r\n except:\r\n detail_address = \"%s市\" % city\r\n\r\n # try:\r\n # public_time = re.compile(r'

发布时间:(2018-\\d{2}-\\d{2}).*?

').findall(html)[0]\r\n # public_time = public_time.replace('

', '').replace('

', '')\r\n # except Exception as e:\r\n # public_time = str(datetime.datetime.now().strftime('%Y/%m/%d'))\r\n\r\n try:\r\n valid_time = re.compile(r'

有效日期:(.*?)

').findall(html)[0]\r\n valid_time = valid_time.replace('

', '').replace('

', '')\r\n except Exception as e:\r\n valid_time = str((datetime.date.today() + datetime.timedelta(days=+61)).strftime(\"%Y/%m/%d\"))\r\n\r\n try:\r\n salary = re.compile(r'(\\d{3,5})-(\\d{3,5})).\n#\n##############################################################################\n\nimport time\nfrom datetime import datetime\nfrom openerp.report import report_sxw\nimport math\n\n\nclass assets_details(report_sxw.rml_parse):\n \"\"\"\n assets details report\n \"\"\"\n _name = 'report.account.assets.detials'\n\n def __init__(self, cr, uid, name, context=None):\n \"\"\"\n initiation method\n \"\"\"\n self.counter = 0\n super(assets_details, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n 'lines': self.lines,\n 'category':self.get_name,\n 'depreciation':self.get_depreciation,\n })\n self.context = context\n def get_name(self):\n \"\"\"\n print category name\n \"\"\"\n name = self.categories_names[self.counter]\n #cuse this method will be called after get_depreciation\n self.counter+=1\n return name\n \n def get_depreciation(self):\n \"\"\"\n print category depreciation percent\n \"\"\"\n percent = self.depreciation_percent[self.counter]\n return percent\n def to_date(self, date):\n \"\"\"\n convert string to date \n \"\"\"\n return datetime.strptime(str(date), \"%Y-%m-%d\")\n\n def compute_assets(self, company_id, category_ids, date):\n \"\"\"\n compute details of assets\n category_ids:list of categories ids\n \"\"\"\n #wanted date\n wanted_date = datetime.strptime(str(date), \"%Y-%m-%d\")\n #wanted year\n year = wanted_date.year\n start_or_year = str(year)+\"-1-1\"\n start_date = datetime.strptime(str(start_or_year), \"%Y-%m-%d\")\n self.assets = {x:{} for x in category_ids}\n self.categories = {x:{} for x in category_ids}\n asset_obj = self.pool.get('account.asset.asset')\n search_ids = asset_obj.search(self.cr, self.uid, [('category_id','in',category_ids),\\\n ('company_id','=',company_id),\\\n ('purchase_date','>=',start_or_year),\\\n ('purchase_date','<=',date),\\\n ('state','!=','draft'),],context=self.context)\n for asset in asset_obj.browse(self.cr, self.uid, search_ids):\n self.categories[asset.category_id.id] = asset.category_id.name\n self.assets[asset.category_id.id][asset.name] = self.assets[asset.category_id.id].get(asset.name,{})\n self.assets[asset.category_id.id][asset.name]['name'] = asset.name\n self.assets[asset.category_id.id][asset.name]['date'] = asset.purchase_date\n #to get the current count if exist or set to zero\n self.assets[asset.category_id.id][asset.name]['count'] = self.assets[asset.category_id.id][asset.name].get('count',0)\n self.assets[asset.category_id.id][asset.name]['count'] += 1\n \n #get the current value of the asset\n value = sum(x.amount for x in asset.history_ids\\\n if (x.type in ['initial']\\\n and self.to_date(x.date) >= start_date\\\n and self.to_date(x.date) <= wanted_date))\n \n self.assets[asset.category_id.id][asset.name]['value'] = value\n #to get the current count if exist or set to zero\n self.assets[asset.category_id.id][asset.name]['sum_value'] = self.assets[asset.category_id.id][asset.name].get('sum_value',0.0)\n \n self.assets[asset.category_id.id][asset.name]['sum_value'] += value\n\n #get the current depreciation of the asset\n depreciation = sum(x.amount for x in asset.depreciation_line_ids\\\n if x.depreciation_date and\\\n (self.to_date(x.depreciation_date) >= start_date\\\n and self.to_date(x.depreciation_date) <= wanted_date))\n \n #to get the current count if exist or set to zero\n self.assets[asset.category_id.id][asset.name]['depreciation'] = self.assets[asset.category_id.id][asset.name].get('depreciation',0.0)\n self.assets[asset.category_id.id][asset.name]['depreciation'] += math.fabs(depreciation)\n\n current_sum = self.assets[asset.category_id.id][asset.name]['sum_value']\n current_depreciation = self.assets[asset.category_id.id][asset.name]['depreciation']\n self.assets[asset.category_id.id][asset.name]['rest_value'] = current_sum - current_depreciation\n \n self.assets_to_print = []\n #hold categories name to print operation\n \n \n self.categories_names = {}\n self.depreciation_percent = {}\n counter = 0\n for key in self.assets.keys():\n category_list = []\n name = self.categories[key]\n self.categories_names[counter] = name\n dic = self.assets[key]\n \n last_line = {'name':'اﻹجمالي', 'date':' ', 'count':' ',\\\n 'value':0, 'sum_value':0, 'depreciation':0, 'rest_value':0}\n for record in dic:\n last_line['value'] += self.assets[key][record]['value']\n last_line['sum_value'] += self.assets[key][record]['sum_value']\n last_line['depreciation'] += self.assets[key][record]['depreciation']\n last_line['rest_value'] += self.assets[key][record]['rest_value']\n category_list.append(self.assets[key][record])\n \n \n \n #to add the sumation line\n category_list.append(last_line)\n \n #to round the percent to 2 digits\n if last_line['depreciation'] and last_line['sum_value']:\n self.depreciation_percent[counter] = round(last_line['depreciation']/last_line['sum_value'], 2)\n \n self.assets_to_print.append(category_list)\n counter += 1\n\n\n def lines(self, data):\n \"\"\"\n return report lines\n \"\"\"\n company_id = data['form']['company_id']\n category_ids = data['form']['category_id']\n date = str(data['form']['date'])\n #get entered company_id or the defualt user company_id\n company_id = company_id and company_id[0] or\\\n self.pool.get('res.company')._company_default_get(self.cr, self.uid, 'account.asset.asset', context=self.context)\n\n self.compute_assets(company_id, category_ids, date)\n\n return self.assets_to_print\n\nreport_sxw.report_sxw('report.account.assets.details.report',\n 'account.asset.asset',\n 'addons/account_asset_custom/report/account_asset_details.rml',\n parser=assets_details,\n header='internal landscape')\n","sub_path":"v_7/Dongola/common/account_asset_custom/report/account_asset_details.py","file_name":"account_asset_details.py","file_ext":"py","file_size_in_byte":7086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"487021245","text":"#!/usr/bin/env python\nimport os\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nfrom membrane.membrane_ops import mops as model_fun\nfrom membrane.layers.feedforward import conv\nfrom membrane.layers.feedforward import normalization\n# from layers.feedforward import pooling\nfrom membrane.layers.recurrent import feedback_hgru\n\n\ndef experiment_params(\n train_name=None,\n test_name=None,\n train_shape=None,\n test_shape=None,\n affinity=12,\n gt_idx=1,\n z=18):\n \"\"\"Parameters for the experiment.\"\"\"\n if train_shape is None:\n train_shape = [0]\n exp = {\n 'lr': [1e-2],\n 'loss_function': ['cce'],\n 'optimizer': ['nadam'],\n 'training_routine': ['seung'],\n 'train_dataset': [train_name],\n 'test_dataset': [test_name],\n 'affinity': [affinity],\n 'cross_val': {'train': [0, 80], 'test': [80, 100]},\n 'gt_idx': [gt_idx], # Changes based on affinity\n 'train_input_shape': [z] + train_shape + [1],\n 'train_label_shape': [z] + train_shape + [affinity],\n 'test_input_shape': [z] + test_shape + [1],\n 'test_label_shape': [z] + test_shape + [affinity],\n 'train_stride': [1, 1, 1],\n 'test_stride': [1, 1, 1],\n 'tf_dtype': tf.float32,\n 'np_dtype': np.float32\n }\n exp['exp_label'] = __file__.split('.')[0].split(os.path.sep)[-1]\n exp['train_augmentations'] = [\n {'min_max_native_normalization': []},\n # {'normalize_volume': lambda x: x / 255.},\n # {'warp': {}},\n {'random_crop': []},\n {'pixel': {}},\n {'misalign': {}},\n {'blur': {}},\n {'missing': {}},\n {'flip_lr': []},\n {'flip_ud': []},\n ]\n exp['test_augmentations'] = [\n # {'normalize_volume': lambda x: x / 255.}\n {'min_max_native_normalization': []},\n {'random_crop': []},\n ]\n exp['train_batch_size'] = 1 # Train/val batch size.\n exp['test_batch_size'] = 1 # Train/val batch size.\n exp['top_test'] = 5 # Keep this many checkpoints/predictions\n exp['epochs'] = 100000\n exp['save_weights'] = False # True\n exp['test_iters'] = 1000\n exp['shuffle_test'] = False # Shuffle test data.\n exp['shuffle_train'] = True\n return exp\n\n\ndef build_model(data_tensor, reuse, training, output_channels):\n \"\"\"Create the hgru from Learning long-range...\"\"\"\n filters = [18]\n kernel_size = [1, 5, 5]\n with tf.variable_scope('cnn', reuse=reuse):\n # Unclear if we should include l0 in the down/upsample cascade\n with tf.variable_scope('in_embedding', reuse=reuse):\n in_emb = conv.conv3d_layer(\n bottom=data_tensor,\n name='l0',\n stride=[1, 1, 1],\n padding='SAME',\n num_filters=filters[0],\n kernel_size=[1, 5, 5],\n trainable=training,\n use_bias=True)\n in_emb = tf.nn.elu(in_emb)\n\n # hGRU down\n layer_hgru = feedback_hgru.hGRU(\n layer_name='hgru_1',\n x_shape=in_emb.get_shape().as_list(),\n timesteps=8,\n h_ext=[[1, 9, 9], [3, 5, 5], [1, 1, 1]],\n strides=[1, 1, 1, 1, 1],\n pool_strides=[1, 4, 4],\n padding='SAME',\n aux={\n 'symmetric_weights': True,\n 'dilations': [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]],\n 'batch_norm': True,\n 'pooling_kernel': [1, 4, 4],\n 'intermediate_ff': filters, # + filters,\n 'intermediate_ks': [kernel_size]},\n train=training)\n h2 = layer_hgru.build(in_emb)\n nh2 = normalization.batch(\n bottom=h2,\n name='hgru_bn',\n fused=True,\n renorm=True,\n training=training)\n with tf.variable_scope('out_embedding', reuse=reuse):\n out_emb = conv.conv3d_layer(\n bottom=nh2,\n name='out_emb',\n stride=[1, 1, 1],\n padding='SAME',\n num_filters=output_channels,\n kernel_size=kernel_size,\n trainable=training,\n use_bias=True)\n return out_emb\n\n\ndef main(\n train=None,\n test=None,\n row_id=None,\n gpu_device='/gpu:0',\n evaluate=False,\n checkpoint=None,\n full_volume=False,\n force_meta=None,\n full_eval=False,\n bethge=None,\n adabn=False,\n test_input_shape=False,\n test_label_shape=False,\n overwrite_training_params=False,\n z=18):\n \"\"\"Run an experiment with hGRUs.\"\"\"\n version = '3d'\n tf_records = False\n if evaluate:\n return model_fun.evaluate_model(\n test=test,\n gpu_device=gpu_device,\n z=z,\n version=version,\n build_model=build_model,\n experiment_params=experiment_params,\n checkpoint=checkpoint,\n force_meta=force_meta,\n full_volume=full_volume,\n full_eval=full_eval,\n test_input_shape=test_input_shape,\n test_label_shape=test_label_shape,\n adabn=adabn,\n bethge=bethge,\n tf_records=tf_records)\n else:\n raise NotImplementedError\n","sub_path":"membrane/models/fgru.py","file_name":"fgru.py","file_ext":"py","file_size_in_byte":5361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"373557464","text":"from fastapi import FastAPI, Path, Query\nfrom pydantic import BaseModel, Field\nfrom starlette.responses import JSONResponse\n\napp = FastAPI()\n\n\n@app.get(\"/profile/{name}\")\ndef get_path_parameter(name: str = Path(\"\", max_length=10)):\n return JSONResponse(\n content={\"message\": f\"My name is: {name}\"},\n status_code=200,\n )\n\n\ndefault_string = \"\"\ndefault_int = 0\n\n\nclass Books(BaseModel):\n name: str = Field(default_string, title=\"Book name\", max_length=300)\n page: int = Field(default_int, title=\"Page in book\", max_length=300)\n\n\n@app.post(\"/books\")\ndef create_books(req_body: Books):\n mock_response = {\n \"_id\": 4,\n \"name\": req_body.name,\n \"page\": req_body.page,\n }\n return JSONResponse(\n content={\"status\": \"ok\", \"data\": mock_response}, status_code=201\n )","sub_path":"add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610608629","text":"\n# compute dataframes d1 (Article, Brand, MC) and d2 (MC, Dept,SubDept,Class,SubClass)\n# compute d3 from primary hierarchy file (MC, Dept,SubDept,Class,SubClass) \n# concat d2 and d3 on MC column with precedence to primary hierarchy file as d4\n# merge d1 with d4 on MC( getting (Article,Brand,MC,Dept,SubDept,Class,SubClass))\n\nimport pandas as pd\nimport sys\n \nlist_df=[]\nkeep_cols = [\"Article\", \"ArticleDesc\",\"BrandDescription\",\"BrandCode\", \"MerCategory\",\"MCDescription\",\"Dept\",\"DeptDescription\",\"SubDeptDescription\",\"SubDept\", \"Class\",\"ClassDescription\",\"SubClass\",\"SubClassDescription\"]\n\n\n# read each CSV file into individual dataframe (df_each) and concat them as single df\nfor arg in sys.argv:\n\n\tif(not(\".csv\" in arg)):\n\t\tcontinue;\n\n\tprint (\"processing...\" + arg)\n\n\t#concatenate df in every iteration of for loop\n\tdf_each = pd.read_csv(arg, thousands=',' )\n\tdf_each = df_each[keep_cols]\n \n\tprint(df_each.head()) \n\tlist_df.append(df_each)\n\n \ndf = pd.concat(list_df)\n \n# filter articles beginning with A \nfilter_criteria = df['Article'].str.contains('^A', na=False)\ndf = df[filter_criteria ] \n\n\ndf_all = df.groupby(['Article']).last() \ndf_all = df_all.reset_index() \nprint(df_all.head())\n\n\n\n# retain and rename necessary columns \nkeep_cols = [\"Article\", \"ArticleDesc\",\"BrandDescription\",\"BrandCode\", \"MerCategory\"]\ndf = df_all[keep_cols] \n\ndf.rename(columns={'ArticleDesc':'Article_Desc'}, inplace=True)\ndf.rename(columns={'BrandDescription':'Brand_Desc'}, inplace=True)\ndf.rename(columns={'MerCategory':'MC'}, inplace=True)\n\ndf.to_csv(\"article_brand_mc.csv\", index=True)\n\n\n\n\n\n#read primary hierarchy file and remove duplicates\n\n\ndf_hier1 = pd.read_csv(\"hierarchy_conv.csv\")\n#article_cols = [\"MC\"] #columns to consider for removing duplicates\ndf_hier1.drop_duplicates([\"MC\"])\ndf_hier1 = df_hier1.reindex()\nkeep_cols = [\"MC\",\"MC Des\",\"Dept\",\"Dept Des\",\"Sub Dept\",\"Sub Dept Des\",\"Class\",\"Class Des\",\"Sub Class\",\"Sub Class Des\"]\ndf_hier1 = df_hier1[keep_cols]\ndf_hier1.to_csv(\"hierarchy_uniq.csv\")\n\n\n# secondary hierarchy from sales data files \n\nkeep_cols = [\"MerCategory\",\"MCDescription\",\"Dept\",\"DeptDescription\",\"SubDept\",\"SubDeptDescription\",\"Class\",\"ClassDescription\",\"SubClass\",\"SubClassDescription\"]\ndf_hier2 = df_all[keep_cols]\nprint(df_hier2.head())\ndf_hier2.rename(columns={'MerCategory':'MC'}, inplace=True)\ndf_hier2.rename(columns={'MCDescription':'MC Des'}, inplace=True)\ndf_hier2.rename(columns={'DeptDescription':'Dept Des'}, inplace=True)\ndf_hier2.rename(columns={'SubDept':'Sub Dept'}, inplace=True)\ndf_hier2.rename(columns={'SubDeptDescription':'Sub Dept Des'}, inplace=True)\ndf_hier2.rename(columns={'ClassDescription':'Class Des'}, inplace=True)\ndf_hier2.rename(columns={'SubClass':'Sub Class'}, inplace=True)\ndf_hier2.rename(columns={'SubClassDescription':'Sub Class Des'}, inplace=True)\n\n\n#sdf_hier2.columns = [\"MC\",\"MC Des\",\"Dept\",\"Dept Des\",\"Sub Dept\",\"Sub Dept Des\",\"Class\",\"Class Des\",\"Sub Class\",\"Sub Class Des\"]\n\narticle_cols = [\"MC\"] #columns to consider for removing duplicates\ngrouped = df_hier2.groupby(article_cols)\nindex = [gp_keys[0] for gp_keys in grouped.groups.values()]\ndf_hier2 = \tdf_hier2.reindex(index)\ndf_hier2.to_csv(\"hierarchy_sec.csv\")\n\n#combine both hierarchies, giving priority to primary hierarchy (using keep=first parameter)\n\ndf_hier1.reset_index(drop=True, inplace=True)\ndf_hier2.reset_index(drop=True, inplace=True)\n\nhier_all = pd.concat([df_hier1,df_hier2])\n\nhier_all.drop_duplicates(subset=[\"MC\"],keep='first',inplace=True)\nhier_all = hier_all.reindex()\nhier_all.to_csv(\"hier_all.csv\")","sub_path":"hierarchy_details.py","file_name":"hierarchy_details.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"144750703","text":"import scrublet as scr\nimport scipy.io\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\n\nplt.rcParams['font.family'] = 'sans-serif'\nplt.rcParams['font.sans-serif'] = 'Arial'\nplt.rc('font', size=14)\nplt.rcParams['pdf.fonttype'] = 42\n\ntag = 'SmartSeq'\noutput_dir = '/home/jovyan/HB_ZIK/scrublet'\ninput_dir = '/home/jovyan/data/ZikaGlioblastomas'\ninput_file = '/home/jovyan/data/HB_ZIK/HB_ZIK/study5953-zika-star-genecounts.txt'\ncounts_matrix = pd.read_csv(input_file, sep='\\t')\ncounts_matrix = counts_matrix.iloc[0:-4,:]\ngenes = counts_matrix.iloc[:,0]\ncounts_matrix = counts_matrix.iloc[:,1:]\ncounts_matrix = np.asarray(counts_matrix)\ncounts_matrix = counts_matrix.transpose()\n\nprint('Counts matrix shape: {} rows, {} columns'.format(counts_matrix.shape[0], counts_matrix.shape[1]))\nprint('Number of genes in gene list: {}'.format(len(genes)))\n\nscrub = scr.Scrublet(counts_matrix, expected_doublet_rate=0.06, sim_doublet_ratio = 10)\ndoublet_scores, predicted_doublets = scrub.scrub_doublets(min_counts=2, \n min_cells=3, \n min_gene_variability_pctl=85, \n n_prin_comps=30)\n\npredicted_doublets = predicted_doublets*1\npredicted_doublets = predicted_doublets.astype(int)\ndetected_doublets_rate = round(scrub.detected_doublet_rate_, 4)\noverall_doublets_rate = round(scrub.overall_doublet_rate_, 4)\n\nnp.savetxt(output_dir + '/' + tag + '_' + 'doublets_scores.txt', doublet_scores) \nnp.savetxt(output_dir + '/' + tag + '_' + 'predicted_doublets.txt', predicted_doublets) \nwith open(output_dir + '/' + tag + '_' + 'detected_doublets_rate.txt', 'w') as f:\n f.write('%f' % detected_doublets_rate) \n\nwith open(output_dir + '/' + tag + '_' + 'overall_doublets_rate.txt', 'w') as f:\n f.write('%f' % overall_doublets_rate)\n\nf = scrub.plot_histogram()\nf[0].savefig(output_dir + '/' + tag + '_' + \"doubletScore_histogram.pdf\", bbox_inches='tight')\n","sub_path":"scrublet/.ipynb_checkpoints/removeDoublets_SmartSeq-checkpoint.py","file_name":"removeDoublets_SmartSeq-checkpoint.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88778545","text":"from math import *\n\nworkdir='/Users/colin/workspace/scratch/spectralLES' # not a problem arg\n\npid = 'test_N64_K30_spectral' # problem ID\nodir = '%s/HIT_LES/%s/' % (workdir, pid) # output folder\nidir = odir # input folder for restarts\nL = 2.*pi # domain size\nN = 64 # linear grid size\ncfl = 0.33 # CFL no.\ntlimit = 12.*pi # Time Limit ~ 20tau\ntau = 0.5*pi # ~ integral turnover time\ndt_rst = 5.0*tau # restart output rate\ndt_bin = 1.0*tau # snapshot output rate\ndt_hst = 0.2*tau # histogram output rate\ndt_spec = 0.1*tau # spectrum output rate\nnu = 0.0011 # kinematic viscosity\neps_inj = 1.2 # energy injection rate (cell avg.)\nUrms = 3.0 # initial rms velocity\nk_exp = -1.0 # initial spectrum power law\nk_peak = 16 # initial spectrum decay scaling\n\n\"\"\"\nFor simulations at 256^3:\ndx/eta = 1 -> nu = 0.0071 (DNS for 2nd-3rd order statistics)\ndx/eta = 2 -> nu = 0.0028 (DNS for at best 2nd-order statistics)\ndx/eta = 4 -> nu = 0.0011 (well-resolved LES)\neps_inj = 1.2\nk_peak = 0-64 (depending on how much small-scale energy you'd like in IC)\n\n\nEverything else stays the same.\n\nEquivalence at 64^3: dx/eta = 4, 8, and 16\n\"\"\"\n","sub_path":"parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"416778886","text":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utility functions to build input_fns for use with tf.Learn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\n\nimport tensorflow as tf\nfrom tensorflow_transform.saved import saved_transform_io\nfrom tensorflow_transform.tf_metadata import dataset_schema\n\nfrom tensorflow.contrib.learn.python.learn.utils import input_fn_utils\n\n\ndef _convert_scalars_to_vectors(features):\n \"\"\"Vectorize scalar columns to meet FeatureColumns input requirements.\"\"\"\n def maybe_expand_dims(tensor):\n # Ignore the SparseTensor case. In principle it's possible to have a\n # rank-1 SparseTensor that needs to be expanded, but this is very\n # unlikely.\n if isinstance(tensor, tf.Tensor) and tensor.get_shape().ndims == 1:\n tensor = tf.expand_dims(tensor, -1)\n return tensor\n\n return {name: maybe_expand_dims(tensor)\n for name, tensor in six.iteritems(features)}\n\n\ndef build_csv_transforming_serving_input_fn(\n raw_metadata,\n transform_savedmodel_dir,\n raw_keys,\n field_delim=\",\",\n convert_scalars_to_vectors=True):\n \"\"\"Creates input_fn that applies transforms to raw data in csv format.\n\n CSV files have many restrictions and are not suitable for every input source.\n Consider using build_parsing_transforming_serving_input_fn (which is good for\n input sources of tensorflow records containing tf.example) or\n build_default_transforming_serving_input_fn (which is good for input sources\n like json that list each input tensor).\n\n CSV input sources have the following restrictions:\n * Only columns with schema tf.FixedLenFeature colums are supported\n * Text columns containing the delimiter must be wrapped in '\"'\n * If a string contains a double quote, the double quote must be escaped with\n another double quote, for example: the first column in\n '\"quick \"\"brown\"\" fox\",1,2' becomes 'quick \"brown\" fox'\n * White space is kept. So a text column \"label ,\" is parsed to 'label '\n\n Args:\n raw_metadata: a `DatasetMetadata` object describing the raw data.\n transform_savedmodel_dir: a SavedModel directory produced by tf.Transform\n embodying a transformation function to be applied to incoming raw data.\n raw_keys: A list of string keys of the raw labels to be used. The order in\n the list matches the parsing order in the csv file.\n field_delim: Delimiter to separate fields in a record.\n convert_scalars_to_vectors: Boolean specifying whether this input_fn should\n convert scalars into 1-d vectors. This is necessary if the inputs will be\n used with `FeatureColumn`s as `FeatureColumn`s cannot accept scalar\n inputs. Default: True.\n\n Raises:\n ValueError: if columns cannot be saved in a csv file.\n\n Returns:\n An input_fn suitable for serving that applies transforms to raw data in\n CSV format.\n \"\"\"\n if not raw_keys:\n raise ValueError(\"raw_keys must be set.\")\n\n column_schemas = raw_metadata.schema.column_schemas\n\n # Check for errors.\n for k in raw_keys:\n if k not in column_schemas:\n raise ValueError(\"Key %s does not exist in the schema\" % k)\n if not isinstance(column_schemas[k].representation,\n dataset_schema.FixedColumnRepresentation):\n raise ValueError((\"CSV files can only support tensors of fixed size\"\n \"which %s is not.\") % k)\n shape = column_schemas[k].tf_shape().as_list()\n if shape and shape != [1]:\n # Column is not a scalar-like value. shape == [] or [1] is ok.\n raise ValueError((\"CSV files can only support features that are scalars \"\n \"having shape []. %s has shape %s\")\n % (k, shape))\n\n def default_transforming_serving_input_fn():\n \"\"\"Serving input_fn that applies transforms to raw data in Tensors.\"\"\"\n\n record_defaults = []\n for k in raw_keys:\n if column_schemas[k].representation.default_value is not None:\n # Note that 0 and '' are valid defaults.\n value = tf.constant([column_schemas[k].representation.default_value],\n dtype=column_schemas[k].domain.dtype)\n else:\n value = tf.constant([], dtype=column_schemas[k].domain.dtype)\n record_defaults.append(value)\n\n placeholder = tf.placeholder(dtype=tf.string, shape=(None,),\n name=\"csv_input_placeholder\")\n parsed_tensors = tf.decode_csv(placeholder, record_defaults,\n field_delim=field_delim)\n\n raw_serving_features = {k: v for k, v in zip(raw_keys, parsed_tensors)}\n\n _, transformed_features = (\n saved_transform_io.partially_apply_saved_transform(\n transform_savedmodel_dir, raw_serving_features))\n\n if convert_scalars_to_vectors:\n transformed_features = _convert_scalars_to_vectors(transformed_features)\n\n return input_fn_utils.InputFnOps(\n transformed_features, None, {\"csv_example\": placeholder})\n\n return default_transforming_serving_input_fn\n\n\ndef build_json_example_transforming_serving_input_fn(\n raw_metadata,\n transform_savedmodel_dir,\n raw_label_keys,\n raw_feature_keys=None,\n convert_scalars_to_vectors=True):\n \"\"\"Creates input_fn that applies transforms to raw data formatted in json.\n\n The json is formatted as tf.examples. For example, one input row could contain\n the string for\n\n {\"features\": {\"feature\": {\"name\": {\"int64List\": {\"value\": [42]}}}}}\n\n which encodes an example containing only feature column 'name' with value 42.\n\n Args:\n raw_metadata: a `DatasetMetadata` object describing the raw data.\n transform_savedmodel_dir: a SavedModel directory produced by tf.Transform\n embodying a transformation function to be applied to incoming raw data.\n raw_label_keys: A list of string keys of the raw labels to be used. These\n labels are removed from the serving graph. To build a serving function\n that expects labels in the input at serving time, pass raw_labels_keys=[].\n raw_feature_keys: A list of string keys of the raw features to be used.\n If None or empty, defaults to all features except labels.\n convert_scalars_to_vectors: Boolean specifying whether this input_fn should\n convert scalars into 1-d vectors. This is necessary if the inputs will be\n used with `FeatureColumn`s as `FeatureColumn`s cannot accept scalar\n inputs. Default: True.\n\n Returns:\n An input_fn suitable for serving that applies transforms to raw data in\n tf.Examples.\n \"\"\"\n\n raw_feature_spec = raw_metadata.schema.as_feature_spec()\n raw_feature_keys = _prepare_feature_keys(raw_metadata,\n raw_label_keys,\n raw_feature_keys)\n raw_serving_feature_spec = {key: raw_feature_spec[key]\n for key in raw_feature_keys}\n\n def _serving_input_fn():\n \"\"\"Applies transforms to raw data in json-example strings.\"\"\"\n\n json_example_placeholder = tf.placeholder(tf.string, shape=[None])\n example_strings = tf.decode_json_example(json_example_placeholder)\n raw_features = tf.parse_example(example_strings, raw_serving_feature_spec)\n inputs = {\"json_example\": json_example_placeholder}\n\n _, transformed_features = (\n saved_transform_io.partially_apply_saved_transform(\n transform_savedmodel_dir, raw_features))\n\n if convert_scalars_to_vectors:\n transformed_features = _convert_scalars_to_vectors(transformed_features)\n\n return input_fn_utils.InputFnOps(transformed_features, None, inputs)\n\n return _serving_input_fn\n\n\ndef build_parsing_transforming_serving_input_fn(\n raw_metadata,\n transform_savedmodel_dir,\n raw_label_keys,\n raw_feature_keys=None,\n convert_scalars_to_vectors=True):\n \"\"\"Creates input_fn that applies transforms to raw data in tf.Examples.\n\n Args:\n raw_metadata: a `DatasetMetadata` object describing the raw data.\n transform_savedmodel_dir: a SavedModel directory produced by tf.Transform\n embodying a transformation function to be applied to incoming raw data.\n raw_label_keys: A list of string keys of the raw labels to be used. These\n labels are removed from the serving graph. To build a serving function\n that expects labels in the input at serving time, pass raw_labels_keys=[].\n raw_feature_keys: A list of string keys of the raw features to be used.\n If None or empty, defaults to all features except labels.\n convert_scalars_to_vectors: Boolean specifying whether this input_fn should\n convert scalars into 1-d vectors. This is necessary if the inputs will be\n used with `FeatureColumn`s as `FeatureColumn`s cannot accept scalar\n inputs. Default: True.\n\n Returns:\n An input_fn suitable for serving that applies transforms to raw data in\n tf.Examples.\n \"\"\"\n\n raw_feature_spec = raw_metadata.schema.as_feature_spec()\n raw_feature_keys = _prepare_feature_keys(raw_metadata,\n raw_label_keys,\n raw_feature_keys)\n raw_serving_feature_spec = {key: raw_feature_spec[key]\n for key in raw_feature_keys}\n\n def parsing_transforming_serving_input_fn():\n \"\"\"Serving input_fn that applies transforms to raw data in tf.Examples.\"\"\"\n raw_input_fn = input_fn_utils.build_parsing_serving_input_fn(\n raw_serving_feature_spec, default_batch_size=None)\n raw_features, _, inputs = raw_input_fn()\n _, transformed_features = (\n saved_transform_io.partially_apply_saved_transform(\n transform_savedmodel_dir, raw_features))\n\n if convert_scalars_to_vectors:\n transformed_features = _convert_scalars_to_vectors(transformed_features)\n\n return input_fn_utils.InputFnOps(transformed_features, None, inputs)\n\n return parsing_transforming_serving_input_fn\n\n\ndef build_default_transforming_serving_input_fn(\n raw_metadata,\n transform_savedmodel_dir,\n raw_label_keys,\n raw_feature_keys=None,\n convert_scalars_to_vectors=True):\n \"\"\"Creates input_fn that applies transforms to raw data in Tensors.\n\n Args:\n raw_metadata: a `DatasetMetadata` object describing the raw data.\n transform_savedmodel_dir: a SavedModel directory produced by tf.Transform\n embodying a transformation function to be applied to incoming raw data.\n raw_label_keys: A list of string keys of the raw labels to be used. These\n labels are removed from the serving graph. To build a serving function\n that expects labels in the input at serving time, pass raw_labels_keys=[].\n raw_feature_keys: A list of string keys of the raw features to be used.\n If None or empty, defaults to all features except labels.\n convert_scalars_to_vectors: Boolean specifying whether this input_fn should\n convert scalars into 1-d vectors. This is necessary if the inputs will be\n used with `FeatureColumn`s as `FeatureColumn`s cannot accept scalar\n inputs. Default: True.\n\n Returns:\n An input_fn suitable for serving that applies transforms to raw data in\n tf.Examples.\n\n Raises:\n ValueError: if raw_label_keys is not provided.\n \"\"\"\n if raw_label_keys is None:\n raise ValueError(\"raw_label_keys must be specified.\")\n if raw_feature_keys is None:\n raw_feature_keys = list(\n set(six.iterkeys(raw_metadata.schema.column_schemas))\n - set(raw_label_keys))\n\n def default_transforming_serving_input_fn():\n \"\"\"Serving input_fn that applies transforms to raw data in Tensors.\"\"\"\n\n raw_serving_features = {\n k: v\n for k, v in six.iteritems(raw_metadata.schema.as_batched_placeholders())\n if k in raw_feature_keys}\n sparse_serving_features = [t for t in raw_serving_features\n if isinstance(t, tf.SparseTensor)]\n if sparse_serving_features:\n raise ValueError(\"Feeding sparse tensors directly at serving time is not \"\n \"supported.\")\n _, transformed_features = (\n saved_transform_io.partially_apply_saved_transform(\n transform_savedmodel_dir, raw_serving_features))\n\n if convert_scalars_to_vectors:\n transformed_features = _convert_scalars_to_vectors(transformed_features)\n\n return input_fn_utils.InputFnOps(\n transformed_features, None, raw_serving_features)\n\n return default_transforming_serving_input_fn\n\n\ndef build_training_input_fn(metadata,\n file_pattern,\n training_batch_size,\n label_keys,\n feature_keys=None,\n reader=tf.TFRecordReader,\n key_feature_name=None,\n convert_scalars_to_vectors=True,\n **read_batch_features_args):\n \"\"\"Creates an input_fn that reads training data based on its metadata.\n\n Args:\n metadata: a `DatasetMetadata` object describing the data.\n file_pattern: List of files or pattern of file paths containing\n `Example` records. See `tf.gfile.Glob` for pattern rules.\n training_batch_size: An int or scalar `Tensor` specifying the batch size to\n use.\n label_keys: A list of string keys of the labels to be used.\n feature_keys: A list of string keys of the features to be used.\n If None or empty, defaults to all features except labels.\n reader: A function or class that returns an object with\n `read` method, (filename tensor) -> (example tensor).\n key_feature_name: A name to use to add a key column to the features dict.\n Defaults to None, meaning no key column will be created.\n convert_scalars_to_vectors: Boolean specifying whether this input_fn should\n convert scalars into 1-d vectors. This is necessary if the inputs will be\n used with `FeatureColumn`s as `FeatureColumn`s cannot accept scalar\n inputs. Default: True.\n **read_batch_features_args: any additional arguments to be passed through to\n `read_batch_features()`, including e.g. queue parameters.\n\n Returns:\n An input_fn suitable for training that reads training data.\n \"\"\"\n feature_spec = metadata.schema.as_feature_spec()\n feature_keys = _prepare_feature_keys(metadata, label_keys, feature_keys)\n\n training_feature_spec = {key: feature_spec[key]\n for key in feature_keys + label_keys}\n\n def training_input_fn():\n \"\"\"A training input function that reads materialized transformed data.\"\"\"\n\n if key_feature_name is not None:\n keys, data = tf.contrib.learn.io.read_keyed_batch_features(\n file_pattern, training_batch_size, training_feature_spec,\n reader, **read_batch_features_args)\n else:\n data = tf.contrib.learn.io.read_batch_features(\n file_pattern, training_batch_size, training_feature_spec, reader,\n **read_batch_features_args)\n\n features = {k: v for k, v in six.iteritems(data) if k in feature_keys}\n labels = {k: v for k, v in six.iteritems(data) if k in label_keys}\n\n if convert_scalars_to_vectors:\n features = _convert_scalars_to_vectors(features)\n labels = _convert_scalars_to_vectors(labels)\n\n if key_feature_name is not None:\n features[key_feature_name] = keys\n\n if len(labels) == 1:\n (_, labels), = labels.items()\n return features, labels\n\n return training_input_fn\n\n\ndef build_transforming_training_input_fn(raw_metadata,\n transformed_metadata,\n transform_savedmodel_dir,\n raw_data_file_pattern,\n training_batch_size,\n raw_label_keys,\n transformed_label_keys,\n raw_feature_keys=None,\n transformed_feature_keys=None,\n reader=tf.TFRecordReader,\n key_feature_name=None,\n convert_scalars_to_vectors=True,\n **read_batch_features_args):\n \"\"\"Creates training input_fn that reads raw data and applies transforms.\n\n Args:\n raw_metadata: a `DatasetMetadata` object describing the raw data.\n transformed_metadata: a `DatasetMetadata` object describing the raw data.\n transform_savedmodel_dir: a SavedModel directory produced by tf.Transform\n embodying a transformation function to be applied to incoming raw data.\n raw_data_file_pattern: List of files or pattern of file paths containing\n `Example` records. See `tf.gfile.Glob` for pattern rules.\n training_batch_size: An int or scalar `Tensor` specifying the batch size to\n use.\n raw_label_keys: A list of string keys of the raw labels to be used.\n transformed_label_keys: A list of string keys of the transformed labels to\n be used.\n raw_feature_keys: A list of string keys of the raw features to be used.\n If None or empty, defaults to all features except labels.\n transformed_feature_keys: A list of string keys of the transformed features\n to be used. If None or empty, defaults to all features except labels.\n reader: A function or class that returns an object with\n `read` method, (filename tensor) -> (example tensor).\n key_feature_name: A name to use to add a key column to the features dict.\n Defaults to None, meaning no key column will be created.\n convert_scalars_to_vectors: Boolean specifying whether this input_fn should\n convert scalars into 1-d vectors. This is necessary if the inputs will be\n used with `FeatureColumn`s as `FeatureColumn`s cannot accept scalar\n inputs. Default: True.\n **read_batch_features_args: any additional arguments to be passed through to\n `read_batch_features()`, including e.g. queue parameters.\n\n Returns:\n An input_fn suitable for training that reads raw training data and applies\n transforms.\n \"\"\"\n\n raw_feature_spec = raw_metadata.schema.as_feature_spec()\n raw_feature_keys = _prepare_feature_keys(raw_metadata,\n raw_label_keys, raw_feature_keys)\n raw_training_feature_spec = {\n key: raw_feature_spec[key]\n for key in raw_feature_keys + raw_label_keys}\n\n transformed_feature_keys = _prepare_feature_keys(\n transformed_metadata, transformed_label_keys, transformed_feature_keys)\n\n def raw_training_input_fn():\n \"\"\"Training input function that reads raw data and applies transforms.\"\"\"\n\n if key_feature_name is not None:\n keys, raw_data = tf.contrib.learn.io.read_keyed_batch_features(\n raw_data_file_pattern, training_batch_size, raw_training_feature_spec,\n reader, **read_batch_features_args)\n else:\n raw_data = tf.contrib.learn.io.read_batch_features(\n raw_data_file_pattern, training_batch_size, raw_training_feature_spec,\n reader, **read_batch_features_args)\n transformed_data = saved_transform_io.apply_saved_transform(\n transform_savedmodel_dir, raw_data)\n\n transformed_features = {\n k: v for k, v in six.iteritems(transformed_data)\n if k in transformed_feature_keys}\n transformed_labels = {\n k: v for k, v in six.iteritems(transformed_data)\n if k in transformed_label_keys}\n\n if convert_scalars_to_vectors:\n transformed_features = _convert_scalars_to_vectors(transformed_features)\n transformed_labels = _convert_scalars_to_vectors(transformed_labels)\n\n if key_feature_name is not None:\n transformed_features[key_feature_name] = keys\n\n if len(transformed_labels) == 1:\n (_, transformed_labels), = transformed_labels.items()\n return transformed_features, transformed_labels\n\n return raw_training_input_fn\n\n\ndef _prepare_feature_keys(metadata, label_keys, feature_keys=None):\n \"\"\"Infer feature keys if needed, and sanity-check label and feature keys.\"\"\"\n if label_keys is None:\n raise ValueError(\"label_keys must be specified.\")\n if feature_keys is None:\n feature_keys = list(\n set(six.iterkeys(metadata.schema.column_schemas)) - set(label_keys))\n overlap_keys = set(label_keys) & set(feature_keys)\n if overlap_keys:\n raise ValueError(\"Keys cannot be used as both a feature and a \"\n \"label: {}\".format(overlap_keys))\n\n return feature_keys\n","sub_path":"tensorflow_transform/saved/input_fn_maker.py","file_name":"input_fn_maker.py","file_ext":"py","file_size_in_byte":21080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"585725991","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 17-8-11 下午3:30\n# @Author : zhe.zhang\n# @Site : \n# @File : 8-11-15-30-23JSON进阶.py\n# @Software: PyCharm Community Edition\n# @Function :\n__author__ = 'zhe.zhang'\nimport json\n\n\nclass Student(object):\n def __init__(self, name, age, score):\n self.name = name\n self.age = age\n self.score = score\n\n\ns = Student('zhe.zhang', '99', '100')\n\n\n# TypeError: <__main__.Student object at 0x7f287b72c860> is not JSON serializable\n# print(json.dumps(s))\n# 错误的原因是Student对象不是一个可序列化为JSON的对象。\n# 如果连class的实例对象都无法序列化为JSON,这肯定不合理!\n# 别急,我们仔细看看dumps()方法的参数列表,可以发现,除了第一个必须的obj参数外,dumps()方法还提供了一大堆的可选参数:\n# https://docs.python.org/3/library/json.html#json.dumps\n# 这些可选参数就是让我们来定制JSON序列化。前面的代码之所以无法把Student类实例序列化为JSON,是因为默认情况下,dumps()方法不知道如何将Student实例变为一个JSON的{}对象。\n# 可选参数default就是把任意一个对象变成一个可序列为JSON的对象,我们只需要为Student专门写一个转换函数,再把函数传进去即可:\nclass Student2(object):\n def __init__(self, name, age, score):\n self.name = name\n self.age = age\n self.score = score\n\n def student2dic(self):\n return {\n 'name': self.name,\n 'age': self.age,\n 'score': self.score\n }\n\n\n# 这样,Student实例首先被student2dict()函数转换成dict,然后再被顺利序列化为JSON:\nstd2 = Student2('zhe.zhang', '99', '100')\nprint(json.dumps(std2, default=Student2.student2dic))\n# 不过,下次如果遇到一个Teacher类的实例,照样无法序列化为JSON。我们可以偷个懒,把任意class的实例变为dict:\nprint(json.dumps(std2, default=lambda obj: obj.__dict__))\n\n\n# 因为通常class的实例都有一个__dict__属性,它就是一个dict,用来存储实例变量。也有少数例外,比如定义了__slots__的class。\n# 同样的道理,如果我们要把JSON反序列化为一个Student对象实例,loads()方法首先转换出一个dict对象,\n# 然后,我们传入的object_hook函数负责把dict转换为Student实例\n# 因为通常class的实例都有一个__dict__属性,它就是一个dict,用来存储实例变量。也有少数例外,比如定义了__slots__的class。\n\n# 同样的道理,如果我们要把JSON反序列化为一个Student对象实例,loads()方法首先转换出一个dict对象,然后,我们传入的object_hook函数负责把dict转换为Student实例:\nclass Student3(object):\n def __init__(self, name, age, score):\n self.name = name\n self.age = age\n self.score = score\n\n def student2dict(self):\n return {\n 'name': self.name,\n 'age': self.age,\n 'score': self.score\n }\n\n def dict2student(self):\n return Student3(self['name'], self['age'], self['score'])\n\n\nstd3 = Student3('name', '99', '100')\nfWrite = open('./json进阶.txt', 'w')\njson.dump(std3, fWrite, default=Student3.student2dict)\nfWrite.close()\nfRead = open('./json进阶.txt', 'r')\nprint(json.load(fRead, object_hook=Student3.dict2student))\nfRead.close()\n# 小结\n# Python语言特定的序列化模块是pickle,但如果要把序列化搞得更通用、更符合Web标准,就可以使用json模块。\n# json模块的dumps()和loads()函数是定义得非常好的接口的典范。当我们使用时,只需要传入一个必须的参数。但是,当默认的序列化或反序列机制不满足我们的要求时,我们又可以传入更多的参数来定制序列化或反序列化的规则,既做到了接口简单易用,又做到了充分的扩展性和灵活性。\n","sub_path":"learnPython/8-8-14-00-00-IO编程/8-9-14-05-26序列化/8-11-15-30-23JSON进阶.py","file_name":"8-11-15-30-23JSON进阶.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24203520","text":"\n\n#calss header\nclass _CHAMPIONSHIP():\n\tdef __init__(self,): \n\t\tself.name = \"CHAMPIONSHIP\"\n\t\tself.definitions = [u'a high-level competition to decide who is the best, especially in a sport: ', u'the position of being a champion: ', u'the support someone gives to a person, belief, right, or principle']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_championship.py","file_name":"_championship.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"454746842","text":"import pytest\nimport os\nimport numpy as np\nimport lightgbm as lgb\n\nfrom mlserver.settings import ModelSettings, ModelParameters\nfrom mlserver.types import InferenceRequest\n\nfrom mlserver_lightgbm import LightGBMModel\n\nTESTS_PATH = os.path.dirname(__file__)\nTESTDATA_PATH = os.path.join(TESTS_PATH, \"testdata\")\n\n\ndef pytest_collection_modifyitems(items):\n \"\"\"\n Add pytest.mark.asyncio marker to every test.\n \"\"\"\n for item in items:\n item.add_marker(\"asyncio\")\n\n\n@pytest.fixture\ndef model_uri(tmp_path) -> str:\n n = 4\n d = 3\n\n train = lgb.Dataset(data=np.random.rand(n, d), label=np.random.rand(n))\n print(train)\n bst = lgb.train(params={}, train_set=train)\n\n model_uri = os.path.join(tmp_path, \"lightgbm-model.bst\")\n bst.save_model(model_uri)\n\n return model_uri\n\n\n@pytest.fixture\ndef model_settings(model_uri: str) -> ModelSettings:\n return ModelSettings(\n name=\"lightgbm-model\",\n parameters=ModelParameters(uri=model_uri, version=\"v1.2.3\"),\n )\n\n\n@pytest.fixture\nasync def model(model_settings: ModelSettings) -> LightGBMModel:\n model = LightGBMModel(model_settings)\n await model.load()\n\n return model\n\n\n@pytest.fixture\ndef inference_request() -> InferenceRequest:\n payload_path = os.path.join(TESTDATA_PATH, \"inference-request.json\")\n return InferenceRequest.parse_file(payload_path)\n","sub_path":"runtimes/lightgbm/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456160668","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 10 13:41:12 2020\r\n\r\n@author: olga\r\n\"\"\"\r\n\r\n\r\nimport numpy\r\nimport math\r\nimport scipy\r\nimport pandas \r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\nfrom numpy import random\r\nfrom numpy import mean\r\nfrom matplotlib import pyplot\r\nfrom statsmodels.graphics.gofplots import qqplot\r\nfrom scipy import stats\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import r2_score\r\nimport statsmodels.api as sm\r\n\r\nimport seaborn as seabornInstance \r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn import metrics\r\n\r\n\r\n# path = 'C:/Users/Olga Rumyantseva/Desktop/US_forest/' # home comp.\r\npath = 'C:/Users/olga/Desktop/US_forest/Bayes_vectors_for_regression/'\r\n\r\n# in the dataset below NA-s in LAT and LON were removed:\r\ndf = pandas.read_csv(path + 'BayesSimsResults_all_USA.csv')\r\ndf.columns\r\n# df = df.dropna()\r\ndata = df.values \r\nnumpy.size(data, 0)\r\n\r\n\r\n###########################################################################\r\n######### Regression BA vs 1 clim var : ######################################\r\n###########################################################################\r\n\r\n\r\ndataset = pandas.DataFrame({'Basal Area': data[:,0],\r\n 'AnnualMeanTemperature': data[:,1],\r\n 'MeanDiurnalRange': data[:,2],\r\n 'Isothermality': data[:,3],\r\n 'TemperatureSeasonality': data[:,4],\r\n 'MaxTemperatureofWarmestMonth': data[:,5],\r\n 'MinTemperatureofColdestMonth': data[:,6],\r\n 'TemperatureAnnualRange': data[:,7],\r\n 'MeanTemperatureofWettestQuarter': data[:,8],\r\n 'MeanTemperatureofDriestQuarter': data[:,9],\r\n 'MeanTemperatureofWarmestQuarter': data[:,10],\r\n 'MeanTemperatureofColdestQuarter': data[:,11],\r\n 'AnnualPrecipitation': data[:,12],\r\n 'PrecipitationofWettestMonth': data[:,13],\r\n 'PrecipitationofDriestMonth': data[:,14],\r\n 'PrecipitationSeasonality': data[:,15],\r\n 'PrecipitationofWettestQuarter': data[:,16],\r\n 'PrecipitationofDriestQuarter': data[:,17],\r\n 'PrecipitationofWarmestQuarte': data[:,18],\r\n 'PrecipitationofColdestQuarter': data[:,19]})\r\n \r\n\r\ndataset.shape\r\n\r\ny = dataset[dataset.columns[0]].values # dataset['Basal Area']\r\n\r\n\r\n\r\nR2results_for_clim_vars = numpy.array([])\r\n\r\nfor j in range(19):\r\n X = dataset[dataset.columns[j+1]].values\r\n # split 80% of the data to training set while \r\n # 20% of the data to test set:\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\r\n X_train= X_train.reshape(-1, 1)\r\n y_train= y_train.reshape(-1, 1)\r\n X_test = X_test.reshape(-1, 1)\r\n \r\n regressor = LinearRegression() \r\n regressor.fit(X_train, y_train)\r\n \r\n y_pred = regressor.predict(X_test)\r\n \r\n R2result = r2_score(y_test, y_pred)\r\n print(round(R2result*100, 2))\r\n# print(j+1, round(R2result*100, 2))\r\n R2results_for_clim_vars = numpy.append(R2results_for_clim_vars, R2result)\r\n\r\n\r\nprint('clim. var ',numpy.argmax(R2results_for_clim_vars)+1,\r\n ' explains ', round(numpy.max(R2results_for_clim_vars)*100, 1), '%')\r\n\r\n\r\n\r\n# Plot outputs\r\n# plt.scatter(X_test, y_test, color='black')\r\n# plt.plot(X_test, y_pred, color='blue', linewidth=3)\r\n# plt.xticks(())\r\n# plt.yticks(())\r\n# plt.show()\r\n\r\n\r\n\r\n###########################################################################\r\n######### Regression BA vs 2 clim vars : ######################################\r\n###########################################################################\r\n\r\ny = dataset[dataset.columns[0]].values # dataset['Basal Area']\r\n\r\nR2results_for_clim_vars2 = numpy.array([])\r\n\r\n\r\nfor j in range(19):\r\n if j+1 == 15:\r\n continue\r\n X = dataset.iloc[:, [15,j+1]].values\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\r\n \r\n regressor = LinearRegression() \r\n regressor.fit(X_train, y_train)\r\n \r\n y_pred = regressor.predict(X_test)\r\n \r\n R2result2 = r2_score(y_test, y_pred)\r\n \r\n print(round(R2result2*100, 3))\r\n# print(j+1, round(R2result2*100, 2))\r\n R2results_for_clim_vars2 = numpy.append(R2results_for_clim_vars2, R2result2)\r\n\r\n\r\nprint(round(numpy.max(R2results_for_clim_vars2)*100, 2), '%')\r\n\r\n###########################################################################\r\n######### Regression BA vs 3 clim vars : ######################################\r\n###########################################################################\r\n\r\nR2results_for_clim_vars3 = numpy.array([])\r\n\r\n\r\nfor j in range(19):\r\n if (j+1 == 15 or j+1 == 9):\r\n continue\r\n X = dataset.iloc[:, [15, 9, j+1]].values\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\r\n \r\n regressor = LinearRegression() \r\n regressor.fit(X_train, y_train)\r\n \r\n y_pred = regressor.predict(X_test)\r\n \r\n R2result3 = r2_score(y_test, y_pred)\r\n \r\n print(round(R2result3*100, 3))\r\n# print(j+1, round(R2result3*100, 2))\r\n R2results_for_clim_vars3 = numpy.append(R2results_for_clim_vars3, R2result3)\r\n\r\n\r\nprint(round(numpy.max(R2results_for_clim_vars3)*100, 2), '%')\r\n\r\n\r\n###########################################################################\r\n######### Regression BA vs 4 clim vars : ######################################\r\n###########################################################################\r\n\r\nR2results_for_clim_vars4 = numpy.array([])\r\n\r\n\r\nfor j in range(19):\r\n if (j+1 == 2 or j+1 == 9 or j+1 == 15):\r\n continue\r\n X = dataset.iloc[:, [2, 9, 15, j+1]].values\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\r\n \r\n regressor = LinearRegression() \r\n regressor.fit(X_train, y_train)\r\n \r\n y_pred = regressor.predict(X_test)\r\n \r\n R2result4 = r2_score(y_test, y_pred)\r\n \r\n print(round(R2result4*100, 2))\r\n# print(j+1, round(R2result4*100, 2))\r\n R2results_for_clim_vars4 = numpy.append(R2results_for_clim_vars4, R2result4)\r\n\r\n\r\nprint(round(numpy.max(R2results_for_clim_vars4)*100, 3), '%')\r\n\r\n###########################################################################\r\n######### Regression BA vs 5 clim vars : ######################################\r\n###########################################################################\r\n\r\nR2results_for_clim_vars5 = numpy.array([])\r\n\r\n\r\nfor j in range(19):\r\n if (j+1 == 2 or j+1 == 9 or j+1 == 15 or j+1 == 17):\r\n continue\r\n X = dataset.iloc[:, [2, 9, 15, 17, j+1]].values\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\r\n \r\n regressor = LinearRegression() \r\n regressor.fit(X_train, y_train)\r\n \r\n y_pred = regressor.predict(X_test)\r\n \r\n R2result5 = r2_score(y_test, y_pred)\r\n \r\n print(round(R2result5*100, 2))\r\n# print(j+1, round(R2result4*100, 2))\r\n R2results_for_clim_vars5 = numpy.append(R2results_for_clim_vars5, R2result5)\r\n\r\n\r\nprint(round(numpy.max(R2results_for_clim_vars5)*100, 3), '%')\r\n\r\n","sub_path":"Regression_BayesBA_vs_BayesClimate_all_USA.py","file_name":"Regression_BayesBA_vs_BayesClimate_all_USA.py","file_ext":"py","file_size_in_byte":7508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"106375700","text":"import logging\nimport os\nimport platform\n\nimport click\n\nfrom eyesight import __version__ # noqa\n\n__all__ = ['cli']\n\n\nPROGRAM_NAME = 'eyesight'\nMIN_MACOS_VERSION = 10.10\nLOG_VERBOSITY_MAP = {True: logging.DEBUG, False: logging.WARNING}\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nclass ClickFormatter(logging.Formatter):\n colors = {\n 'critical': 'red',\n 'debug': 'blue',\n 'error': 'red',\n 'exception': 'red',\n 'warning': 'yellow',\n }\n\n def format(self, record):\n if not record.exc_info:\n level = record.levelname.lower()\n msg = record.msg\n if level in self.colors:\n prefix = click.style(\n '{0}: '.format(level.title()), fg=self.colors[level]\n )\n if not isinstance(msg, (str, bytes)):\n msg = str(msg)\n msg = '\\n'.join(prefix + l for l in msg.splitlines())\n return msg\n return logging.Formatter.format(self, record)\n\n\nclass ClickHandler(logging.Handler):\n error_levels = ['critical', 'error', 'exception', 'warning']\n\n def emit(self, record):\n try:\n msg = self.format(record)\n err = record.levelname.lower() in self.error_levels\n click.echo(msg, err=err)\n except Exception:\n self.handleError(record)\n\n\nclick_handler = ClickHandler()\nclick_formatter = ClickFormatter()\nclick_handler.setFormatter(click_formatter)\nlogger.addHandler(click_handler)\n\n\nclass Camera(object):\n \"\"\" Container for camera files and routines. \"\"\"\n\n paths = [\n '/System/Library/Frameworks/CoreMediaIO.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC',\n '/System/Library/PrivateFrameworks/CoreMediaIOServices.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC', # noqa\n '/System/Library/PrivateFrameworks/CoreMediaIOServicesPrivate.framework/Versions/A/Resources/AVC.plugin/Contents/MacOS/AVC', # noqa\n '/System/Library/PrivateFrameworks/CoreMediaIOServicesPrivate.framework/Versions/A/Resources/VDC.plugin/Contents/MacOS/VDC', # noqa\n '/System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Contents/MacOS/QuickTimeUSBVDCDigitizer',\n '/Library/CoreMediaIO/Plug-Ins/DAL/AppleCamera.plugin/Contents/MacOS/AppleCamera',\n '/Library/CoreMediaIO/Plug-Ins/FCP-DAL/AppleCamera.plugin/Contents/MacOS/AppleCamera',\n ]\n\n def __init__(self, enable=True):\n self.enable = enable\n self.files = self.get_files()\n\n @property\n def mode(self):\n return 0o755 if self.enable else 0o000\n\n def change_state(self):\n logger.info('{0} camera'.format('Enabling' if self.enable else 'Disabling'))\n\n for f in self.files:\n logger.debug('Processing: \"{0}\"'.format(f))\n os.chmod(f, self.mode)\n\n def get_files(self):\n logger.debug('Collecting camera files')\n files = []\n\n for p in self.paths:\n if os.path.isfile(p):\n logger.debug('Camera file found \"{0}\"'.format(p))\n files.append(p)\n else:\n logger.debug('Skipping missing camera file \"{0}\"'.format(p))\n\n if not files:\n raise click.ClickException('Could not locate camera files')\n return files\n\n\nclass Context(object):\n def __init__(self, enable, verbose):\n logger.debug('Gathering system and environment details')\n\n self.enable = enable\n self.verbose = verbose\n self.macos_version = self._get_mac_version()\n self.sip_enabled = self._get_sip_status()\n self.sudo = os.geteuid() == 0\n\n def _get_mac_version(self):\n version = platform.mac_ver()[0]\n version = float('.'.join(version.split('.')[:2])) # format as e.g., '10.10'\n return version\n\n def _get_sip_status(self):\n try:\n status = subprocess32.check_output(['csrutil', 'status'])\n except subprocess32.CalledProcessError:\n return None\n\n # status string format example: 'System Integrity Protection status: disabled.\\n'\n status = status.split(': ')[1].strip('.\\n').upper()\n return status == 'ENABLED'\n\n\n@click.command()\n@click.option(\n '--enable/--disable',\n '-e/-d',\n default=None,\n help='Set the camera state. No-op if missing.',\n)\n@click.option(\n '--verbose/--quiet',\n '-v/-q',\n is_flag=True,\n default=None,\n help='Specify verbosity level.',\n)\n@click.version_option()\n@click.pass_context\ndef cli(ctx, enable, verbose):\n logger.setLevel(LOG_VERBOSITY_MAP.get(verbose, logging.INFO))\n logger.debug('{0} started'.format(PROGRAM_NAME))\n\n logger.debug('Checking \"enable\" command line option')\n if enable is None:\n raise click.UsageError('Missing option (--enable/--disable)')\n\n ctx.obj = Context(enable, verbose)\n\n logger.debug('Checking macOS version')\n if ctx.obj.macos_version < MIN_MACOS_VERSION:\n raise click.ClickException(\n '{0} requires macOS {1} or higher'.format(PROGRAM_NAME, MIN_MACOS_VERSION)\n )\n\n logger.debug('Checking SIP status')\n if ctx.obj.sip_enabled is None:\n raise click.ClickException('Could not determine SIP status')\n elif ctx.obj.sip_enabled:\n raise click.ClickException('SIP is enabled')\n\n logger.debug('Checking user permissions')\n if not ctx.obj.sudo:\n raise click.ClickException('{0} must be run as root'.format(PROGRAM_NAME))\n\n camera = Camera(enable=ctx.obj.enable)\n camera.change_state()\n\n logger.info('Camera {0}'.format('enabled' if ctx.obj.enable else 'disabled'))\n\n\ndef show_exception(self, file=None):\n logger.error(self.message)\n\n\nclick.ClickException.show = show_exception\nclick.UsageError.show = show_exception\n","sub_path":"eyesight/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566735841","text":"# coding=utf8\n\n\"\"\"\n zhiz.views.page\n ~~~~~~~~~~~~~~~\n\n routes:\n\n page\n GET, `page/`, display a page\n\"\"\"\n\nfrom flask import abort\nfrom skylark import fn\n\nfrom zhiz import app\nfrom zhiz.models import Post\nfrom zhiz.views.utils import render_public\n\n\n@app.route('/page/')\ndef page(page_number):\n if page_number <= 0:\n abort(404)\n\n n = 9\n\n query = Post.where(published=True).orderby(\n Post.datetime, desc=True).limit(n, offset=n * (page_number - 1)\n ).select()\n results = query.execute()\n count = results.count\n\n if count < 0: # no posts\n abort(404)\n\n query = Post.where(published=True).select(fn.count(Post.id))\n result = query.execute()\n total_count = result.tuples()[0][0]\n\n is_first_page = True if page_number == 1 else False\n is_last_page = True if n * page_number >= total_count else False\n\n posts = tuple(results.all())\n\n page = dict(\n number=page_number,\n posts=posts,\n first=is_first_page,\n last=is_last_page\n )\n return render_public('page.html', page=page)\n","sub_path":"zhiz/views/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"570845988","text":"from quadrature import *\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import *\nfrom numpy import *\nimport numpy as np\n\ndef make_random_partition(n):\n partition = [0]\n lower = 0\n for i in range(n):\n new_rand = random.uniform(lower, 1)\n partition.append(new_rand)\n lower = new_rand\n partition.append(1)\n return partition\n\ndef make_h_from_interval(interval, dim):\n h_arr = [interval[j + 1] - interval[j] for j in range(dim-1)]\n return h_arr\n\ndef make_elems(dim, nodes):\n elem_arr = [[nodes[j],nodes[j+1]] for j in range(dim-1)]\n return elem_arr\n\ndef make_elem_indices(dim):\n elem_arr = [[j,j+1] for j in range(dim)]\n return elem_arr\n\ndef two(x):\n return 2.\n\ndef exp4(x):\n return exp(4*x)\n\ndef make_diri(num_elems):\n diri = zeros(num_elems)\n for i in range(num_elems):\n if i == 0 or i == num_elems-1: diri[i] = True\n else: diri[i] = False\n return diri\n\ndef make_boundary_vals(num_elems, left_boundary, right_boundary):\n boundary = zeros(num_elems)\n for i in range(num_elems):\n if i == 0: boundary[i] = left_boundary #* h_arr[0]\n elif i == num_elems-1: boundary[i] = right_boundary #* h_arr[0]\n return boundary\n\n\"\"\"\nTODO: Use general quadrature routines\n\"\"\"\ndef make_local_matrix_and_local_rhs(elem, u_prime_coef):\n A_loc = zeros((2,2))\n b_loc = zeros(2)\n for i in range(2):\n for j in range(2):\n A_loc[i,j] = integ_deriv_deriv(elem, i, j)\n A_loc[i,j] += integ_deriv_basis(elem, i, j, u_prime_coef)\n b_loc[i] += integ_f_basis(elem, two)\n return A_loc, b_loc\n\n\"\"\"\nFans out the values in the submatrix local to their\ncorrect place in the global matrix, A. The boundary\nconditions are taken care of by use of the diri (short\nfor Dirichlet) array.\n\"\"\"\ndef fan_out(elem_i, A_loc, b_loc, diri, A, b, boundary):\n # number of rows\n for v_i in range(2):\n # number of columns\n for u_j in range(2):\n # if we aren't on a boundary element\n if not diri[elem_i[v_i]] and not diri[elem_i[u_j]]:\n # fan out to the corresponding matrix entry\n A[elem_i[v_i]][elem_i[u_j]] += A_loc[v_i][u_j]\n # fan out to the RHS exactly once\n if u_j == 0: b[elem_i[v_i]] += b_loc[v_i]\n # fan out to the RHS vector if symmetric\n # if just the row is on the boundary\n elif diri[elem_i[u_j]] and not diri[elem_i[v_i]]:\n b[elem_i[v_i]] -= boundary[elem_i[u_j]] * A_loc[v_i][u_j]\n elif v_i == u_j:\n A[elem_i[v_i]][elem_i[u_j]] = 1\n b[elem_i[v_i]] = boundary[elem_i[v_i]]\n\n\n\"\"\"\nBuild the global A matrix by first constructing local\nsubmatrices and then \"fanning them out\" to the correct\nplaces.\n\"\"\"\ndef make_global_matrix_and_rhs(elems_i, elems, diri, boundary, u_prime_coef):\n dim = len(elems_i)\n #rhs = set_rhs(h_arr)\n b = zeros(dim)\n A = zeros((dim,dim))\n for i in range(dim-1):\n A_loc, b_loc = make_local_matrix_and_local_rhs(elems[i], u_prime_coef)\n fan_out(elems_i[i], A_loc, b_loc, diri, A, b, boundary)\n return A, b\n\ndef parabolic_soln(x, c_1, c_2):\n return -x**2+c_1*x+c_2\n\nerrors = []\nnum_tests = 2\nstart_dim = 1\nnum_intervals = 10\n\n#for num_intervals in range(start_dim, num_tests):\nh = 1.0/num_intervals\nnodes = linspace(0.0, 1.0, num_intervals + 1)\n#nodes = make_random_partition(num_intervals+1)\n#nodes = [0.0, 0.2, 0.27, 0.32, 0.4, 0.45, 0.46, 0.51, 0.54, 0.56, 0.59, 0.63, 0.78, 0.84, 0.9, 1.0]\ndim = len(nodes)\nelems_i = make_elem_indices(dim)\nelems = make_elems(dim, nodes)\ndiri = make_diri(len(elems_i))\n#h_arr = make_h_from_interval(nodes, dim)\nleft_boundary = 0.#/h_arr[0]\nright_boundary = 0.#/h_arr[dim-2]\n#boundary = zeros(dim)\nboundary = make_boundary_vals(len(elems_i), left_boundary, right_boundary)\n#rhs = ones(dim)\nu_prime_coef = 0\nA_fem, rhs = make_global_matrix_and_rhs(elems_i, elems, diri, boundary, u_prime_coef)\nsoln = solve(A_fem, rhs)\n#print zip(nodes, soln)\n#true_soln = [parabolic_soln(x, 1, -2) for x in nodes]\n#true_soln = [2 * (x + 5) + 23 * exp(5 - 5 *x) - exp(5 (2*x + 33))/(5 - 5 e^5)\n\nx = nodes\nplt.xlabel('x')\nplt.ylabel('Solution')\nplt.plot(x , soln)\n# plt.plot(x , true_soln)\nplt.show()\n","sub_path":"python_code/finelem.py","file_name":"finelem.py","file_ext":"py","file_size_in_byte":4278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"290276163","text":"# Keesha Erickson, Nov 2018\r\n# plot heatmaps from bngl files\r\n# plot rankings of recruitment\r\n# clustering by cell line and protein recruitment\r\n\r\nfrom heatmaps_demo_def import heatmapsIGF1R, clusteringIGF1R, rankIGF1R\r\n\r\n# location of gdat files\r\n# there can only be gdat files in here (rm cdat and net)\r\nloc = 'C:/Users/Keesha/PycharmProjects/IGF1R/NCI60/bnglout/'\r\n\r\n# plot heatmaps of protein recruitment\r\nheatmapsIGF1R(loc)\r\n\r\n# rank analysis\r\nrankIGF1R(loc)\r\n\r\n# cluster cell lines\r\nclusteringIGF1R(loc)\r\n\r\n","sub_path":"igf1r_demo.py","file_name":"igf1r_demo.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"134578735","text":"# 画图,学用rectangle画方形。  \n\nimport turtle as tt\n\n# 参数n多边形边数\ndef drawLine(n):\n t=tt.Pen()\n t.color('yellow')\n t.width(3)\n t.begin_fill()\n t.shape('turtle')\n\n for i in range(n):\n t.forward(100)\n t.left(360/n)\n t.end_fill() \n\ndef drawRactangle():\n t=tt.Pen()\n t.color('blue')\n t.width(3)\n t.shape('turtle')\n\n t.begin_fill()\n for i in range(4):\n t.forward(100)\n t.left(90)\n t.end_fill()\n\n\n \ndef run():\n #drawLine(8)\n drawRactangle()\n \nrun()\n","sub_path":"Practices/Practice58.py","file_name":"Practice58.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"30581247","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/11/28 1:58 下午\n# @Author : Yijia Zheng\n# @FileName: tools.py\n\n# Useful Functions that will be repeatedly used\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\n\n\ndef pca(XMat, k):\n average = np.mean(XMat)\n m, n = np.shape(XMat)\n avgs = np.tile(average, (m, 1))\n data_adjust = XMat - avgs\n covX = np.cov(data_adjust.T)\n featValue, featVec= np.linalg.eig(covX)\n index = np.argsort(-featValue)\n if k > n:\n print(\"k must lower than feature number\")\n return\n else:\n selectVec = np.matrix(featVec.T[index[:k]]) #转置\n finalData = data_adjust * selectVec.T\n reconData = (finalData * selectVec) + average\n return finalData.real, reconData\n\n\ndef confusion_matrix(preds, labels):\n conf_matrix = np.zeros((len(labels), len(labels)))\n for p, t in zip(preds, labels):\n conf_matrix[p, t] += 1\n return conf_matrix\n\n\ndef plot_confusion_matrix(confusion_mat, save_path):\n plt.rcParams['figure.dpi'] = 500\n plt.imshow(confusion_mat, interpolation='nearest', cmap=plt.cm.gray)\n thresh = confusion_mat.max() / 2.\n for i, j in itertools.product(range(confusion_mat.shape[0]), range(confusion_mat.shape[1])):\n plt.text(j, i, confusion_mat[i, j],\n horizontalalignment=\"center\",\n color=\"black\" if confusion_mat[i, j] > thresh else \"white\")\n plt.title('Confusion matrix')\n plt.colorbar()\n tick_marks = np.arange(confusion_mat.shape[0])\n plt.xticks(tick_marks, tick_marks)\n plt.yticks(tick_marks, tick_marks)\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.savefig(save_path)\n plt.show()\n\n\n\n","sub_path":"models/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"376030728","text":"import cv2\nimport csv\nimport time\nimport numpy as np\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nfrom select_points import select_points\nfrom warp_image import warp_image\n\ntime.sleep(30)\n\ndef drawBox(image, boundary):\n x, y, w, h = int(boundary[0]), int(boundary[1]), int(boundary[2]), int(boundary[3])\n cv2.rectangle(image, (x, y), ((x + w), (y + h)), (255, 0, 255), 3, 1)\n cv2.putText(image, \"Tracking...\", (75, 75), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 255, 0), 2)\n\n#tracker = cv2.TrackerMOSSE_create()\n# tracker = cv2.TrackerCSRT_create()\n#tracker = cv2.TrackerMedianFlow_create()\n\ncamera = PiCamera() # initialize the camera and grab a reference to the raw camera capture\ncamera.resolution = (1280,720)\ncamera.framerate = 10\nrawCapture = PiRGBArray(camera, size=(1280,720))\ntime.sleep(0.1) # allows the camera to warmup\n\ncamera.capture(rawCapture, format=\"bgr\")\nimage = rawCapture.array\nrawCapture.truncate(0)\n\n#_, img = cap.read() # get initial image\n\n#coords, image1 = select_points(image)\ncoords = [[55, 326], [805, 277], [48, 636], [831, 559]] # these two lines are for when you know the coordinates\nimage1 = warp_image(image,coords) # I want to run this automatically at boot without human intervention\n\n#camera.capture(rawCapture, format=\"bgr\")\n#image = rawCapture.array\n#rawCapture.truncate(0)\n#image2 = warp_image(image,coords)\n\n#bbox = cv2.selectROI(\"Tracking\", image, False) # select bounding box\n#tracker.init(image, bbox) # initialize the tracker on the selected bounding box\n#ok, img = cap.read() # get the next image\n\n#img = warp_image(img, coords) ## maybe i'll use this\n\n# fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n# video = cv2.VideoWriter('Resources/geno_detect.mp4', fourcc, 30, (1080, 1920))\n\nt = time.localtime()\ncurrent_date = time.strftime(\"%Y%m%d\", t)\ncsv_file = 'logged_data/' + current_date + '_location.csv'\n\nwith open(csv_file, 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow([\"time\",\"x_pixel\", \"y_pixel\",])\n \nx_pixel = np.zeros(5)\ny_pixel = np.zeros(5)\ncounter = 0\n\nfor frame in camera.capture_continuous(rawCapture, format = 'bgr', use_video_port=True):\n timer = cv2.getTickCount() # this is for the fps counter\n\n img = frame.array\n image2 = warp_image(img,coords)\n \n diff = cv2.absdiff(image1,image2)\n gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\n blur= cv2.GaussianBlur(gray, (5,5),0)\n _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)\n dilated = cv2.dilate(thresh,None,iterations=3)\n contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n \n largest = 0\n largest_contour = None\n \n for contour in contours:\n #(x,y,w,h) = cv2.boundingRect(contour)\n if cv2.contourArea(contour) > largest:\n largest = cv2.contourArea(contour)\n largest_contour = contour\n if largest_contour is not None:\n\n (x,y,w,h) = cv2.boundingRect(largest_contour)\n cv2.rectangle(image1,(x,y),(x+w,y+h),(0,255,0),2)\n \n\n #x, y, w, h = int(contours[0]), int(contours[1]), int(contours[2]), int(contours[3])\n x_pos = x + w / 2\n y_pos = y + h / 2\n \n if counter < 4:\n x_pixel[counter] = x_pos\n y_pixel[counter] = y_pos\n counter += 1\n \n else:\n \n x_pixel[counter] = x_pos\n y_pixel[counter] = y_pos\n \n t = time.localtime()\n current_time = time.strftime(\"%Y/%m/%d %H:%M:%S\", t)\n \n with open(csv_file, 'a', newline='') as file:\n writer = csv.writer(file)\n writer.writerow([current_time, np.average(x_pixel), np.average(y_pixel)])\n \n x_pixel = np.zeros(5)\n y_pixel = np.zeros(5)\n counter = 0\n #cv2.drawContours(image1, contours, -1, (0,255,0),2)\n \n #ok, new_bbox = tracker.update(img) # updates with a new bounding box in the next frame\n\n# if contours:\n# \n# print(contours)\n# #drawBox(img, new_bbox) # if the object is found, draw the new box on the image\n#\n#\n\n\n \n# else:\n# cv2.putText(img, \"Lost\", (75, 75), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 0, 255), 2)\n\n \n fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer) # fps junk\n\n cv2.putText(img, str(int(fps)), (75, 50), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 0, 255), 2)\n\n #cv2.imshow(\"Motion Detection\", image1)\n #cv2.imshow(\"diff\",diff)\n rawCapture.truncate(0)\n\n if cv2.waitKey(1) & 0xff == ord('q'):\n break\n \n image1 = image2\n\n #video.write(img)\n #ok, img = cap.read() # get the next image in the stream for tracking\n #if ok:\n # img = warp_image(img, coords)\n\ncv2.destroyAllWindows()\n# video.release()\n","sub_path":"track_geno.py","file_name":"track_geno.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"470664702","text":"import sys, os\nimport re\nfrom difflib import SequenceMatcher\nfrom PyTib.common import open_file, write_file, pre_process\nfrom xlwt import Workbook\nimport yaml\nfrom pathlib import Path\n\n\nparentDir = Path(__file__).resolve().parent\ninDir = parentDir / 'input'\noutDir = parentDir / 'output'\n\n\ndef is_punct(string):\n # put in common\n if '༄' in string or '༅' in string or '༆' in string or '༇' in string or '༈' in string or \\\n '།' in string or '༎' in string or '༏' in string or '༐' in string or '༑' in string or \\\n '༔' in string or '_' in string:\n return True\n else:\n return False\n\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\ndef strip_particle(word):\n particles = ['འི','འུ','འོ','ར','འམ']\n for particle in particles:\n word = word.strip(particle)\n return word\n\n\ndef reinsert_notes(raw_text, raw_notes, basis_edition='སྡེ་'):\n global note_num\n raw_text = raw_text.replace('a', '').replace('\\t', ' ').split('\\n')\n raw_notes = re.sub(r'《([^《》་]+)》', r'《\\1་》', raw_notes) # add a tsek in the edition names that lack one.\n raw_notes = raw_notes.strip().split('\\n')[1:]\n\n text = {}\n for t in raw_text:\n parts = re.split(r'([0-9]+)\\.[\\t\\s]', t)[1:]\n if parts:\n note_number = parts[0]\n note_text = pre_process(parts[1], mode='syls')\n if note_text == []:\n note_text = ['']\n text[note_number] = note_text\n\n edition_regex = r'《([^《》]+)》'\n\n # finding all the editions that exist for that text\n edition_names = set([e for r in raw_notes for e in re.findall(edition_regex, r)])\n editions = {basis_edition: []}\n for e in edition_names:\n editions[e] = []\n\n error = False\n for n in raw_notes:\n #if debug == 1:\n if show_note == 1:\n print('\\t\\t'+n)\n if error:\n break\n if n.replace(',', '').replace(' ', '') == '':\n continue\n parts = n.split(',')\n number = str(int(parts[2])-1)\n # DEBUG. Enables to start debugging at a given note\n #note_num = 304\n if number == str(note_num-1):\n print('ok')\n page_number = parts[1]\n content = parts[4:]\n note = ''\n # keep track of which edition has already been replaced\n generated_versions = {basis_edition: False}\n for e in edition_names:\n generated_versions[e] = False\n # loop through tuples of (edition-s, note)\n max_pairs = len(content)-1\n if max_pairs > len(content):\n max_pairs = len(content)-1\n tuple_idx = [c for c in range(0, max_pairs) if c % 2 == 0]\n for a in tuple_idx:\n if error:\n break\n if content[a]:\n # filters the cases where the second tuple is empty\n note = content[a+1]\n if note == 'ལ་ཆུག་མོད་ཀྱི་ཞེས་བྱ་བ་ན།':\n print('check')\n if '(' in note:\n print('there is a note on top of the comparison.')\n print('\\t'.join(parts))\n note = note.split('(')[0].strip()\n if '《' in note:\n print('The following note needs to be edited. The execution will stop now.')\n print('\\t'.join(parts))\n error = True\n break\n # 0 prepare\n # separate in syllables not separating the fusioned particles\n modif_type = ''\n if note.startswith('m'):\n modif_type = 'm'\n elif note.startswith('p'):\n modif_type = 'p'\n version = pre_process(note.replace(modif_type, ''), mode='syls')\n # delete the last element in the list of the note\n #if is_punct(version[-1]):\n if is_punct(version[-1]) and len(version) > 1:\n del version[-1]\n # reconstitute the punctuation for comparing the syllables:\n\n # add a tsek to it if the original text has one\n # if the last syllable is not a punctuation\n if not version[-1].endswith('་'):\n if not is_punct(text[number][-1]):\n if not text[number][-1].endswith('་'):\n version[-1] += '་' \n # if the last syllable is a punctuation\n elif is_punct(text[number][-1]) and len(text[number]) > 1:\n if text[number][-2].endswith('་'):\n version[-1] += '་'\n\n # 1 find index\n # 1.a\n # find the index of the syllable from which to start replacing the original\n index = len(text[number]) - len(version)\n # go one syllable left if the last syllable of the original text is a punctuation\n if is_punct(text[number][-1]):\n index -= 1\n # put the index at 0 if the replacement text is longer than the original\n if index < 0:\n index = 0\n\n # 1.b\n # try to find a point of correspondence in case there are more than a few syllables that are added\n orig_sync_idx = False\n version_sync_idx = False\n window_size = 4\n maximum = len(text[number]) - 1\n # attempts_num becomes 0 if window_size is larger than the length of version, making window_indexes an empty list.\n # this way, window_size decides wether we search for a syncronisation point or not.\n attempts_num = len(version[window_size:])\n window_indexes = [(a, a + window_size) for a in range(attempts_num)]\n # for v_w in window_indexes:\n # for a_n in range(attempts_num):\n # orig_window = text[number][maximum - window_size - a_n:maximum - a_n]\n # version_window = version[v_w[0]:v_w[1]]\n # if orig_window == version_window:\n # if not orig_sync_idx:\n # orig_sync_idx = maximum - window_size - a_n\n # version_sync_idx = v_w[0]\n\n # finding the sync point if it is the last syllable\n if not orig_sync_idx:\n # detects which of the two syls is the longest to check if both start the same way\n if len(text[number][-1]) > len(version[0]):\n long = text[number][-1]\n #long = ''.join(text[number][index:])\n short = version[0].rstrip('་')\n #short = ''.join(version)\n else:\n long = version[0]\n short = text[number][-1].rstrip('་')\n # long = ''.join(version)\n # short = ''.join(text[number][index:])\n # finds if long is short with an addition. This deals with བདེའང་ being replaced by བདེ་བའང་.\n # Todo: similar replacements may occur elsewhere than the last syllable. implementation needed.\n # in case both syllables are identical, the condition is also met.\n if short in long:\n if short+'་' != long and (len(version)==1 or short == strip_particle(long.strip('་'))):\n if modif_type == 'p': # ,,9,4,《པེ་》《སྣར་》,pཔོ།,\n orig_sync_idx = len(text[number])\n else:\n orig_sync_idx = len(text[number])-1\n else:\n orig_sync_idx = index\n version_sync_idx = 0\n\n # 2\n # generating the versions of the different editions\n edition_text = [b for b in text[number]]\n\n # A.1 for subsequent addition, keep the last syllable if it is a punctuation to add it at the end\n edition_text_last_syl = False\n if is_punct(edition_text[-1]):\n edition_text_last_syl = edition_text[-1]\n #orig_sync_idx -= 1 # as note's conjuction are removed\n\n # remove the ending tsek in version if it was not there in the original\n if edition_text[-1].endswith('་'):\n if not version[-1].endswith('་'):\n version[-1] += '་'\n if version[-1].endswith('ང'):\n version[-1] += '་'\n else:\n if version[-1].endswith('་') and not version[-1].endswith('ང་'):\n version[-1] = version[-1].rstrip('་')\n\n # 2.1 if the operation is a deletion (m stands for minus)\n if modif_type == 'm':\n # a if there is a synchronizing point between the original and the version\n if orig_sync_idx:\n del edition_text[orig_sync_idx:]\n # b if there is no sync point\n else:\n del edition_text[len(edition_text)-len(version):]\n\n # 2.2 if the operation is an addition (p stands for plus)\n elif modif_type == 'p':\n # a if there is a synchronizing point between the original and the version\n if orig_sync_idx:\n # replace the part that precedes the synchronising point\n edition_text[orig_sync_idx - version_sync_idx:orig_sync_idx] = version[:version_sync_idx]\n # replacing from the synchronising point onwards\n edition_text[orig_sync_idx:orig_sync_idx] = version[version_sync_idx:]\n # b if there is no sync point\n else:\n # add a tsek if there is none on the last syllable\n if not edition_text[-1].endswith('་'):\n edition_text[-1] += '་'\n # remove the ending tsek of version\n if version[-1].endswith('་'):\n version[-1] = version[-1].rstrip('་')\n edition_text.extend(version)\n\n # 2.3 if the operation is a replacement\n else:\n if orig_sync_idx:\n # replace the part that precedes the synchronising point\n edition_text[orig_sync_idx - version_sync_idx:orig_sync_idx] = version[:version_sync_idx]\n # replacing from the synchronising point onwards\n edition_text[orig_sync_idx:] = version[version_sync_idx:]\n # 2.b if there is no synchronising point\n else:\n ad = 0\n prev_similarity = similar(edition_text[index-1].strip('་'), version[0].strip('་'))\n diff = len(edition_text[index-1].strip('་'))-len(version[0].strip('་'))\n if prev_similarity >= 0.5 and len(version)==1:\n ad = 1\n index -= 1\n elif strip_particle(edition_text[index-1].strip('་')) == strip_particle(version[0].strip('་')):\n ad = 1\n index -= 1\n # if len(version)>1:\n # if edition_text[index+1] in version:\n # index +=1\n # edition_text.append('')\n for e in range(len(version)):\n #print(e) # གཞུང་འདིའི་བསླབ་པ་ལ་ནི་བསླབ་པར་ དབུ་མ་རིན་པོ་ཆེའི་སྒྲོན་མ།.txt\n #print(version[e])\n edition_text[index + e] = version[e]\n if ad:\n del edition_text[-1]\n\n # A.2 add the punctuation to the end if needed\n # if a punctuation was saved in A.1 and if it is not the same as the last syllable of edition_text\n if edition_text_last_syl and len(edition_text) > 0:\n if edition_text_last_syl != edition_text[-1]:\n # if the last syllable ends with a tsek\n if edition_text[-1].endswith('་'):\n # if there is a ང་\n if not edition_text[-1].endswith('ང་'):\n edition_text[-1] = edition_text[-1][:-1]\n elif edition_text[-len(version)] == version[-1]:\n edition_text[-2] = edition_text[-1]\n edition_text[-1] = ''\n edition_text.append(edition_text_last_syl)\n\n\n # 2.4 if a sync point was found, i.e. if the size of version is longer than window_size,\n # add '%' to manually check the replacement has been correctly done\n #if orig_sync_idx:\n # edition_text[-1] += '%'\n\n # 3 Add the text to the respective editions\n #\n edition_refs = re.findall(edition_regex, content[a])\n # 3.a add the versions of all the editions that require modifications from Derge and notify the edition is added\n for e in edition_refs:\n chunk = ''.join(edition_text)\n # remove the extra spaces inserted between the shad and the next verse\n chunk = chunk.replace('_།_', '_།').replace('_', ' ')\n editions[e].append((chunk, len(version), page_number, note))\n generated_versions[e] = True\n\n # 3.b add the original version of the text to the remaining\n for g in generated_versions:\n if not generated_versions[g]:\n chunk = ''.join(text[number])\n # remove the extra spaces inserted between the shad and the next verse\n chunk = chunk.replace('_།_', '_།').replace('_', ' ')\n editions[g].append((chunk, '', page_number, note))\n\n # 4 add the last bit of the text that corresponds to no note\n for g in editions:\n chunk = ''.join(text[str(len(text))])\n chunk = chunk.replace('_།_', '_།').replace('_', ' ')\n editions[g].append((chunk, '', '', ''))\n return editions\n\n\ndef generate_editions(editions, out_dir, work_name):\n # writing all the editions in their respective folder\n for e in editions:\n path = out_dir / 'editions' / e.replace('་', '།') \n file_name = work_name+'_'+e+'.txt'\n content = ''.join([e[0] for e in editions[e]]).replace('_', ' ')\n write_file(path / file_name, content)\n\n\ndef generate_unified_version(editions):\n '''\n :param editions:\n :return: a list with common syllables as separate elements, differing parts within a dict\n '''\n total = []\n # a. generate the list of editions’ names\n ed_names = [a for a in editions]\n for syl_num in range(1, len(editions['སྡེ་'])):\n pre_processed = {}\n common = []\n # b. segment in syllables and seperate on the punctuation for each version\n for ed in ed_names:\n chunk = editions[ed][syl_num][0].replace('_', ' ')\n pre_processed[ed] = pre_process(chunk, mode='syls')\n # c. add to common the syls that are the same in all editions and leave the others in pre_processed\n while len({pre_processed[ed][0] if pre_processed[ed] != [] else '' for ed in ed_names}) == 1:\n if pre_processed[ed_names[0]]:\n common.append(pre_processed[ed_names[0]][0])\n for ed in ed_names:\n del pre_processed[ed][0]\n else:\n break\n\n total.extend(common)\n total.append(pre_processed)\n return total\n\n\ndef generate_context_versions(editions, file_name, out_dir, left=5, right=5, base_ed='སྡེ་'):\n def calculate_contexts(unified_version, left=5, right=5, base_ed='སྡེ་'):\n all_versions = []\n c = 0\n for num, syl in enumerate(unified_version):\n if type(syl) == dict:\n if c == 137:\n print('ok')\n versions = {}\n for ed in syl:\n # add left context\n n_l = num-left\n if n_l < 0:\n n_l = 0\n left_context = unified_version[n_l:num]\n # add note\n note = syl[ed]\n # add right context\n n_r = num+right+1\n if n_r > len(unified_version)-1:\n n_r = len(unified_version)-1\n right_context = unified_version[num+1:n_r]\n version = left_context + note + right_context\n # if there is a note (if version[v] == dict), choose the base_ed version\n no_note_version = []\n for v in version:\n if type(v) == dict:\n for base_syl in v[base_ed]:\n no_note_version.append(base_syl)\n else:\n no_note_version.append(v)\n # add the versions in the versions\n versions[ed] = ''.join(no_note_version).replace('_', ' ')\n c += 1\n versions[str(c)] = ''\n all_versions.append(versions)\n return all_versions\n\n unified = generate_unified_version(editions)\n with_context = calculate_contexts(unified, left=left, right=right, base_ed=base_ed)\n for i in range(len(with_context)):\n with_context[i] = [[a, with_context[i][a]] for a in sorted(with_context[i])]\n output = yaml.dump_all(with_context, allow_unicode=True, default_flow_style=False, width=float(\"inf\"))\n # reformat the page number\n output = re.sub(r'\\n- -([^\\n]+)\\n -', r'\\n\\1: ', output)\n output = re.sub(r\"---\\n '([0-9]+)': ''\", r'-\\1-', output)\n output = re.sub(r\"- - '1'\\n - ''\", r'-1-', output).replace(\" '\", '').replace(\"'\", '')\n output = re.sub(r'\\n', r',,,,,,,,,,,,,,,\\n', output) # Todo\n write_file(out_dir / f'/conc_yaml/{file_name}_conc.txt', output)\n\n\ndef export_unified_structure(editions, text_name, out_dir=outDir/'unified_structure'):\n unified = generate_unified_version(editions)\n out = yaml.dump(unified, allow_unicode=True, default_flow_style=False, width=float(\"inf\"))\n write_file(out_dir / f'{text_name}_unified_structure.yaml', out)\n\n\ndef generate_outputs(text_name, notes_name, context, in_dir=inDir, out_dir=outDir):\n\n # extract text and reinsert notes\n editions = reinsert_notes(open_file(in_dir/text_name), open_file(in_dir/notes_name).replace(';', ','))\n\n work_name = text_name.split('.')[0].replace(' ', '_')\n print(work_name)\n\n\n generate_editions(editions, out_dir, work_name)\n \n export_unified_structure(editions, work_name)\n\n generate_context_versions(editions, work_name, out_dir, left=context, right=context)\n\n\nexcluded = [#'11-20_ཆོས་མངོན་པའི་འགྲེལ་པ་གནད་ཀྱི་སྒྲོན་མ།.txt',\n ]\nvol_num = 0\n\nworks = []\nfor f in sorted(os.listdir(inDir)):\n if f.endswith('txt') and f not in excluded:\n csv = f.replace('.txt', '')+'.csv'\n works.append((f, csv))\n\ndef debug_files(vol_num):\n c = 0\n for w in works:\n c += 1\n print(c, w[0])\n if c >= vol_num:\n generate_outputs(w[0], w[1], 5)\n\n\nnote_num = 738\ndebug = 1\nshow_note = 0\nif debug:\n debug_files(vol_num)\nelse:\n for w in works:\n if 'N5000' not in w[0]:\n continue\n print(w[0])\n generate_outputs(w[0], w[1], 5)\n","sub_path":"1-a-reinsert_notes/insertion.py","file_name":"insertion.py","file_ext":"py","file_size_in_byte":20569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"3572824","text":"\n# coding: utf-8\n\n# In[112]:\n\n\nimport pprint as pp\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport numpy as np\nimport cv2\nimport time\nimport copy\nimport os\nimport json\n\n# For defining network\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n# For load data\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets,transforms\nfrom torch.utils.data.dataset import Dataset\n\n# For optimizer\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\n\n\n# In[73]:\n\n\ndef target2tensor(img):\n y = np.array(img['y'])\n tensor = torch.zeros((13,13,5))\n for box in img['boxes']:\n M = box['matrix_cell']\n r_y = box['region_y']\n tensor[M[1],M[0],:] = torch.Tensor(y[r_y[0]:r_y[1]+1]) \n return tensor\n\ndef open_json(file):\n with open(file) as data_file: \n dic = json.load(data_file)\n return dic\n\n\n# In[32]:\n\n\ndef mse_loss(input, target):\n return torch.sum((input - target) ** 2)\n\n\n# In[33]:\n\n\npreprocess = transforms.Compose([\n transforms.Resize((416,416)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n\n\n#
\n\n#

Yolo\n\n#

Network\n\n# In[122]:\n\n\ndef train_model(model,dataloaders,criterion,optimizer,scheduler,num_epochs=25):\n since = time.time()\n \n best_model_wts = model.state_dict()\n best_acc = 0.0\n \n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch,num_epochs-1))\n print('-'*10)\n \n for phase in ['train','valid']:\n if phase == 'train':\n scheduler.step()\n model.train(True)\n else:\n model.train(False)\n \n running_loss = 0.0\n running_corrects = 0\n \n for data in dataloaders[phase]:\n inputs,labels = data\n inputs,labels = Variable(inputs),Variable(labels)\n \n optimizer.zero_grad()\n \n #forward\n outputs = model(inputs)\n #_,pred = torch.max(outputs,1)\n loss = criterion(outputs,labels)\n \n if phase == 'train':\n loss.backward()\n optimizer.step()\n \n running_loss += loss.data[0]\n #running_corrects += torch.sum(pred == labels.data)\n \n epoch_loss = running_loss / dataset_sizes[phase]\n #epoch_acc = running_corrects / dataset_sizes[phase]\n \n #print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase,epoch_loss,epoch_acc))\n print('{} Loss: {:.4f}'.format(phase,epoch_loss))\n \n #if phase == 'valid' and epoch_acc > best_acc:\n # best_acc = epoch_acc\n # best_model_wts = model.state_dict()\n \n print()\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s '.format(time_elapsed//60,time_elapsed%60))\n #print('Best val Acc: {:4f}'.format(best_acc))\n #model.load_state_dict(best_model_wts)\n return model\n\n\n# In[ ]:\n\n\"\"\"\nfor epoch in range(2): # loop over the dataset multiple times\n\n running_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n # get the inputs\n inputs, labels = data\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % 2000 == 1999: # print every 2000 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n\nprint('Finished Training')\n\"\"\"\n\n# In[87]:\n\n\nclass Conv(nn.Module):\n def __init__(self,in_channels,out_channels,kernel,padding,stride):\n super(Conv,self).__init__()\n self.conv = nn.Conv2d(in_channels,out_channels,kernel_size=kernel,\n stride=stride,padding=padding,bias=False)\n self.bn = nn.BatchNorm2d(out_channels)\n self.leaky = nn.LeakyReLU(0.1, inplace = True)\n \n def forward(self,x):\n return self.leaky(self.bn(self.conv(x)))\n\nclass Conv_linear(nn.Module):\n def __init__(self,in_channels,out_channels,kernel,padding,stride):\n super(Conv_linear,self).__init__()\n self.conv = nn.Conv2d(in_channels,out_channels,kernel_size=kernel,\n stride=stride,padding=padding,bias=False)\n def forward(self,x):\n return self.conv(x) \n \nclass ResBlock(nn.Module):\n def __init__(self,channels):\n super(ResBlock,self).__init__()\n self.conv1 = Conv(channels,channels//2,kernel=(1,1),stride=1,padding=0)\n self.conv2 = Conv(channels//2,channels,kernel=(3,3),stride=1,padding=1)\n \n def forward(self,x):\n res = x\n out = self.conv1(x)\n out = self.conv2(out)\n out += x\n return out\n \nclass Flatten(nn.Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\n\n \nclass Yolo(nn.Module):\n def __init__(self,anchors):\n super(Yolo,self).__init__()\n self.conv1 = Conv(3,32,kernel=(3,3),stride=1,padding=1)\n self.conv2 = Conv(32,64,kernel=(3,3),stride=2,padding=1)\n self.res1 = ResBlock(64)\n self.conv3 = Conv(64,128,kernel=(3,3),stride=1,padding=1)\n self.res2_1 = ResBlock(128)\n self.res2_2 = ResBlock(128)\n self.conv4 = Conv(128,256,kernel=(3,3),stride=2,padding=1)\n self.res3_1 = ResBlock(256)\n self.res3_2 = ResBlock(256)\n self.res3_3 = ResBlock(256)\n self.res3_4 = ResBlock(256)\n self.res3_5 = ResBlock(256)\n self.res3_6 = ResBlock(256)\n self.res3_7 = ResBlock(256)\n self.res3_8 = ResBlock(256)\n self.conv5 = Conv(256,512,kernel=(3,3),stride=2,padding=1)\n self.res4_1 = ResBlock(512)\n self.res4_2 = ResBlock(512)\n self.res4_3 = ResBlock(512)\n self.res4_4 = ResBlock(512)\n self.res4_5 = ResBlock(512)\n self.res4_6 = ResBlock(512)\n self.res4_7 = ResBlock(512)\n self.res4_8 = ResBlock(512)\n self.conv6 = Conv(512,1024,kernel=(3,3),stride=2,padding=1)\n self.res5_1 = ResBlock(1024)\n self.res5_2 = ResBlock(1024)\n self.res5_3 = ResBlock(1024)\n self.res5_4 = ResBlock(1024)\n \n self.conv7 = Conv(1024,512,kernel=(1,1),stride=1,padding=0)\n self.conv8 = Conv(512,1024,kernel=(3,3),stride=1,padding=1)\n self.conv9 = Conv(1024,512,kernel=(1,1),stride=1,padding=0)\n self.conv10 = Conv(512,1024,kernel=(3,3),stride=1,padding=1)\n self.conv11 = Conv(1024,512,kernel=(1,1),stride=1,padding=0)\n self.conv12 = Conv(512,1024,kernel=(3,3),stride=1,padding=1)\n self.conv13 = Conv_linear(1024,5*anchors,kernel=(3,3),stride=1,padding=1)\n self.avg = nn.AvgPool2d(kernel_size=(2,2))\n \n def forward(self,x):\n out = self.conv1(x)\n out = self.conv2(out)\n out = self.res1(out) \n out = self.conv3(out)\n out = self.res2_1(out)\n out = self.res2_2(out)\n out = self.conv4(out)\n out = self.res3_1(out)\n out = self.res3_2(out)\n out = self.res3_3(out)\n out = self.res3_4(out)\n out = self.res3_5(out)\n out = self.res3_6(out)\n out = self.res3_7(out)\n out = self.res3_8(out)\n out = self.conv5(out)\n out = self.res4_1(out)\n out = self.res4_2(out)\n out = self.res4_3(out)\n out = self.res4_4(out)\n out = self.res4_5(out)\n out = self.res4_6(out)\n out = self.res4_7(out)\n out = self.res4_8(out)\n out = self.conv6(out)\n out = self.res5_1(out)\n out = self.res5_2(out)\n out = self.res5_3(out)\n out = self.res5_4(out)\n out = self.conv7(out)\n out = self.conv8(out)\n out = self.conv9(out)\n out = self.conv10(out)\n out = self.conv11(out)\n out = self.conv12(out)\n out = self.conv13(out)\n out = self.avg(out)\n return out.view(13*13*5)\n\n\n# In[88]:\n\n\"\"\"\nyolo = Yolo(anchors=1)\n\n\n# In[84]:\n\n\nimg_pil = Image.open('./img/el11.jpg')\nplt.imshow(img_pil)\n\n\n# In[89]:\n\n\nsince = time.time()\nimg = preprocess(img_pil)\nimg = Variable(img.unsqueeze_(0))\n\nout1 = yolo(img)\ntime_elapsed = time.time() - since\nprint('processed in {:.0f}m {:.0f}s '.format(time_elapsed//60,time_elapsed%60))\n\n\n# In[97]:\n\n\nprint('Out:',out1.data.size())\nel11 = open_json('./labels_json_v2/el11.json')\nel11_y = torch.Tensor(np.array(el11['y']))\nprint('El11:',el11_y.size())\n\n\nloss = nn.MSELoss(size_average=False)\noutput = Variable(out1.data)\ntarget = Variable(el11_y)\nerror = loss(output,target)\nprint('Error:',error.data.numpy())\n\nprint(el11_y[245:250],out1[245:250])\n\n\n#
\n\n#

Training\n\n# In[128]:\n\n\"\"\"\ndef get_target(img_name):\n name = img_name.split('/')[-1].split('.')[0]\n img_json = open_json('labels_json_v2/'+name+'.json')\n return torch.Tensor(np.array(img_json['y']))\n\nclass getDataset(Dataset):\n def __init__(self,img_dir,transform=None):\n self.transform = transform\n self.img_list = glob.glob(img_dir+'*')\n self.data_len = len(self.img_list)\n \n def __getitem__(self, index):\n img_name = self.img_list[index]\n img = Image.open(img_name)\n target = get_target(img_name)\n if self.transform:\n img = self.transform(img)\n return (img, target)\n\n def __len__(self):\n return self.data_len\n\n\n# In[121]:\n\n\ntrain_dataset = getDataset('Data/train/',transform=preprocess)\nval_dataset = getDataset('Data/val/',transform=preprocess)\n\ntrain_loader = DataLoader(dataset=train_dataset,batch_size=10,shuffle=False)\nval_loader = DataLoader(dataset=val_dataset,batch_size=10,shuffle=False)\ndataloaders = {'train':train_loader,'val':val_loader}\n\n\n# In[124]:\n\n\nmodel = Yolo(anchors=1)\ncriterion = nn.MSELoss(size_average=False)\noptimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\nscheduler = lr_scheduler.StepLR(optimizer, step_size=2, gamma=0.1)\n\n\n# In[129]:\n\nmodel = train_model(model,dataloaders,criterion,optimizer,scheduler,num_epochs=1)\n\n","sub_path":"YoLo/YoloV5.py","file_name":"YoloV5.py","file_ext":"py","file_size_in_byte":10482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"341438812","text":"#!/usr/bin/python2\n\nfrom calculus import *\nfrom math import *\nfrom matplotlib import pyplot\nimport pylab\nimport time\n\ndef f(x):\n\treturn 3*x*x - 2*x + 1\n\t#return pow(5, x) * log(5)\n\t#return sin(sqrt(x))/sqrt(x)\n\t#return tan(x) + pow(tan(x), 3)\n\t#return pow(e, x) * sin(x)\n\t#return sin(x)\n\t#return x * sin(2 * x)\n\t#return x * pow(e, x)\n\nprint(diff(f, 1, 10000))\n\nprint(sigma(f, 1, 100))\n\nt0 = time.time()\ns1 = integLeft(f=f, a=0, b=1, nbins=10000)\nt1 = time.time()\ns2 = integMid(f=f, a=0, b=1, nbins=10000)\nt2 = time.time()\ns3 = integTrap(f=f, a=0, b=1, nbins=10000)\nt3 = time.time()\n\nprint(\"%s %s\\n%s %s\\n%s %s\" % (s1, t1-t0, s2, t2-t1, s3, t3-t2))\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"503614978","text":"import frappe\n\nfrom frappe.desk.form import run_method\nfrom latte.json import loads\nfrom frappe import local\n\n@frappe.whitelist()\ndef runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):\n\t\"\"\"run controller method - old style\"\"\"\n\tif not args: args = arg or \"\"\n\n\tif dt: # not called from a doctype (from a page)\n\t\tif not dn: dn = dt # single\n\t\tdoc = frappe.get_doc(dt, dn)\n\n\telse:\n\t\tdoc = frappe.get_doc(loads(docs))\n\t\tdoc._original_modified = doc.modified\n\t\tdoc.check_if_latest()\n\n\tlocal.flags.current_running_method = f'{doc.__module__}.{doc.doctype}.{method}'\n\tif not doc.has_permission(\"read\"):\n\t\tfrappe.throw(\"Not permitted\", frappe.PermissionError)\n\n\tif doc:\n\t\tfrappe.response['message'] = getattr(doc, method)()\n\n\t\tfrappe.response.docs.append(doc)\n\nrun_method.runserverobj = runserverobj\n","sub_path":"latte/monkey_patches/frappe/desk/form/run_method.py","file_name":"run_method.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538577129","text":"from django.db import models\nfrom log_reg_app.models import Users\n# Create your models here.\n\nclass BooksManager(models.Manager):\n def validator(self, postData):\n errors = {}\n if len(postData['title']) == 0:\n errors['title'] = 'Please fill out the title field.'\n if len(postData['desc']) < 5:\n errors['desc'] = 'Description has to be at least 5 characters long.'\n \n return errors\n\nclass Books(models.Model):\n title = models.CharField(max_length=255)\n desc = models.TextField()\n \n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n uploaded_by = models.ForeignKey(\n Users,\n related_name=\"book_uploaded\",\n on_delete=models.CASCADE\n )\n users_who_like = models.ManyToManyField(\n Users,\n related_name=\"liked_books\"\n )\n\n objects = BooksManager()\n","sub_path":"python_stack/django/django_full_stack/fav_book_proj/fav_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"477889409","text":"'''\nthe file descriptor returns a dictionary containing username, hostname, a uuid4 string and the utc time\n'''\n\n__all__ = [\"filedescriptor\"]\n__version__ = \"0.0.1\"\n\nimport os\nimport datetime\nimport uuid\n\ndef filedescriptor():\n result = {}\n result[\"user\"] = os.getenv(\"USER\")\n result[\"host\"] = os.uname()[1]\n result[\"utc\"] = str(datetime.datetime.utcnow())\n result[\"uuid4\"] = str(uuid.uuid4())\n return result\n","sub_path":"python/biggles/_filedescriptor.py","file_name":"_filedescriptor.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168713431","text":"import config, os, json\nimport datetime\nfrom flask import render_template, request, redirect, url_for\nfrom playhouse import shortcuts\nfrom werkzeug import secure_filename\nfrom ..utilities.images import Images\nfrom ..models import *\nfrom ..utilities.decorators import noindex\n\nclass PageController():\n\tdef __init__(self):\n\t\tself._theme = Settings.select(Settings.value).where(Settings.field == 'theme').get().value\n\n\t@noindex\n\tdef all(self):\n\n\t\tobject_type = request.args.get('object-type') or 'page'\n\t\tpageheader = object_type.title() + ' Pages' if object_type != 'page' else 'Pages'\n\n\t\tpages = Pages.select().where(Pages.object_type == object_type).order_by(+Pages.title)\n\n\t\treturn render_template(\"all-pages.html\", pages=pages, object_type=object_type, pageheader=pageheader)\n\n\t@noindex\n\tdef add(self):\n\n\t\tobject_type = request.args.get('object-type') or 'page'\n\n\t\terr_return = {}\n\t\tif request.method == 'POST':\n\t\t\tif not request.form['title']:\n\t\t\t\terr_return['title'] = \"Title is required\"\n\t\t\tif not request.form['slug']:\n\t\t\t\terr_return['slug'] = \"Slug is required\"\n\t\t\tif not err_return:\n\t\t\t\t\n\t\t\t\tp = Pages(title=request.form['title'], slug=request.form['slug'], \\\n\t\t\t\t\tcontent=request.form['content'], object_type=object_type)\n\t\t\t\tp.save()\n\n\t\t\t\tfor name, v in request.form.items():\n\t\t\t\t\tif name.startswith(\"field--\"):\n\t\t\t\t\t\tname_split = name.split(\"--\")\n\t\t\t\t\t\tfield_type = name_split[1]\n\t\t\t\t\t\tfield_id = name_split[2]\n\n\t\t\t\t\t\tif v:\n\t\t\t\t\t\t\tf = Fields(page_id=p.id, field_id=field_id, field_value=v, field_type=field_type)\n\t\t\t\t\t\t\tf.save()\n\n\n\t\t\t\tn = datetime.date.today()\n\t\t\t\tyear_dir = str(n.year)\n\t\t\t\tyear_path = config.RUNT_UPLOADS + year_dir\n\t\t\t\tmonth_dir = '/' + str(format(n.month, '02d'))\n\t\t\t\tmonth_path = year_path + month_dir\n\t\t\t\trelative_path = '/uploads/' + year_dir + month_dir + '/'\n\n\t\t\t\tfor name, file in request.files.items():\n\t\t\t\t\tif name.startswith(\"field--\"):\n\t\t\t\t\t\tname_split = name.split(\"--\")\n\t\t\t\t\t\tfield_type = name_split[1]\n\t\t\t\t\t\tfield_id = name_split[2]\n\t\t\t\t\t\t\n\t\t\t\t\t\tif field_type == 'photo':\n\n\t\t\t\t\t\t\tif file and file.filename.endswith(('.jpg','.png')):\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif not os.path.exists(year_path):\n\t\t\t\t\t\t\t\t\tos.mkdir(year_path)\n\n\t\t\t\t\t\t\t\tif not os.path.exists(month_path):\n\t\t\t\t\t\t\t\t\tos.mkdir(month_path)\n\n\t\t\t\t\t\t\t\tfilename = secure_filename(file.filename)\n\n\t\t\t\t\t\t\t\tfile.save(os.path.join(month_path, filename))\n\n\t\t\t\t\t\t\t\tImages().upload_processing(month_path, filename)\n\n\t\t\t\t\t\t\t\tfield_out = relative_path + filename\n\n\t\t\t\t\t\t\telse:\n\n\t\t\t\t\t\t\t\tfield_out = file\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tf = Fields(page_id=p.id, field_id=field_id,\\\n\t\t\t\t\t\t\t\t\t\tfield_value=field_out, field_type=field_type)\n\t\t\t\t\t\t\tf.save()\n\n\t\t\t\treturn redirect(url_for('admin.edit_pages', id=p.id))\n\t\t\n\t\tfields = self._object_fields(object_type) or None\n\n\t\tpageheader = \"Add New \" + object_type.title()\n\t\t\n\t\treturn render_template(\"add-page.html\", error=err_return,\\\n\t\t\t\t\t\t\t\t object_type=object_type, fields=fields,\\\n\t\t\t\t\t\t\t\t pageheader=pageheader)\n\n\t@noindex\n\tdef edit(self, id):\n\n\t\terr_return = {}\n\t\tp = Pages.select().where(Pages.id == id)\n\n\t\tif p.exists():\n\t\t\tvalues = p.get()\n\n\t\t\tif request.method == 'POST':\n\t\t\t\tif not request.form['title']:\n\t\t\t\t\terr_return['title'] = \"Title is required\"\n\t\t\t\tif not request.form['slug']:\n\t\t\t\t\terr_return['slug'] = \"Slug is required\"\n\t\t\t\tif not err_return:\n\t\t\t\t\tp_update = Pages().update(title=request.form['title'], slug=request.form['slug'], \\\n\t\t\t\t\t\tcontent=request.form['content']).where(Pages.id == id).execute()\n\t\t\t\t\tvalues = {}\n\t\t\t\t\tvalues['title'] = request.form['title']\n\t\t\t\t\tvalues['slug'] = request.form['slug']\n\t\t\t\t\tvalues['content'] = request.form['content']\n\t\t\t\t\tvalues['id'] = id\n\n\t\t\t\t\tfor name, v in request.form.items():\n\t\t\t\t\t\tif name.startswith(\"field--\"):\n\t\t\t\t\t\t\tname_split = name.split(\"--\")\n\t\t\t\t\t\t\tfield_type = name_split[1]\n\t\t\t\t\t\t\tfield_id = name_split[2]\n\n\t\t\t\t\t\t\tif v and Fields().select().where(\n\t\t\t\t\t\t\t\t\t\t(Fields.page_id == id) & (Fields.field_id == field_id)\n\t\t\t\t\t\t\t\t\t).exists():\n\t\t\t\t\t\t\t\tf_update = Fields().update(field_value=v).where(\n\t\t\t\t\t\t\t\t\t\t\t\t(Fields.page_id == id) & (Fields.field_id == field_id)\n\t\t\t\t\t\t\t\t\t\t\t).execute()\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tf = Fields(page_id=id, field_id=field_id, field_value=v, field_type=field_type)\n\t\t\t\t\t\t\t\tf.save()\n\n\n\t\t\t\t\tn = datetime.date.today()\n\t\t\t\t\tyear_dir = str(n.year)\n\t\t\t\t\tyear_path = config.RUNT_UPLOADS + year_dir\n\t\t\t\t\tmonth_dir = '/' + str(format(n.month, '02d'))\n\t\t\t\t\tmonth_path = year_path + month_dir\n\t\t\t\t\trelative_path = '/uploads/' + year_dir + month_dir + '/'\n\n\t\t\t\t\tfor name, file in request.files.items():\n\t\t\t\t\t\tif name.startswith(\"field--\"):\n\t\t\t\t\t\t\tname_split = name.split(\"--\")\n\t\t\t\t\t\t\tfield_type = name_split[1]\n\t\t\t\t\t\t\tfield_id = name_split[2]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif field_type == 'photo':\n\n\t\t\t\t\t\t\t\tif file and file.filename.endswith(('.jpg','.png')):\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif not os.path.exists(year_path):\n\t\t\t\t\t\t\t\t\t\tos.mkdir(year_path)\n\n\t\t\t\t\t\t\t\t\tif not os.path.exists(month_path):\n\t\t\t\t\t\t\t\t\t\tos.mkdir(month_path)\n\n\t\t\t\t\t\t\t\t\tfilename = secure_filename(file.filename)\n\n\t\t\t\t\t\t\t\t\tfile.save(os.path.join(month_path, filename))\n\n\t\t\t\t\t\t\t\t\tImages().upload_processing(month_path, filename)\n\n\t\t\t\t\t\t\t\t\tfield_out = relative_path + filename\n\n\t\t\t\t\t\t\t\telse:\n\n\t\t\t\t\t\t\t\t\tfield_out = file\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif Fields().select().where(\n\t\t\t\t\t\t\t\t\t\t(Fields.page_id == id) & (Fields.field_id == field_id)\n\t\t\t\t\t\t\t\t\t).exists():\n\n\t\t\t\t\t\t\t\t\tf_update = Fields().update(field_value=field_out).where(\n\t\t\t\t\t\t\t\t\t\t\t\t(Fields.page_id == id) & (Fields.field_id == field_id)\n\t\t\t\t\t\t\t\t\t\t\t).execute()\n\n\t\t\t\t\t\t\t\telse:\n\n\t\t\t\t\t\t\t\t\tf = Fields(page_id=id, field_id=field_id,\\\n\t\t\t\t\t\t\t\t\t\t\t\tfield_value=field_out, field_type=field_type)\n\t\t\t\t\t\t\t\t\tf.save()\n\n\t\t\t\t\treturn redirect(url_for('admin.edit_pages', id=id))\n\n\t\t\tobject_type = p.get().object_type\n\t\t\tfields = self._object_fields(object_type) or None\n\n\t\t\tallf = Fields.select().where(Fields.page_id == id)\n\t\t\t\n\t\t\tfor a in allf:\n\t\t\t\tif a.field_value:\n\t\t\t\t\tfields[a.field_id]['value'] = a.field_value\n\n\n\t\t\treturn render_template(\"edit-page.html\", values=values,\\\n\t\t\t\t\t\t\t\t\t\terror=err_return, object_type=object_type,\\\n\t\t\t\t\t\t\t\t\t\tfields=fields)\n\n\t\treturn '404 page'\n\n\tdef _object_fields(self, obj):\n\n\t\tfields = {}\n\n\t\tobjects_json = config.ROOT_DIR + '/themes/' + self._theme + '/objects.json'\n\t\t\n\t\tif os.path.exists(objects_json):\n\n\t\t\twith open(objects_json, \"r\") as oj:\n\t\t\t\n\t\t\t\t\"\"\" BROKEN FOR PAGES \"\"\"\n\n\t\t\t\t_o_decode = json.loads(oj.read())\n\n\t\t\t\tif obj in _o_decode and 'fields' in _o_decode[obj]:\n\t\t\t\t\t\n\t\t\t\t\tfields = _o_decode[obj]['fields']\n\t\t\t\t\t\n\t\t\t\t\tfor _k, _v in fields.items():\n\t\t\t\t\t\t\n\t\t\t\t\t\tif _v['type'] == 'cross_object' and 'object' in _v:\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t_p_o = Pages.select().where(Pages.object_type == _v['object'])\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t_temp_o = {}\n\n\t\t\t\t\t\t\tfor _p in _p_o:\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t_temp_o[_p.id] = _p.title\n\n\t\t\t\t\t\t\tfields[_k]['object_items'] = _temp_o\n\n\t\t\treturn fields\n\n\t\treturn False\n\n\t\n\n","sub_path":"runt/controllers/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":6788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354010372","text":"import socket, os, json, time\nfrom six.moves.urllib.parse import urlparse\n\ndef is_open(ip, port, timeout=30):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(timeout)\n try:\n s.connect((ip, int(port)))\n s.shutdown(socket.SHUT_RDWR)\n return True\n except:\n return False\n finally:\n s.close()\n\ndef check_host(ip, port, retry=10, delay=3):\n ipup = False\n for i in range(retry):\n print(\"Attempt {i} to connect to {ip}:{port}\".format(ip=ip,port=port,i=i+1))\n if is_open(ip, port):\n ipup = True\n break\n else:\n time.sleep(delay)\n return ipup\n\n# Check connection to servers\nconfig = None\ntry:\n with open('common_site_config.json') as config_file:\n config = json.load(config_file)\nexcept FileNotFoundError:\n raise FileNotFoundError(\"common_site_config.json missing\")\nexcept:\n raise ValueError(\"common_site_config.json is not valid\")\n\n# Check mariadb\ncheck_mariadb = False\ncheck_mariadb = check_host(config.get('db_host', 'mariadb'), 3306)\nif not check_mariadb:\n raise ConnectionError(\"Connection to mariadb timed out\")\n\n# Check redis queue\ncheck_redis_queue = False\nredis_queue_url = urlparse(config.get(\"redis_queue\",\"redis://redis:6379\")).netloc\nredis_queue, redis_queue_port = redis_queue_url.split(\":\")\ncheck_redis_queue = check_host(redis_queue, redis_queue_port)\nif not check_redis_queue:\n raise ConnectionError(\"Connection to redis queue timed out\")\n\n# Check redis cache\ncheck_redis_cache = False\nredis_cache_url = urlparse(config.get(\"redis_cache\",\"redis://redis:6379\")).netloc\nredis_cache, redis_cache_port = redis_cache_url.split(\":\")\ncheck_redis_cache = check_host(redis_cache, redis_cache_port)\nif not check_redis_cache:\n raise ConnectionError(\"Connection to redis cache timed out\")\n\n# Check redis socketio\ncheck_redis_socketio = False\nredis_socketio_url = urlparse(config.get(\"redis_socketio\",\"redis://redis:6379\")).netloc\nredis_socketio, redis_socketio_port = redis_socketio_url.split(\":\")\ncheck_redis_socketio = check_host(redis_socketio, redis_socketio_port)\nif not check_redis_socketio:\n raise ConnectionError(\"Connection to redis socketio timed out\")\n\nprint('Connections OK')\n","sub_path":"build/common/commands/check_connection.py","file_name":"check_connection.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496782","text":"#\n# Utilities for converting morph analyses from \n# the UniversalDependencies (UD) format to a \n# reduced Vabamorf's format\n#\n\nimport os, os.path, re\nfrom collections import defaultdict\nfrom collections import OrderedDict\n\nfrom estnltk.text import Text\nfrom estnltk.layer.layer import Layer\nfrom estnltk.layer.annotation import Annotation\n\n# =================================================\n# =================================================\n# Convert UD annotations to reduced \n# Vabamorf's annotations\n# =================================================\n# =================================================\n\ndef convert_ud_layer_to_reduced_morph_layer( text_obj, ud_layer, output_layer, add_layer=True ):\n '''Creates a reduced version of the UD layer which consists only of morph_analysis. \n The reduced morph layer contains attributes 'lemma', 'pos' and 'form',\n and it uses Vabamorf's morphological categories.\n '''\n assert isinstance(text_obj, Text)\n assert ud_layer in text_obj.layers, \\\n '(!) Layer {!r} missing from: {!r}'.format(ud_layer, text_obj.layers)\n redux_layer = Layer(name=output_layer, \\\n attributes=('lemma', 'pos', 'form'), \\\n text_object=text_obj,\\\n ambiguous=True)\n for ud_word in text_obj[ ud_layer ]:\n for ann in ud_word.annotations:\n attribs = parse_ud_morph_redux_attribs( ann )\n redux_layer.add_annotation( ud_word.base_span, **attribs )\n pass\n if add_layer:\n text_obj.add_layer( redux_layer )\n return redux_layer\n\n\ndef _split_feats( morph_form_feats ):\n '''Creates a dictionary based on UD's \"feats\" attribute.'''\n if morph_form_feats is None or len(morph_form_feats) == 0:\n return {}\n feat_chunks = morph_form_feats.split('|')\n feat_chunks_split = [chunk.split('=') for chunk in feat_chunks]\n feats = {kv[0]:kv[1] for kv in feat_chunks_split if len(kv) == 2}\n return feats\n\n\ndef _clean_lemma( lemma ):\n '''Removes '=' symbols from lemma if they appear between letters.'''\n new_lemma = []\n for i in range(len(lemma)):\n last_c = lemma[i-1] if i-1>-1 else ''\n c = lemma[i]\n next_c = lemma[i+1] if i+1 'sg ill' or 'adt'\n # ud_case == 'Add' --> 'sg ill' or 'adt'\n # TODO: do we need to generate several variants here?\n # \n # ... All the dance with the verbs ...\n if ud_xpos == 'V':\n # Get UD's category values\n ud_verb_form = ud_feats.get('VerbForm', None) # Fin, Inf, Part, Sup, Conv\n ud_voice = ud_feats.get('Voice', None) # Act, Pass\n ud_mood = ud_feats.get('Mood', None) # Ind, Imp, Cnd, Qou\n ud_case = ud_feats.get('Case', None) # Ill, Ine, Ela, Tra, Abe\n ud_number = ud_feats.get('Number', None) # Plur, Sing\n ud_person = ud_feats.get('Person', None) # 1, 2, 3\n ud_tense = ud_feats.get('Tense', None) # Past, Pres\n ud_polarity = ud_feats.get('Polarity', None) # Neg\n ud_connegative = ud_feats.get('Connegative', None) # Yes\n assert not (ud_xpos == 'V' and ud_case != None and ud_number != None), \\\n '(!) There should be no such verb: {!r}!'.format( ud_annotation )\n #\n # For an overview of Vabamorf's verb categories, \n # see: http://www.filosoft.ee/html_morf_et/morfoutinfo.html#4\n #\n # V1) Infinite forms\n # pure infinite\n if ud_verb_form == 'Inf':\n attribs['form'] = 'da'\n # supine personal\n if ud_verb_form == 'Sup' and ud_voice == 'Act':\n if ud_case == 'Ill':\n attribs['form'] = 'ma'\n if ud_case == 'Ine':\n attribs['form'] = 'mas'\n if ud_case == 'Ela':\n attribs['form'] = 'mast'\n if ud_case == 'Tra':\n attribs['form'] = 'maks'\n if ud_case == 'Abe':\n attribs['form'] = 'mata'\n # supine impersonal\n if ud_verb_form == 'Sup' and ud_voice == 'Pass':\n attribs['form'] = 'tama'\n # nud/tud\n if ud_verb_form == 'Part' and ud_tense == 'Past':\n if ud_voice == 'Act':\n attribs['form'] = 'nud'\n if ud_voice == 'Pass':\n attribs['form'] = 'tud'\n # ger\n if ud_verb_form == 'Conv':\n attribs['form'] = 'des'\n # V2) Negatives:\n if ud_polarity == 'Neg' or ud_connegative == 'Yes':\n # neg auxiliary\n if ud_upos == 'AUX' and ud_lemma in ['ära', 'ei']:\n attribs['form'] = 'neg'\n # neg personal \n if ud_voice == 'Act':\n # # Ind, Imp, Cnd, Qou\n if ud_mood == 'Ind' and ud_tense == 'Pres':\n # (!) Ambiguity: vm_form in ['o', 'neg o']\n attribs['form'] = 'neg o'\n if ud_mood == 'Imp' and ud_tense == 'Pres' and ud_person == '2' and ud_number == 'Sing':\n attribs['form'] = 'o'\n if ud_mood == 'Imp' and ud_tense == 'Pres' and ud_person == '2' and ud_number == 'Plur':\n attribs['form'] = 'neg ge'\n if ud_mood == 'Imp' and ud_tense == 'Pres' and ud_person == '3' and ud_number == 'Plur':\n attribs['form'] = 'neg gu'\n if ud_mood == 'Ind' and ud_tense == 'Past':\n # (!) Ambiguity: vm_form in ['nud', 'neg nud']\n attribs['form'] = 'neg nud'\n if ud_mood == 'Cnd' and ud_tense == 'Pres':\n # (!) Ambiguity: vm_form in ['ks', 'neg ks']\n attribs['form'] = 'neg ks'\n # neg impersonal \n if ud_voice == 'Pass':\n if ud_mood == 'Ind' and ud_tense == 'Pres':\n attribs['form'] = 'ta'\n ud_affirmative = (not ud_polarity == 'Neg') and (not ud_connegative == 'Yes')\n # V3) Indicative, affirmative\n if ud_affirmative and ud_mood == 'Ind':\n # Present tense\n if ud_number == 'Sing' and ud_tense == 'Pres' and ud_person == '1':\n attribs['form'] = 'n'\n if ud_number == 'Plur' and ud_tense == 'Pres' and ud_person == '1':\n attribs['form'] = 'me'\n if ud_number == 'Sing' and ud_tense == 'Pres' and ud_person == '2':\n attribs['form'] = 'd'\n if ud_number == 'Plur' and ud_tense == 'Pres' and ud_person == '2':\n attribs['form'] = 'te'\n if ud_number == 'Sing' and ud_tense == 'Pres' and ud_person == '3':\n attribs['form'] = 'b'\n if ud_number == 'Plur' and ud_tense == 'Pres' and ud_person == '3':\n attribs['form'] = 'vad'\n if ud_voice == 'Pass' and ud_tense == 'Pres' and ud_person == None:\n # Passive voice\n attribs['form'] = 'takse'\n # Past tense\n if ud_number == 'Sing' and ud_tense == 'Past' and ud_person == '1':\n attribs['form'] = 'sin'\n if ud_number == 'Plur' and ud_tense == 'Past' and ud_person == '1':\n attribs['form'] = 'sime'\n if ud_number == 'Sing' and ud_tense == 'Past' and ud_person == '2':\n attribs['form'] = 'sid'\n if ud_number == 'Plur' and ud_tense == 'Past' and ud_person == '2':\n attribs['form'] = 'site'\n if ud_number == 'Sing' and ud_tense == 'Past' and ud_person == '3':\n attribs['form'] = 's'\n if ud_number == 'Plur' and ud_tense == 'Past' and ud_person == '3':\n attribs['form'] = 'sid'\n if ud_voice == 'Pass' and ud_tense == 'Past' and ud_person == None:\n # Passive voice\n attribs['form'] = 'ti'\n # V4) Imperative, affirmative\n if ud_affirmative and ud_mood == 'Imp':\n if ud_number == 'Sing' and ud_tense == 'Pres' and ud_person == None and ud_voice == 'Act':\n attribs['form'] = 'gu'\n if ud_number == 'Sing' and ud_tense == 'Pres' and ud_person == '2' and ud_voice == 'Act':\n attribs['form'] = 'o'\n if ud_number == 'Sing' and ud_tense == 'Pres' and ud_person == '3' and ud_voice == 'Act':\n attribs['form'] = 'gu'\n if ud_number == 'Plur' and ud_tense == 'Pres' and ud_person == '1' and ud_voice == 'Act':\n attribs['form'] = 'gem'\n if ud_number == 'Plur' and ud_tense == 'Pres' and ud_person == '2' and ud_voice == 'Act':\n attribs['form'] = 'ge'\n if ud_number == 'Plur' and ud_tense == 'Pres' and ud_person == '3' and ud_voice == 'Act':\n attribs['form'] = 'gu'\n # V5) Quotative, affirmative\n if ud_affirmative and ud_mood == 'Qot':\n if ud_tense == 'Pres' and ud_voice == 'Act':\n attribs['form'] = 'vat'\n if ud_tense == 'Pres' and ud_voice == 'Pass':\n attribs['form'] = 'tavat'\n # V6) Conditional, affirmative\n if ud_affirmative and ud_mood == 'Cnd':\n # Present tense\n if ud_tense == 'Pres' and ud_voice == 'Act' and ud_number == 'Sing' and ud_person == '1':\n # (!) Ambiguity: vm_form in ['ksin', 'ks']\n attribs['form'] = 'ksin'\n if ud_tense == 'Pres' and ud_voice == 'Act' and ud_number == 'Sing' and ud_person == '2':\n # (!) Ambiguity: vm_form in ['ksid', 'ks']\n attribs['form'] = 'ksid'\n if ud_tense == 'Pres' and ud_voice == 'Act' and ud_number == 'Sing' and ud_person == '3':\n attribs['form'] = 'ks'\n if ud_tense == 'Pres' and ud_voice == 'Act' and ud_number == 'Plur' and ud_person == '1':\n # (!) Ambiguity: vm_form in ['ksime', 'ks']\n attribs['form'] = 'ksime'\n if ud_tense == 'Pres' and ud_voice == 'Act' and ud_number == 'Plur' and ud_person == '2':\n # (!) Ambiguity: vm_form in ['ksite', 'ks']\n attribs['form'] = 'ksite'\n if ud_tense == 'Pres' and ud_voice == 'Act' and ud_number == 'Plur' and ud_person == '3':\n # (!) Ambiguity: vm_form in ['ksid', 'ks']\n attribs['form'] = 'ksid'\n if ud_voice == 'Act' and ud_tense == 'Pres' and ud_person == None:\n attribs['form'] = 'ks'\n # Past tense\n if ud_tense == 'Past' and ud_voice == 'Act' and ud_number == 'Sing' and ud_person == '1':\n # (!) Ambiguity: vm_form in ['nuksin', 'nuks']\n attribs['form'] = 'nuksin'\n if ud_tense == 'Past' and ud_voice == 'Act' and ud_number == 'Sing' and ud_person == '2':\n # (!) Ambiguity: vm_form in ['nuksid', 'nuks']\n attribs['form'] = 'nuksid'\n if ud_tense == 'Past' and ud_voice == 'Act' and ud_number == 'Sing' and ud_person == '3':\n attribs['form'] = 'nuks'\n if ud_tense == 'Past' and ud_voice == 'Act' and ud_number == 'Plur' and ud_person == '1':\n # (!) Ambiguity: vm_form in ['nuksime', 'nuks']\n attribs['form'] = 'nuksime'\n if ud_tense == 'Past' and ud_voice == 'Act' and ud_number == 'Plur' and ud_person == '2':\n # (!) Ambiguity: vm_form in ['nuksite', 'nuks']\n attribs['form'] = 'nuksite'\n if ud_tense == 'Past' and ud_voice == 'Act' and ud_number == 'Plur' and ud_person == '3':\n # (!) Ambiguity: vm_form in ['nuksid', 'nuks']\n attribs['form'] = 'nuksid'\n if ud_mood == 'Cnd' and ud_tense == 'Pres' and ud_voice == 'Pass' and ud_number == None and ud_person == None:\n # Conditional impersonal\n attribs['form'] = 'taks'\n return attribs\n\n\n","sub_path":"est_ud_morph_conv.py","file_name":"est_ud_morph_conv.py","file_ext":"py","file_size_in_byte":16005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468437256","text":"# import csv\n# with open(\"csv_read.csv\") as file1:\n# read=csv.reader(file1)\n# for i in read:\n# print(i)\n#\n# with open(\"csv_write.csv\",'w') as file2:\n# write=csv.writer(file2,delimiter=',')\n# write.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])\n\n# import csv\n# with open(\"csv_read.csv\") as file3:\n# dictread=csv.DictReader(file3)\n# for i in dictread:\n# print(i)\n\nimport csv\nwith open('csv_write_dict.csv','w') as file4:\n fieldname=['first_name','last_name']\n writer=csv.DictWriter(file4,fieldnames=fieldname)\n writer.writeheader()\n writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})\n writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})\n writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})\n","sub_path":"python_practice/csv_practice.py","file_name":"csv_practice.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"23424778","text":"class Contact(object):\n\tdef __init__(self, name, phone, email, address=None):\n\t\tself.name = name\n\t\tself.phone = phone\n\t\tself.email = email\n\t\tself.address = address\nclass AddressBook(object):\n\tdef __init__(self, owner):\n\t\tself.owner = owner\n\t\tself.contact_list = []\n\tdef add_contact(self):\n\t\tnew_contact_name = raw_input(\"what is their name?\")\n\t\tnew_contact_phone = raw_input(\"what is their number?\")\n\t\tnew_contact_email = raw_input(\"what is their email?\")\n\t\tnew_contact_address = raw_input(\"what is their address (optional)?\")\n\t\tnew_contact = Contact(new_contact_name, new_contact_phone, new_contact_email, new_contact_address)\n\t\tself.contact_list.append(new_contact)\n\n\n\n\t# \"\"\"\n\t# list of contacts\n\t# sorting?\n\t# view\n\t# add\n\t# delete\n\t# edit\n\t# \"\"\"","sub_path":"like/icecream/yoyo/address_book_w_class.py","file_name":"address_book_w_class.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"212606122","text":"\ndef supp_doublon(liste):\n nouvelle_liste = []\n for element in liste:\n if element not in nouvelle_liste:\n nouvelle_liste.append(element)\n return nouvelle_liste\n\n\nprint(\"Entrez des valeurs. Appuyez sur Entrée pour terminer\")\n\nliste_valeurs = []\nnb_elements = 0\n\nwhile True:\n valeur = input(\"Saisir une valeur : \")\n if valeur:\n try:\n liste_valeurs.append(int(valeur))\n nb_elements += 1\n except:\n continue\n else:\n break\nprint(\"Valeurs entrées : \", liste_valeurs)\nprint(\"Nombre d'éléments de la liste : \", nb_elements)\nprint(\"La nouvelle liste est : \", supp_doublon(liste_valeurs))","sub_path":"Exercices Python/Exercices apcpedagogie YTB/supprimer_éléments_dupl.py","file_name":"supprimer_éléments_dupl.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"158999756","text":"import unittest\nimport json\nimport sys\nimport copy\nsys.path.append('../rss_reader')\nfrom NewsCache import NewsCache\n\nTEST_NEWS_LIST = [\n {\"Title\": \"Air racing tournament unveils an all-electric sports aircraft\",\n \"Date\": \"Sun, 17 Nov 2019 15:35:00 -0500\",\n \"Link\": \"link\",\n \"Summary\": \"Test text\",\n \"Source of image\": \"img_link\",\n \"Date key\": \"20191117\"}]\n\nFILE_CONTENTS = {\"20191117\":\n {\"https://www.engadget.com/rss.xml\":\n {\"Air racing tournament unveils an all-electric sports aircraft\":\n {\"Title\": \"Air racing tournament unveils an all-electric sports aircraft\",\n \"Date\": \"Sun, 17 Nov 2019 15:35:00 -0500\",\n \"Link\": \"link\",\n \"Summary\": \"Test text\",\n \"Source of image\": \"img_link\"}}}}\n\n\nclass NewsCacheTestCase(unittest.TestCase):\n\n def setUp(self):\n self.cache = NewsCache('Test_file.json')\n test_news = copy.deepcopy(TEST_NEWS_LIST)\n self.cache.caching(test_news, 'https://www.engadget.com/rss.xml')\n\n def test_caching(self):\n with open('Test_file.json', \"r\") as test_json:\n content = test_json.read()\n self.assertEqual(json.loads(content), FILE_CONTENTS)\n self.assertEqual(json.loads(content).get('20191117'), FILE_CONTENTS['20191117'])\n\n def test_returning(self):\n result = self.cache.returning('20191117', 'https://www.engadget.com/rss.xml')\n self.assertEqual(result[0].get('Title'), \"Air racing tournament unveils an all-electric sports aircraft\")\n self.assertEqual(result[0].get('Date'), \"Sun, 17 Nov 2019 15:35:00 -0500\")\n self.assertEqual(result[0].get('Link'), \"link\")\n self.assertEqual(result[0].get('Summary'), \"Test text\")\n self.assertEqual(result[0].get('Source of image'), \"img_link\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"final_task/tests/NewsCache_test.py","file_name":"NewsCache_test.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"373673696","text":"import sys\n\nsys.path.append('.')\nimport my_helper_functions as mhf\nfrom qlearning_dataset_with_mc_return import qlearning_dataset_with_mc_return\nfrom qlearning_dataset_with_next_action import qlearning_dataset_wonjoon, qlearning_dataset_with_next_action_v0, qlearning_dataset_with_next_action_v2\n\nsys.path.append('cql/d4rl')\n\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.data_management.env_replay_buffer import EnvReplayBuffer\nfrom rlkit.data_management.env_replay_buffer_with_return import EnvReplayBufferWithReturn\nfrom rlkit.data_management.env_replay_buffer_with_next_action import EnvReplayBufferWithNextAction\nfrom rlkit.envs.wrappers import NormalizedBoxEnv\nfrom rlkit.launchers.launcher_util import setup_logger\nfrom rlkit.samplers.data_collector import MdpPathCollector, CustomMDPPathCollector\nfrom rlkit.torch.sac.policies import TanhGaussianPolicy, MakeDeterministic\nfrom rlkit.torch.sac.cql import CQLTrainer\nfrom rlkit.torch.networks import FlattenMlp\nfrom rlkit.torch.torch_rl_algorithm import TorchBatchRLAlgorithm\n\nimport argparse, os\nimport numpy as np\nimport torch\n\nimport h5py\nimport d4rl, gym\n\nimport shutil\n\n\ndef load_hdf5(dataset, replay_buffer):\n replay_buffer._observations = dataset['observations']\n replay_buffer._next_obs = dataset['next_observations']\n replay_buffer._actions = dataset['actions']\n replay_buffer._rewards = np.expand_dims(np.squeeze(dataset['rewards']), 1)\n replay_buffer._terminals = np.expand_dims(np.squeeze(dataset['terminals']), 1) \n replay_buffer._size = dataset['terminals'].shape[0]\n print ('Number of terminals on: ', replay_buffer._terminals.sum())\n replay_buffer._top = replay_buffer._size\n\n\ndef load_hdf5_with_mc_return(dataset, replay_buffer):\n replay_buffer._observations = dataset['observations']\n replay_buffer._next_obs = dataset['next_observations']\n replay_buffer._actions = dataset['actions']\n replay_buffer._rewards = np.expand_dims(np.squeeze(dataset['rewards']), 1)\n replay_buffer._terminals = np.expand_dims(np.squeeze(dataset['terminals']), 1) \n replay_buffer._mc_returns = np.expand_dims(np.squeeze(dataset['mc_returns']), 1)\n replay_buffer._size = dataset['terminals'].shape[0]\n print ('Number of terminals on: ', replay_buffer._terminals.sum())\n replay_buffer._top = replay_buffer._size\n\n\ndef load_hdf5_with_next_action(dataset, replay_buffer):\n replay_buffer._observations = dataset['observations']\n replay_buffer._next_obs = dataset['next_observations']\n replay_buffer._actions = dataset['actions']\n replay_buffer._rewards = np.expand_dims(np.squeeze(dataset['rewards']), 1)\n replay_buffer._terminals = np.expand_dims(np.squeeze(dataset['terminals']), 1)\n replay_buffer._next_actions = dataset['next_actions']\n replay_buffer._size = dataset['terminals'].shape[0]\n print('Number of terminals on: ', replay_buffer._terminals.sum())\n replay_buffer._top = replay_buffer._size\n\n \ndef experiment(variant):\n eval_env = gym.make(variant['env_name'])\n expl_env = eval_env\n \n obs_dim = expl_env.observation_space.low.size\n action_dim = eval_env.action_space.low.size\n\n M = variant['layer_size']\n qf1 = FlattenMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[M, M, M],\n )\n qf2 = FlattenMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[M, M, M],\n )\n target_qf1 = FlattenMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[M, M, M],\n )\n target_qf2 = FlattenMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[M, M, M],\n )\n policy = TanhGaussianPolicy(\n obs_dim=obs_dim,\n action_dim=action_dim,\n hidden_sizes=[M, M, M], \n )\n eval_policy = MakeDeterministic(policy)\n eval_path_collector = MdpPathCollector(\n eval_env,\n eval_policy,\n )\n expl_path_collector = CustomMDPPathCollector(\n eval_env,\n )\n buffer_filename = None\n if variant['buffer_filename'] is not None:\n buffer_filename = variant['buffer_filename']\n\n # =========================================================\n # different dataset modifications\n \n if variant['use_sil']:\n\n print('Internal report: loading data for CQL SIL')\n\n replay_buffer = EnvReplayBufferWithReturn(\n variant['replay_buffer_size'],\n expl_env,\n )\n \n load_hdf5_with_mc_return(qlearning_dataset_with_mc_return(eval_env), replay_buffer)\n\n elif variant['cql_beta']:\n\n if variant['env_name'].endswith('v0'):\n\n print('Internal report: Loading data for CQL beta v0')\n\n replay_buffer = EnvReplayBufferWithNextAction(\n variant['replay_buffer_size'],\n expl_env,\n )\n\n load_hdf5_with_next_action(qlearning_dataset_with_next_action_v0(variant['env_name']), replay_buffer)\n\n elif variant['env_name'].endswith('v2'):\n\n print('Internal report: Loading data for CQL beta v2')\n\n replay_buffer = EnvReplayBufferWithNextAction(\n variant['replay_buffer_size'],\n expl_env,\n )\n\n load_hdf5_with_next_action(qlearning_dataset_with_next_action_v2(variant['env_name']), replay_buffer)\n\n else:\n\n raise NotImplementedError\n\n elif variant['cql_original']:\n\n print('Internal report: Loading data for CQL original')\n\n replay_buffer = EnvReplayBuffer(\n variant['replay_buffer_size'],\n expl_env,\n )\n\n if variant['load_buffer'] and buffer_filename is not None:\n replay_buffer.load_buffer(buffer_filename)\n elif 'random-expert' in variant['env_name']:\n load_hdf5(d4rl.basic_dataset(eval_env), replay_buffer)\n else:\n load_hdf5(d4rl.qlearning_dataset(eval_env), replay_buffer)\n\n else:\n\n replay_buffer = EnvReplayBuffer(\n variant['replay_buffer_size'],\n expl_env,\n )\n\n load_hdf5(qlearning_dataset_wonjoon(variant['env_name']), replay_buffer)\n\n # =========================================================\n \n trainer = CQLTrainer(\n env=eval_env,\n policy=policy,\n qf1=qf1,\n qf2=qf2,\n target_qf1=target_qf1,\n target_qf2=target_qf2,\n **variant['trainer_kwargs']\n )\n algorithm = TorchBatchRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n eval_both=False, # added/modified by Zhihan\n batch_rl=variant['load_buffer'],\n **variant['algorithm_kwargs']\n )\n algorithm.to(ptu.device)\n algorithm.train()\n\n print('Saving networks.')\n\n DIR = variant['model_save_dir']\n torch.save(policy.state_dict(), os.path.join(DIR, 'policy.pth'))\n torch.save(qf1.state_dict(), os.path.join(DIR, 'qf1.pth'))\n torch.save(qf2.state_dict(), os.path.join(DIR, 'qf2.pth'))\n\n print('Done saving networks.')\n\ndef enable_gpus(gpu_str):\n if (gpu_str is not \"\"):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = gpu_str\n return\n\nif __name__ == \"__main__\":\n # noinspection PyTypeChecker\n variant = dict(\n algorithm=\"CQL\",\n version=\"normal\",\n layer_size=256,\n replay_buffer_size=int(2E6),\n buffer_filename=None,\n load_buffer=None,\n env_name='Hopper-v2',\n sparse_reward=False,\n use_sil=False, # added for the new SIL idea; default to be false\n algorithm_kwargs=dict(\n num_epochs=300,\n num_eval_steps_per_epoch=1000,\n num_trains_per_train_loop=1000, \n num_expl_steps_per_train_loop=1000,\n min_num_steps_before_training=1000,\n max_path_length=1000,\n batch_size=256,\n ),\n trainer_kwargs=dict(\n discount=0.99,\n soft_target_tau=5e-3,\n policy_lr=1E-4,\n qf_lr=3E-4,\n reward_scale=1,\n use_automatic_entropy_tuning=True,\n\n # Target nets/ policy vs Q-function update\n policy_eval_start=40000,\n num_qs=2,\n\n # min Q\n temp=1.0,\n min_q_version=3,\n min_q_weight=1.0,\n\n # lagrange\n with_lagrange=True, # Defaults to true\n lagrange_thresh=10.0,\n \n # extra params\n num_random=10,\n max_q_backup=False,\n deterministic_backup=False,\n ),\n )\n\n # added/modified by Zhihan\n\n # Arguments that should be specified\n # env\n\n # According to instructions in the codebase, for Gym Mujoco tasks, we should use:\n # min_q_weight: 5.0 (different from default)\n # lagrange_thresh: -1.0 (different from default)\n # policy_lr: 1e-4\n\n # Variants:\n # min_q_version: 3 (CQL(H) default) vs 2 (CQL(rho))\n\n # For convenience, we should use\n # seed: 10 -> 0 (different from default)\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--env\", type=str, default='hopper-medium-v0')\n parser.add_argument(\"--gpu\", default='0', type=str)\n parser.add_argument(\"--max_q_backup\", type=str, default=\"False\") # if we want to try max_{a'} backups, set this to true\n parser.add_argument(\"--deterministic_backup\", type=str, default=\"True\") # defaults to true, it does not backup entropy in the Q-function, as per Equation 3\n parser.add_argument(\"--policy_eval_start\", default=10000, type=int) # Defaulted to 20000 (40000 or 10000 work similarly)\n parser.add_argument('--min_q_weight', default=1.0, type=float) # the value of alpha, set to 5.0 or 10.0 if not using lagrange\n parser.add_argument('--policy_lr', default=1e-4, type=float) # Policy learning rate\n parser.add_argument('--min_q_version', default=3, type=int) # min_q_version = 3 (CQL(H)), version = 2 (CQL(rho)) \n parser.add_argument('--lagrange_thresh', default=5.0, type=float) # the value of tau, corresponds to the CQL(lagrange) version\n parser.add_argument('--seed', default=10, type=int)\n parser.add_argument('--use_sil', default='False', type=str) # added for the new idea\n parser.add_argument('--cql_beta', default='False', type=str) # added for the new idea\n parser.add_argument('--cql_original', default='False', type=str)\n\n args = parser.parse_args()\n enable_gpus(args.gpu)\n \n variant['use_sil'] = (True if args.use_sil == 'True' else False)\n variant['cql_beta'] = (True if args.cql_beta == 'True' else False)\n variant['cql_original'] = (True if args.cql_original == 'True' else False)\n\n assert not (variant['use_sil'] and variant['cql_beta']), \"can't use these two together at this point\"\n \n variant['trainer_kwargs']['max_q_backup'] = (True if args.max_q_backup == 'True' else False)\n variant['trainer_kwargs']['deterministic_backup'] = (True if args.deterministic_backup == 'True' else False)\n variant['trainer_kwargs']['min_q_weight'] = args.min_q_weight\n variant['trainer_kwargs']['policy_lr'] = args.policy_lr\n variant['trainer_kwargs']['min_q_version'] = args.min_q_version\n variant['trainer_kwargs']['policy_eval_start'] = args.policy_eval_start\n variant['trainer_kwargs']['lagrange_thresh'] = args.lagrange_thresh\n if args.lagrange_thresh < 0.0:\n variant['trainer_kwargs']['with_lagrange'] = False\n \n variant['buffer_filename'] = None\n\n variant['load_buffer'] = True\n variant['env_name'] = args.env\n variant['seed'] = args.seed\n\n # added/modified by Zhihan: use entire buffer\n variant['replay_buffer_size'] = mhf.get_dataset_size(args.env)\n\n # added/modified by Zhihan: use 1M grad steps, report avg return across 10 episodes per 10K grad steps\n variant['algorithm_kwargs']['num_epochs'] = 100\n variant['algorithm_kwargs']['num_trains_per_train_loop'] = int(5e3)\n variant['algorithm_kwargs']['num_eval_steps_per_epoch'] = 10 * variant['algorithm_kwargs']['max_path_length']\n\n print('Epochs:', variant['algorithm_kwargs']['num_epochs'])\n print('Num trains per epoch:', variant['algorithm_kwargs']['num_trains_per_train_loop'])\n\n # added/modified by Zhihan: convenient log dir\n\n algo_name = 'CQL'\n if variant['use_sil']:\n algo_name += '_SIL'\n elif variant['cql_beta']:\n algo_name += '_BETA'\n elif variant['cql_original']:\n algo_name += '_ORIGINAL'\n elif (not variant['use_sil']) and (not variant['cql_beta']) and (not variant['cql_original']):\n pass # just use default algo_name\n else:\n raise NotImplementedError # prevent invalid algo_name\n\n log_dir = mhf.get_log_dir(\n base_dir='results',\n algo_dir=algo_name,\n env_dir=args.env,\n seed_dir=args.seed\n )\n\n print('Log dir:', log_dir)\n\n shutil.rmtree(log_dir, ignore_errors=True) # overwrite any previous stuff written in here by deleting the directory\n # later on setup_logger would re-create it anyway\n\n setup_logger(\n log_dir=log_dir,\n )\n\n variant['model_save_dir'] = log_dir\n\n ptu.set_gpu_mode(True)\n experiment(variant)\n","sub_path":"cql/d4rl/examples/cql_mujoco_new.py","file_name":"cql_mujoco_new.py","file_ext":"py","file_size_in_byte":13386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"298631169","text":"class TreeNode(object):\n def __init__(self, val = 0, left=None,right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution(object):\n # Recursive Approach\n # Time complexity O(N)\n # Space complexity O(N)\n def inorderTraversal(self,root):\n res = []\n self.helper(root, res)\n return res\n def helper(self, node, res):\n if node:\n if node.left:\n self.helper(node.left, res)\n res.append(node.val)\n if node.right:\n self.helper(node.right, res)\n\n # Iterating method using Stack\n # Time complexity O(N)\n # Space complexity O(N)\n def inorderTraversal(self,root):\n res = []\n stack = []\n curr = root\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop\n res.append(curr.val)\n curr = curr.right\n return res","sub_path":"practice_problems/Trees_and_Graghs/Binary Tree Inorder Traversal.py","file_name":"Binary Tree Inorder Traversal.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"336999055","text":"import tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, LSTM\nfrom keras.layers.normalization import BatchNormalization\nimport matplotlib.pyplot as plt\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n\n#Train the model on imagenet with vgg16\n# = VGG16(weights='imagenet', include_top=True)\n#model.save(\"vgg16.h5\")\n\n#Load the saved model\nmodel = tf.keras.models.load_model(\"D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\\\vgg16.h5\")\nmodel.layers.pop()\nmodel.layers.pop()\nprint(\"vgg\")\nmodel.summary()\n\nimages = ['D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000103.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000108.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000113.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000118.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000123.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000128.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000133.jpg']\ntestimages = ['D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000304.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000309.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000314.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000319.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000324.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000329.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000334.jpg']\n\npredictimages = ['D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\000461.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\002439.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\003950.jpg',\n 'D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\yolov3\\\\train\\\\004647.jpg']\n\ndef preprocessing(files):\n a = []\n for img_path in files:\n img = image.load_img(img_path, target_size=(224, 224))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n\n features = model.predict(x)\n a.append(features[np.newaxis, ...])\n\n f = model.layers[-2].output\n f = tf.squeeze(f, axis=0)\n\n inputarr = np.vstack(a)\n print(inputarr.shape)\n return inputarr\n\n\nx_train = preprocessing(images)\nx_test = preprocessing(testimages)\nx_predict = preprocessing(predictimages)\n\n#split into train and test\ny_train = np.array([[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[1,0]]) #y[:i]\ny_test = np.array(([0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[1,0])) #y[i:]\ny_predict = np.array(([0,1],[0,1],[0,1],[0,1])) #y[i:]\n\n# #build model\n# seq = Sequential()\n# seq.add(LSTM(128,input_shape=(1,1000),return_sequences=True))\n# seq.add(Dense(128, activation='relu'))\n# seq.add(BatchNormalization())\n#\n# seq.add(LSTM(64,return_sequences=True))\n# seq.add(Dense(64, activation='relu'))\n# seq.add(BatchNormalization())\n#\n# seq.add(LSTM(32,return_sequences=True))\n# seq.add(Dense(32, activation='relu'))\n#\n# seq.add(Flatten())\n# seq.add(Dense(2, activation='softmax'))\n#\n\n#\n# seq.summary()\n# model = seq\n#model.save(\"seq.h5\")\nmodel = tf.keras.models.load_model(\"D:\\CSCI631-FoundCV\\Final Project\\FinalProject\\\\yolov3\\\\seq.h5\")\nprint(\"seq\")\nmodel.summary()\nopt = tf.keras.optimizers.Adam(lr=0.001, decay=1e-6)\nmodel.compile(loss='binary_crossentropy', optimizer=opt, metrics=['mae', 'acc'])\nhistory = model.fit(x_train,\n y_train,\n epochs=3,\n validation_data=(x_test, y_test))\n\n# predict accidents test images\npred_y = model.predict_classes(x_predict, verbose=True)\n\nprint(pred_y)\n\nprint(history)\n\n# show graphs for accuarcy and loss\nacc_vals = history.history['acc']\nepochs = range(1, len(acc_vals)+1)\nplt.plot(epochs, acc_vals, label='Training Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\nplt.show()\n\nloss_values = history.history['mae']\nepochs = range(1, len(loss_values)+1)\nplt.plot(epochs, loss_values, label='Training Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\n\n\n# confusion matrix\ny_p = [0, 0, 0, 0]\ny_predicted = model.predict_classes(x_predict)\nprint(y_predicted)\n#y_pred = np.argmax(y_predicted, axis=1)\n\ntarget_classes = [ \"not accident\", \"accident\" ]\n\nprint(confusion_matrix(np.asarray(y_p),y_predicted), )\n\nprint(classification_report(np.asarray(y_p),y_predicted,target_names = target_classes ))","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583032262","text":"# Calendars\n\n# import calendar module\nimport calendar\n\n# create plain text calendar\nc = calendar.TextCalendar(calendar.SUNDAY) # starting day of week is Sunday\nst = c.formatmonth(2020,3,0,0)\nprint(st) # March 2020 calendar starting sunday\n\nc = calendar.TextCalendar(calendar.MONDAY) # starting day of week is Sunday\nst = c.formatmonth(2021,4,0,0)\nprint(st) # April 2021 starting MONDAY\n\n# HTML formatted calendar\nh = calendar.HTMLCalendar(calendar.MONDAY)\nhst = h.formatmonth(2021,4)\nprint(hst) # April 2021 starting MONDAY - table based calendar - with classes for styling\n\n# loop over days of a month\n# zeroes mean that the day of that week belongs to another month\nfor i in c.itermonthdays(2020,8): # loop through Aug 2020 days\n print(i)\n\n# calendar module provides useful utilities for the given locale Ex: days and months in full and abbreviated forms\nfor name in calendar.month_name:\n print(name)\n\nfor name in calendar.day_name:\n print(name)\n\n# If team meeting on first Friday of every month. What day would it be for each month\nprint(\"Team meetings will be on: \")\nfor m in range(1,13): # 13 is not included\n cal = calendar.monthcalendar(2020, m)\n weekone = cal[0]\n weektwo = cal[1] # First Friday must be within week 1 or two\n\n if weekone[calendar.FRIDAY] != 0: # if calendar's Friday is in weekone then weekone has the meetday else week two\n meetday = weekone[calendar.FRIDAY]\n else:\n meetday = weektwo[calendar.FRIDAY]\n\n print(\"%10s %2d\" %(calendar.month_name[m], meetday))\n","sub_path":"python_101/03/03_04_calendars.py","file_name":"03_04_calendars.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48379927","text":"from django.contrib import admin\nfrom trucks.models import BaseTruck, DeleteRequest, PlusTruck, EmailCollection, Event, Feedback\nfrom trucks.forms import BaseTruckCreateForm, BaseDeleteRequest, PlusTruckCreateForm, EmailCollectionForm, EventCreateForm, FeedbackForm\nfrom profiles.models import Profile\n\nclass TruckAdmin(admin.ModelAdmin):\n\tform = BaseTruckCreateForm\n\nclass TruckPremiumAdmin(admin.ModelAdmin):\n\tdef save_model(self, request, obj, form, change):\n\t\tTruckPremium.owner = request.user\n\t\tTruckPremium.save()\n\nclass TruckDeleteRequest(admin.ModelAdmin):\n\tdef save_model(self, request, obj, form, change):\n\t\tBaseDeleteRequest.user = request.user\n\t\tBaseDeleteRequest.save()\n\n\nclass PlusTruckAdmin(admin.ModelAdmin):\n\tfields = (\n\t\t'plus_truck_name',\n\t\t'plus_phone_number',\n\t\t'plus_address',\n\t\t'plus_city',\n\t\t'plus_state',\n\t\t'plus_postal_code',\n\t\t'plus_menu',\n\t\t'plus_menu_photo',\n\t\t'plus_food_type',\n\t\t'plus_description',\n\t\t'plus_thumbnail',\n\t\t'plus_status',\n\t\t'slug',\n\n\t\t)\n\nclass EmailCollectionAdmin(admin.ModelAdmin):\n\tform = EmailCollectionForm\n\nclass EventAdmin(admin.ModelAdmin):\n\tform = EventCreateForm\n\n\nclass FeedbackAdmin(admin.ModelAdmin):\n\tform = FeedbackForm\n\n\nadmin.site.register(BaseTruck, TruckAdmin)\nadmin.site.register(DeleteRequest, TruckDeleteRequest)\nadmin.site.register(PlusTruck, PlusTruckAdmin)\nadmin.site.register(EmailCollection, EmailCollectionAdmin)\nadmin.site.register(Event, EventAdmin)\nadmin.site.register(Feedback, FeedbackAdmin)\n","sub_path":"src/trucks/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55764849","text":"'''\nThis module us for utilty functions that take as input and / or return Container subclasses such as Index, Series, or Frame, and that need to be shared by multiple such Container classes.\n'''\n\nfrom collections import defaultdict\n\nimport numpy as np\nimport typing as tp\n\nif tp.TYPE_CHECKING:\n from static_frame.core.series import Series #pylint: disable=W0611 #pragma: no cover\n from static_frame.core.frame import Frame #pylint: disable=W0611 #pragma: no cover\n from static_frame.core.index_hierarchy import IndexHierarchy #pylint: disable=W0611 #pragma: no cover\n from static_frame.core.index_auto import IndexAutoFactoryType #pylint: disable=W0611 #pragma: no cover\n\nfrom static_frame.core.util import IndexConstructor\nfrom static_frame.core.util import IndexConstructors\nfrom static_frame.core.util import IndexInitializer\nfrom static_frame.core.util import STATIC_ATTR\nfrom static_frame.core.util import AnyCallable\nfrom static_frame.core.util import NULL_SLICE\nfrom static_frame.core.util import Bloc2DKeyType\nfrom static_frame.core.util import DtypesSpecifier\nfrom static_frame.core.util import slice_to_ascending_slice\nfrom static_frame.core.util import GetItemKeyType\nfrom static_frame.core.util import DEFAULT_SORT_KIND\nfrom static_frame.core.util import iterable_to_array_1d\n\nfrom static_frame.core.index_base import IndexBase\n\ndef dtypes_mappable(dtypes: DtypesSpecifier):\n '''\n Determine if the dtypes argument can be used by name lookup, rather than index.\n '''\n from static_frame.core.series import Series\n return isinstance(dtypes, (dict, Series))\n\n\ndef is_static(value: IndexConstructor) -> bool:\n try:\n # if this is a class constructor\n return getattr(value, STATIC_ATTR)\n except AttributeError:\n pass\n # assume this is a class method\n return getattr(value.__self__, STATIC_ATTR)\n\n\ndef index_from_optional_constructor(\n value: IndexInitializer,\n *,\n default_constructor: IndexConstructor,\n explicit_constructor: tp.Optional[IndexConstructor] = None,\n ) -> IndexBase:\n '''\n Given a value that is an IndexInitializer (which means it might be an Index), determine if that value is really an Index, and if so, determine if a copy has to be made; otherwise, use the default_constructor. If an explicit_constructor is given, that is always used.\n '''\n # NOTE: this might return an own_index flag to show callers when a new index has been created\n\n if explicit_constructor:\n return explicit_constructor(value)\n\n # default constructor could be a function with a STATIC attribute\n if isinstance(value, IndexBase):\n # if default is STATIC, and value is not STATIC, get an immutabel\n if is_static(default_constructor): # type: ignore\n if not value.STATIC:\n # v: ~S, dc: S, use immutable alternative\n return value._IMMUTABLE_CONSTRUCTOR(value)\n # v: S, dc: S, both immutable\n return value\n else: # default constructor is mutable\n if not value.STATIC:\n # v: ~S, dc: ~S, both are mutable\n return value.copy()\n # v: S, dc: ~S, return a mutable version of something that is not mutable\n return value._MUTABLE_CONSTRUCTOR(value)\n\n # cannot always deterine satic status from constructors; fallback on using default constructor\n return default_constructor(value)\n\ndef index_constructor_empty(index: tp.Union[IndexInitializer, 'IndexAutoFactoryType']):\n '''\n Determine if an index is empty (if possible) or an IndexAutoFactory.\n '''\n from static_frame.core.index_auto import IndexAutoFactory\n\n return index is None or index is IndexAutoFactory or (\n hasattr(index, '__len__') and len(index) == 0)\n\ndef matmul(\n lhs: tp.Union['Series', 'Frame', tp.Iterable],\n rhs: tp.Union['Series', 'Frame', tp.Iterable],\n ) -> tp.Any: #tp.Union['Series', 'Frame']:\n '''\n Implementation of matrix multiplication for Series and Frame\n '''\n from static_frame.core.series import Series\n from static_frame.core.frame import Frame\n\n # for a @ b = c\n # if a is 2D: a.columns must align b.index\n # if b is 1D, a.columns bust align with b.index\n # if a is 1D: len(a) == b.index (len of b), returns w columns of B\n\n if not isinstance(rhs, (np.ndarray, Series, Frame)):\n # try to make it into an array\n rhs = np.array(rhs)\n\n if not isinstance(lhs, (np.ndarray, Series, Frame)):\n # try to make it into an array\n lhs = np.array(lhs)\n\n if isinstance(lhs, np.ndarray):\n lhs_type = np.ndarray\n elif isinstance(lhs, Series):\n lhs_type = Series\n else: # normalize subclasses\n lhs_type = Frame\n\n if isinstance(rhs, np.ndarray):\n rhs_type = np.ndarray\n elif isinstance(rhs, Series):\n rhs_type = Series\n else: # normalize subclasses\n rhs_type = Frame\n\n if rhs_type == np.ndarray and lhs_type == np.ndarray:\n return np.matmul(lhs, rhs)\n\n\n own_index = True\n constructor = None\n\n if lhs.ndim == 1: # Series, 1D array\n # result will be 1D or 0D\n columns = None\n\n if lhs_type == Series and (rhs_type == Series or rhs_type == Frame):\n aligned = lhs._index.union(rhs._index)\n # if the aligned shape is not the same size as the originals, we do not have the same values in each and cannot proceed (all values go to NaN)\n if len(aligned) != len(lhs._index) or len(aligned) != len(rhs._index):\n raise RuntimeError('shapes not alignable for matrix multiplication')\n\n if lhs_type == Series:\n if rhs_type == np.ndarray:\n if lhs.shape[0] != rhs.shape[0]: # works for 1D and 2D\n raise RuntimeError('shapes not alignable for matrix multiplication')\n ndim = rhs.ndim - 1 # if 2D, result is 1D, of 1D, result is 0\n left = lhs.values\n right = rhs # already np\n if ndim == 1:\n index = None # force auto increment integer\n own_index = False\n constructor = lhs.__class__\n # else:\n # index = lhs.index\n elif rhs_type == Series:\n ndim = 0\n left = lhs.reindex(aligned).values\n right = rhs.reindex(aligned).values\n # index = aligned\n else: # rhs is Frame\n ndim = 1\n left = lhs.reindex(aligned).values\n right = rhs.reindex(index=aligned).values\n index = rhs._columns\n constructor = lhs.__class__\n else: # lhs is 1D array\n left = lhs\n right = rhs.values\n if rhs_type == Series:\n ndim = 0\n else: # rhs is Frame, len(lhs) == len(rhs.index)\n ndim = 1\n index = rhs._columns\n constructor = Series # cannot get from argument\n\n elif lhs.ndim == 2: # Frame, 2D array\n\n if lhs_type == Frame and (rhs_type == Series or rhs_type == Frame):\n aligned = lhs._columns.union(rhs._index)\n # if the aligned shape is not the same size as the originals, we do not have the same values in each and cannot proceed (all values go to NaN)\n if len(aligned) != len(lhs._columns) or len(aligned) != len(rhs._index):\n raise RuntimeError('shapes not alignable for matrix multiplication')\n\n if lhs_type == Frame:\n if rhs_type == np.ndarray:\n if lhs.shape[1] != rhs.shape[0]: # works for 1D and 2D\n raise RuntimeError('shapes not alignable for matrix multiplication')\n ndim = rhs.ndim\n left = lhs.values\n right = rhs # already np\n index = lhs._index\n\n if ndim == 1:\n constructor = Series\n else:\n constructor = lhs.__class__\n columns = None # force auto increment index\n elif rhs_type == Series:\n # a.columns must align with b.index\n ndim = 1\n left = lhs.reindex(columns=aligned).values\n right = rhs.reindex(aligned).values\n index = lhs._index # this axis is not changed\n constructor = rhs.__class__\n else: # rhs is Frame\n # a.columns must align with b.index\n ndim = 2\n left = lhs.reindex(columns=aligned).values\n right = rhs.reindex(index=aligned).values\n index = lhs._index\n columns = rhs._columns\n constructor = lhs.__class__ # give left precedence\n else: # lhs is 2D array\n left = lhs\n right = rhs.values\n if rhs_type == Series: # returns unindexed Series\n ndim = 1\n index = None\n own_index = False\n constructor = rhs.__class__\n else: # rhs is Frame, lhs.shape[1] == rhs.shape[0]\n if lhs.shape[1] != rhs.shape[0]: # works for 1D and 2D\n raise RuntimeError('shapes not alignable for matrix multiplication')\n ndim = 2\n index = None\n own_index = False\n columns = rhs._columns\n constructor = rhs.__class__\n\n # NOTE: np.matmul is not the same as np.dot for some arguments\n data = np.matmul(left, right)\n\n if ndim == 0:\n return data\n\n data.flags.writeable = False\n if ndim == 1:\n return constructor(data,\n index=index,\n own_index=own_index,\n )\n return constructor(data,\n index=index,\n own_index=own_index,\n columns=columns\n )\n\n\ndef axis_window_items( *,\n source: tp.Union['Series', 'Frame'],\n size: int,\n axis: int = 0,\n step: int = 1,\n window_sized: bool = True,\n window_func: tp.Optional[AnyCallable] = None,\n window_valid: tp.Optional[AnyCallable] = None,\n label_shift: int = 0,\n start_shift: int = 0,\n size_increment: int = 0,\n as_array: bool = False,\n ) -> tp.Iterator[tp.Tuple[tp.Hashable, tp.Any]]:\n '''Generator of index, window pairs pairs.\n\n Args:\n size: integer greater than 0\n step: integer greater than 0 to determine the step size between windows. A step of 1 shifts the window 1 data point; a step equal to window size results in non-overlapping windows.\n window_sized: if True, windows that do not meet the size are skipped.\n window_func: Array processor of window values, pre-function application; useful for applying weighting to the window.\n window_valid: Function that, given an array window, returns True if the window meets requirements and should be returned.\n label_shift: shift, relative to the right-most data point contained in the window, to derive the label to be paired with the window; e.g., to return the first label of the window, the shift will be the size minus one.\n start_shift: shift from 0 to determine where the collection of windows begins.\n size_increment: value to be added to each window aftert the first, so as to, in combination with setting the step size to 0, permit expanding windows.\n as_array: if True, the window is returned as an array instead of a SF object.\n '''\n if size <= 0:\n raise RuntimeError('window size must be greater than 0')\n if step < 0:\n raise RuntimeError('window step cannot be less than than 0')\n\n source_ndim = source.ndim\n\n if source_ndim == 1:\n labels = source._index\n if as_array:\n values = source.values\n else:\n labels = source._index if axis == 0 else source._columns\n if as_array:\n values = source._blocks.values\n\n if start_shift >= 0:\n count_window_max = len(labels)\n else: # add for iterations when less than 0\n count_window_max = len(labels) + abs(start_shift)\n\n idx_left_max = count_window_max - 1\n idx_left = start_shift\n count = 0\n\n while True:\n # idx_left, size can change over iterations\n idx_right = idx_left + size - 1\n\n # floor idx_left at 0 so as to not wrap\n idx_left_floored = max(idx_left, 0)\n idx_right_floored = max(idx_right, -1) # will add one\n\n key = slice(idx_left_floored, idx_right_floored + 1)\n\n if source_ndim == 1:\n if as_array:\n window = values[key]\n else:\n window = source._extract_iloc(key)\n else:\n if axis == 0:\n if as_array:\n window = values[key]\n else: # use low level iloc selector\n window = source._extract(row_key=key)\n else:\n if as_array:\n window = values[NULL_SLICE, key]\n else:\n window = source._extract(column_key=key)\n\n valid = True\n try:\n idx_label = idx_right + label_shift\n if idx_label < 0: # do not wrap around\n raise IndexError()\n #if we cannot get a lable, the window is invalid\n label = labels.iloc[idx_label]\n except IndexError: # an invalid label has to be dropped\n valid = False\n\n if valid and window_sized and window.shape[axis] != size:\n valid = False\n if valid and window_valid and not window_valid(window):\n valid = False\n\n if valid:\n if window_func:\n window = window_func(window)\n yield label, window\n\n idx_left += step\n size += size_increment\n count += 1\n\n # import ipdb; ipdb.set_trace()\n\n if count > count_window_max or idx_left > idx_left_max or size < 0:\n break\n\n\ndef bloc_key_normalize(\n key: Bloc2DKeyType,\n container: 'Frame'\n ) -> np.ndarray:\n '''\n Normalize and validate a bloc key. Return a same sized Boolean array.\n '''\n from static_frame.core.frame import Frame\n\n if isinstance(key, Frame):\n bloc_frame = key.reindex(\n index=container._index,\n columns=container._columns,\n fill_value=False\n )\n bloc_key = bloc_frame.values # shape must match post reindex\n elif isinstance(key, np.ndarray):\n bloc_key = key\n if bloc_key.shape != container.shape:\n raise RuntimeError(f'bloc {bloc_key.shape} must match shape {container.shape}')\n else:\n raise RuntimeError(f'invalid bloc_key, must be Frame or array, not {key}')\n\n if not bloc_key.dtype == bool:\n raise RuntimeError('cannot use non-Bolean dtype as bloc key')\n\n return bloc_key\n\n\ndef key_to_ascending_key(key: GetItemKeyType, size: int) -> GetItemKeyType:\n '''\n Normalize all types of keys into an ascending formation.\n\n Args:\n size: the length of the container on this axis\n '''\n from static_frame.core.frame import Frame\n from static_frame.core.series import Series\n\n if isinstance(key, slice):\n return slice_to_ascending_slice(key, size=size)\n\n if isinstance(key, str) or not hasattr(key, '__len__'):\n return key\n\n if isinstance(key, np.ndarray):\n # array first as not truthy\n return np.sort(key, kind=DEFAULT_SORT_KIND)\n\n if not key:\n return key\n\n if isinstance(key, list):\n return sorted(key)\n\n if isinstance(key, Series):\n return key.sort_index()\n\n if isinstance(key, Frame):\n # for usage in assignment we need columns to be sorted\n return key.sort_columns()\n\n raise RuntimeError(f'unhandled key {key}')\n\n\n\ndef rehierarch_and_map(*,\n labels: np.ndarray,\n depth_map: tp.Iterable[int],\n index_constructor: IndexConstructor,\n index_constructors: tp.Optional[IndexConstructors] = None,\n name: tp.Hashable = None,\n ) -> tp.Tuple['IndexHierarchy', tp.Sequence[int]]:\n '''\n Given labels suitable for a hierarchical index, order them into a hierarchy using the given depth_map.\n '''\n\n depth = labels.shape[1] # number of columns\n\n if depth != len(depth_map):\n raise RuntimeError('must specify new depths for all depths')\n if set(range(depth)) != set(depth_map):\n raise RuntimeError('all depths must be specified')\n\n labels_post = labels[NULL_SLICE, list(depth_map)]\n labels_sort = np.full(labels_post.shape, 0)\n\n # get ordering of vlues found in each level\n order = [defaultdict(int) for _ in range(depth)]\n\n for idx_row, label in enumerate(labels):\n label = tuple(label)\n for idx_col in range(depth):\n if label[idx_col] not in order[idx_col]:\n # Map label to an integer representing the observed order.\n order[idx_col][label[idx_col]] = len(order[idx_col])\n # Fill array for sorting based on observed order.\n labels_sort[idx_row, idx_col] = order[idx_col][label[idx_col]]\n\n # Reverse depth_map for lexical sorting, which sorts by rightmost column first.\n order_lex = np.lexsort([labels_sort[NULL_SLICE, i] for i in reversed(depth_map)])\n labels_post = labels_post[order_lex]\n labels_post.flags.writeable = False\n index = index_constructor(labels_post,\n index_constructors=index_constructors,\n name=name,\n )\n return index, order_lex\n\n\n\ndef array_from_value_iter(\n key: tp.Hashable,\n idx: int,\n get_value_iter: tp.Callable[[tp.Hashable], tp.Iterator[tp.Any]],\n get_col_dtype: tp.Optional[tp.Callable],\n row_count: int,\n ):\n '''\n Return a single array given keys and collections.\n\n Args:\n get_value_iter: Iterator of a values\n dtypes: if an\n key: hashable for looking up field in `get_value_iter`.\n idx: integer position to extract from dtypes\n '''\n # for each column, try to get a column_type, or None\n if get_col_dtype is None:\n column_type = None\n else: # column_type returned here can be None.\n column_type = get_col_dtype(idx)\n # if this value is None we cannot tell if it was explicitly None or just was not specified\n\n values = None\n if column_type is not None:\n try:\n values = np.fromiter(\n get_value_iter(key),\n count=row_count,\n dtype=column_type)\n values.flags.writeable = False\n except (ValueError, TypeError):\n # the column_type may not be compatible, so must fall back on using np.array to determine the type, i.e., ValueError: cannot convert float NaN to integer\n pass\n if values is None:\n # returns an immutable array\n values, _ = iterable_to_array_1d(\n get_value_iter(key),\n dtype=column_type\n )\n\n return values\n\n\n\n","sub_path":"static_frame/core/container_util.py","file_name":"container_util.py","file_ext":"py","file_size_in_byte":19181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167284645","text":"from poc.classes.AuxISourceAnalyser import AuxISourceAnalyser\nfrom poc.classes.AuxInterpretation import AuxInterpretation\nfrom poc.classes.AuxContext import AuxContext\nfrom poc.classes.NamespaceIdentifier import NamespaceIdentifier\nfrom poc.classes.AuxSymbolTable import AuxSymbolTable\n\n\nclass ContextNamespaceIdentifier:\n @staticmethod\n def dispatch(i: AuxISourceAnalyser, parsing_info: AuxInterpretation):\n namespace_info = NamespaceIdentifier(i.parse_list, parsing_info)\n # NamespaceIdentifier can occur in the following contexts:\n if i.context.is_parsing_context([AuxContext.root]):\n # tag the namespace to the theory node\n i.theory_node.namespace = namespace_info.id\n else:\n if i.verbose:\n print(\n \"########### Unhandled context in ContextNamespaceIdentifier.dispatch \" + str(\n i.context.get_context()) + \" \" + str(namespace_info))\n i.parse_list.append(namespace_info)\n\n","sub_path":"poc/classes/ContextNamespaceIdentifier.py","file_name":"ContextNamespaceIdentifier.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132794780","text":"# ctypes_helloWorld.py\n# Demonstrates using the ctype variables\n\nfrom ctypes import *\n\n# Declaring a C string (char * NULL terminated)\n# Don't forget to change the encoding from Unicode to ASCII\nc_string = c_char_p(\"Hello world!\".encode('ascii'))\n\n# To change the byte string back use .decode('ascii')\n# after the c_string pointer is dereferenced with .value\npy_string = c_string.value.decode('ascii')\nprint(py_string) \n","sub_path":"ctypes/vars.py","file_name":"vars.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"76589984","text":"# Copyright 2016-2018 Yubico AB\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Core classes for YubiHSM communication.\"\"\"\n\n\nfrom __future__ import absolute_import, division\n\nfrom . import utils\nfrom .defs import COMMAND, ALGORITHM, LIST_FILTER, OPTION, AUDIT\nfrom .backends import get_backend\nfrom .objects import YhsmObject, _label_pack, LABEL_LENGTH\nfrom .exceptions import (\n YubiHsmDeviceError,\n YubiHsmInvalidRequestError,\n YubiHsmInvalidResponseError,\n YubiHsmAuthenticationError,\n YubiHsmConnectionError,\n)\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import cmac, constant_time\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.utils import int_to_bytes\nfrom hashlib import sha256\nfrom collections import namedtuple\nimport os\nimport six\nimport struct\n\n\nKEY_ENC = 0x04\nKEY_MAC = 0x06\nKEY_RMAC = 0x07\nCARD_CRYPTOGRAM = 0x00\nHOST_CRYPTOGRAM = 0x01\n\nMAX_MSG_SIZE = 2048 - 1\n\n\ndef _derive(key, t, context, L=0x80):\n # this only supports aes128\n if L != 0x80 and L != 0x40:\n raise ValueError(\"L must be 0x40 or 0x80\")\n\n i = b\"\\0\" * 11 + struct.pack(\"!BBHB\", t, 0, L, 1) + context\n\n c = cmac.CMAC(algorithms.AES(key), backend=default_backend())\n c.update(i)\n return c.finalize()[: L // 8]\n\n\ndef _unpad_resp(resp, cmd):\n if len(resp) < 3:\n raise YubiHsmInvalidResponseError(\"Wrong length\")\n rcmd, length = struct.unpack(\"!BH\", resp[:3])\n if len(resp) < length + 3:\n raise YubiHsmInvalidResponseError(\"Wrong length\")\n if rcmd == COMMAND.ERROR:\n raise YubiHsmDeviceError(six.indexbytes(resp, 3))\n elif rcmd != cmd | 0x80:\n raise YubiHsmInvalidResponseError(\"Wrong command in response\")\n return resp[3 : length + 3]\n\n\nclass YubiHsm(object):\n \"\"\"An unauthenticated connection to a YubiHSM.\"\"\"\n\n def __init__(self, backend):\n \"\"\"Constructs a YubiHSM connected to the given backend.\n\n :param backend: A backend used to communicate with a YubiHSM.\n \"\"\"\n self._backend = backend\n\n def __enter__(self):\n return self\n\n def __exit__(self, typ, value, traceback):\n self.close()\n\n def close(self):\n \"\"\"Disconnect from the backend, freeing any resources in use by it.\"\"\"\n if self._backend:\n self._backend.close()\n self._backend = None\n\n def _transceive(self, msg):\n if len(msg) > MAX_MSG_SIZE:\n raise YubiHsmInvalidRequestError(\"Message too long.\")\n return self._backend.transceive(msg)\n\n def send_cmd(self, cmd, data=b\"\"):\n \"\"\"Encode and send a command byte and its associated data.\n\n :param COMMAND cmd: The command to send.\n :param bytes data: The command payload to send.\n :return: The response data from the YubiHSM.\n :rtype: bytes\n \"\"\"\n msg = struct.pack(\"!BH\", cmd, len(data)) + data\n return _unpad_resp(self._transceive(msg), cmd)\n\n def get_device_info(self):\n \"\"\"Get general device information from the YubiHSM.\n\n :return: Device information.\n :rtype: DeviceInfo\n \"\"\"\n return DeviceInfo.parse(self.send_cmd(COMMAND.DEVICE_INFO))\n\n def create_session(self, auth_key_id, key_enc, key_mac):\n \"\"\"Creates an authenticated session with the YubiHSM.\n\n See also create_session_derived, which derives K-ENC and K-MAC from a\n password.\n\n :param int auth_key_id: The ID of the Authentication key used to\n authenticate the session.\n :param bytes key_enc: Static K-ENC used to establish session.\n :param bytes key_mac: Static K-MAC used to establish session.\n :return: An authenticated session.\n :rtype: AuthSession\n \"\"\"\n return AuthSession(self, auth_key_id, key_enc, key_mac)\n\n def create_session_derived(self, auth_key_id, password):\n \"\"\"Creates an authenticated session with the YubiHSM.\n\n Uses a supplied password to derive the keys K-ENC and K-MAC.\n\n :param int auth_key_id: The ID of the Authentication key used to\n authenticate the session.\n :param str password: The password used to derive the keys from.\n :return: An authenticated session.\n :rtype: AuthSession\n \"\"\"\n key_enc, key_mac = utils.password_to_key(password)\n return self.create_session(auth_key_id, key_enc, key_mac)\n\n @classmethod\n def connect(cls, url=None):\n \"\"\"Return a YubiHsm connected to the backend specified by the URL.\n\n If no URL is given this will attempt to connect to a YubiHSM connector\n running on localhost, using the default port.\n\n :param str url: (optional) A http(s):// or yhusb:// backend URL.\n :return: A YubiHsm instance connected to the backend referenced by the\n url.\n :rtype: YubiHsm\n \"\"\"\n return cls(get_backend(url))\n\n def __repr__(self):\n return \"{0.__class__.__name__}({0._backend})\".format(self)\n\n\nclass _UnknownIntEnum(int):\n name = \"UNKNOWN\"\n\n def __repr__(self):\n return \"<%s: %d>\" % (self.name, self)\n\n def __str__(self):\n return self.name\n\n @property\n def value(self):\n return int(self)\n\n\nclass _UnknownAlgorithm(_UnknownIntEnum):\n \"\"\"Wrapper for unknown ALGORITHM values.\n\n Provides obj.name, obj.value and and string representations.\"\"\"\n\n name = \"ALGORITHM.UNKNOWN\"\n\n\ndef _algorithm(val):\n try:\n return ALGORITHM(val)\n except ValueError:\n return _UnknownAlgorithm(val)\n\n\nclass _UnknownCommand(_UnknownIntEnum):\n \"\"\"Wrapper for unknown COMMAND values.\n\n Provides obj.name, obj.value and and string representations.\"\"\"\n\n name = \"COMMAND.UNKNOWN\"\n\n\nclass DeviceInfo(\n namedtuple(\n \"DeviceInfo\",\n [\"version\", \"serial\", \"log_size\", \"log_used\", \"supported_algorithms\"],\n )\n):\n \"\"\"Data class holding various information about the YubiHSM.\n\n :param version: YubiHSM version tuple.\n :type version: tuple[int, int, int]\n :param int serial: YubiHSM serial number.\n :param int log_size: Log entry storage capacity.\n :param int log_used: Log entries currently stored.\n :param set[ALGORITHM] supported_algorithms: List of supported algorithms.\n \"\"\"\n\n __slots__ = ()\n FORMAT = \"!BBBIBB\"\n LENGTH = struct.calcsize(FORMAT)\n\n @classmethod\n def parse(cls, data):\n \"\"\"Parse a DeviceInfo from its binary representation.\n\n :param bytes data: Binary data to unpack from.\n :return: The parsed object.\n :rtype: DeviceInfo\n \"\"\"\n unpacked = struct.unpack_from(cls.FORMAT, data)\n version = unpacked[:3]\n serial, log_size, log_used = unpacked[3:]\n algorithms = {_algorithm(a) for a in six.iterbytes(data[cls.LENGTH :])}\n\n return cls(version, serial, log_size, log_used, algorithms)\n\n\ndef _calculate_iv(key, counter):\n encryptor = Cipher(\n algorithms.AES(key), modes.ECB(), backend=default_backend()\n ).encryptor()\n return encryptor.update(int_to_bytes(counter, 16)) + encryptor.finalize()\n\n\ndef _calculate_mac(key, chain, message):\n c = cmac.CMAC(algorithms.AES(key), backend=default_backend())\n c.update(chain)\n c.update(message)\n chain = c.finalize()\n return chain, chain[:8]\n\n\nclass AuthSession(object):\n \"\"\"An authenticated secure session with a YubiHSM.\n\n Typically you get an instance of this class by calling\n :func:`~YubiHsm.create_session` or :func:`~YubiHsm.create_session_derived`.\n \"\"\"\n\n def __init__(self, hsm, auth_key_id, key_enc, key_mac):\n \"\"\"Constructs an authenticated session.\n\n :param YubiHsm hsm: The YubiHSM connection.\n :param int auth_key_id: The ID of the Authentication key used to\n authenticate the session.\n :param bytes key_enc: Static `K-ENC` used to establish the session.\n :param bytes key_mac: Static `K-MAC` used to establish the session.\n \"\"\"\n self._hsm = hsm\n\n context = os.urandom(8)\n\n data = self._hsm.send_cmd(\n COMMAND.CREATE_SESSION, struct.pack(\"!H\", auth_key_id) + context\n )\n\n self._sid = six.indexbytes(data, 0)\n context += data[1 : 1 + 8]\n card_crypto = data[9 : 9 + 8]\n self._key_enc = _derive(key_enc, KEY_ENC, context)\n self._key_mac = _derive(key_mac, KEY_MAC, context)\n self._key_rmac = _derive(key_mac, KEY_RMAC, context)\n gen_card_crypto = _derive(self._key_mac, CARD_CRYPTOGRAM, context, 0x40)\n\n if not constant_time.bytes_eq(gen_card_crypto, card_crypto):\n raise YubiHsmAuthenticationError()\n\n msg = struct.pack(\"!BHB\", COMMAND.AUTHENTICATE_SESSION, 1 + 8 + 8, self.sid)\n msg += _derive(self._key_mac, HOST_CRYPTOGRAM, context, 0x40)\n self._ctr = 1\n self._mac_chain, mac = _calculate_mac(self._key_mac, b\"\\0\" * 16, msg)\n msg += mac\n if _unpad_resp(self._hsm._transceive(msg), COMMAND.AUTHENTICATE_SESSION) != b\"\":\n raise YubiHsmInvalidResponseError(\"Non-empty response\")\n\n def close(self):\n \"\"\"Close this session with the YubiHSM.\n\n Once closed, this session object can no longer be used, unless re-connected.\n \"\"\"\n\n if self._sid is not None:\n try:\n self.send_secure_cmd(COMMAND.CLOSE_SESSION)\n finally:\n self._sid = None\n self._key_enc = self._key_mac = self._key_rmac = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, typ, value, traceback):\n self.close()\n\n def _secure_transceive(self, msg):\n msg += b\"\\x80\"\n padlen = 16 - len(msg) % 16\n msg = msg.ljust(len(msg) + padlen, b\"\\0\")\n\n wrapped = struct.pack(\n \"!BHB\", COMMAND.SESSION_MESSAGE, 1 + len(msg) + 8, self.sid\n )\n cipher = Cipher(\n algorithms.AES(self._key_enc),\n modes.CBC(_calculate_iv(self._key_enc, self._ctr)),\n backend=default_backend(),\n )\n encryptor = cipher.encryptor()\n wrapped += encryptor.update(msg) + encryptor.finalize()\n next_mac_chain, mac = _calculate_mac(self._key_mac, self._mac_chain, wrapped)\n wrapped += mac\n raw_resp = self._hsm._transceive(wrapped)\n\n data = _unpad_resp(raw_resp, COMMAND.SESSION_MESSAGE)\n\n if six.indexbytes(data, 0) != self._sid:\n raise YubiHsmInvalidResponseError(\"Incorrect SID\")\n\n rmac = _calculate_mac(self._key_rmac, next_mac_chain, raw_resp[:-8])[1]\n if not constant_time.bytes_eq(raw_resp[-8:], rmac):\n raise YubiHsmInvalidResponseError(\"Incorrect MAC\")\n\n self._ctr += 1\n self._mac_chain = next_mac_chain\n\n decryptor = cipher.decryptor()\n return decryptor.update(data[1:-8]) + decryptor.finalize()\n\n @property\n def sid(self):\n \"\"\"Session ID\n\n :return: The ID of the session.\n :rtype: int\n \"\"\"\n return self._sid\n\n def send_secure_cmd(self, cmd, data=b\"\"):\n \"\"\"Send a command over the encrypted session.\n\n :param COMMAND cmd: The command to send.\n :param bytes data: The command payload to send.\n :return: The decrypted response data from the YubiHSM.\n :rtype: bytes\n \"\"\"\n msg = struct.pack(\"!BH\", cmd, len(data)) + data\n return _unpad_resp(self._secure_transceive(msg), cmd)\n\n def list_objects(\n self,\n object_id=None,\n object_type=None,\n domains=None,\n capabilities=None,\n algorithm=None,\n label=None,\n ):\n \"\"\"List objects from the YubiHSM.\n\n This returns a list of all objects currently stored on the YubiHSM,\n which are accessible by this session. The arguments to this method can\n be used to filter the results returned.\n\n :param int object_id: (optional) Return only objects with this ID.\n :param OBJECT object_type: (optional) Return only objects of this type.\n :param int domains: (optional) Return only objects belonging to one or\n more of these domains.\n :param int capabilities: (optional) Return only objects with one or more\n of these capabilities.\n :param ALGORITHM algorithm: (optional) Return only objects with this\n algorithm.\n :param label: (optional) Return only objects with this label.\n :return: A list of matched objects.\n :rtype: list\n \"\"\"\n msg = b\"\"\n if object_id is not None:\n msg += struct.pack(\"!BH\", LIST_FILTER.ID, object_id)\n if object_type is not None:\n msg += struct.pack(\"!BB\", LIST_FILTER.TYPE, object_type)\n if domains is not None:\n msg += struct.pack(\"!BH\", LIST_FILTER.DOMAINS, domains)\n if capabilities is not None:\n msg += struct.pack(\"!BQ\", LIST_FILTER.CAPABILITIES, capabilities)\n if algorithm is not None:\n msg += struct.pack(\"!BB\", LIST_FILTER.ALGORITHM, algorithm)\n if label is not None:\n msg += struct.pack(\n \"!B%ds\" % LABEL_LENGTH, LIST_FILTER.LABEL, _label_pack(label)\n )\n\n resp = self.send_secure_cmd(COMMAND.LIST_OBJECTS, msg)\n\n objects = []\n for i in range(0, len(resp), 4):\n object_id, typ, seq = struct.unpack(\"!HBB\", resp[i : i + 4])\n objects.append(YhsmObject._create(typ, self, object_id, seq))\n return objects\n\n def get_object(self, object_id, object_type):\n \"\"\"Get a reference to a YhsmObject with the given id and type.\n\n The object returned will be a subclass of YhsmObject corresponding to\n the given object_type.\n\n :param int object_id: The ID of the object to retrieve.\n :param OBJECT object_type: The type of the object to retrieve.\n :return: An object reference.\n :rtype: YhsmObject\n \"\"\"\n return YhsmObject._create(object_type, self, object_id)\n\n def get_pseudo_random(self, length):\n \"\"\"Get bytes from YubiHSM PRNG.\n\n :param int length: The number of bytes to return.\n :return: The requested number of random bytes.\n :rtype: bytes\n \"\"\"\n msg = struct.pack(\"!H\", length)\n return self.send_secure_cmd(COMMAND.GET_PSEUDO_RANDOM, msg)\n\n def reset_device(self):\n \"\"\"Performs a factory reset of the YubiHSM.\n\n Resets and reboots the YubiHSM, deletes all Objects and restores the\n default Authkey.\n \"\"\"\n try:\n if self.send_secure_cmd(COMMAND.RESET_DEVICE) != b\"\":\n raise YubiHsmInvalidResponseError(\"Non-empty response\")\n except YubiHsmConnectionError:\n pass # Assume reset went well, it may interrupt the connection.\n self._sid = None\n self._key_enc = self._key_mac = self._key_rmac = None\n self._hsm.close()\n\n def get_log_entries(self, previous_entry=None):\n \"\"\"Get logs from the YubiHSM.\n\n This returns a tuple of the number of unlogged boot events, the number\n of unlogged authentication events, and the log entries from the YubiHSM.\n The chain of entry digests will be validated, starting from the first\n entry returned, or the one supplied as previous_entry.\n\n :param LogEntry previous_entry: (optional) Entry to start verification\n against.\n :return: A tuple consisting of the number of unlogged boot and\n authentication events, and the list of log entries.\n :rtype: LogData\n \"\"\"\n resp = self.send_secure_cmd(COMMAND.GET_LOG_ENTRIES)\n boot, auth, num = struct.unpack(\"!HHB\", resp[:5])\n\n data = resp[5:]\n if len(data) != num * LogEntry.LENGTH:\n raise YubiHsmInvalidResponseError(\"Incorrect length\")\n\n logs = []\n for i in range(0, len(data), LogEntry.LENGTH):\n entry = LogEntry.parse(data[i : i + LogEntry.LENGTH])\n if previous_entry:\n if not entry.validate(previous_entry):\n raise YubiHsmInvalidResponseError(\"Incorrect log digest\")\n logs.append(entry)\n previous_entry = entry\n\n return LogData(boot, auth, logs)\n\n def set_log_index(self, index):\n \"\"\"Clears logs to free up space for use with forced audit.\n\n :param int index: The log entry index to clear up to (inclusive).\n \"\"\"\n msg = struct.pack(\"!H\", index)\n if self.send_secure_cmd(COMMAND.SET_LOG_INDEX, msg) != b\"\":\n raise YubiHsmInvalidResponseError(\"Non-empty response\")\n\n def put_option(self, option, value):\n \"\"\"Set the raw value of a YubiHSM device option.\n\n :param OPTION option: The OPTION to set.\n :param bytes value: The value to set the OPTION to.\n \"\"\"\n msg = struct.pack(\"!BH\", option, len(value)) + value\n if self.send_secure_cmd(COMMAND.SET_OPTION, msg) != b\"\":\n raise YubiHsmInvalidResponseError(\"Non-empty response\")\n\n def get_option(self, option):\n \"\"\"Get the raw value of a YubiHSM device option.\n\n :param OPTION option: The OPTION to get.\n :return: The currently set value for the given OPTION\n :rtype: bytes\n \"\"\"\n msg = struct.pack(\"!B\", option)\n return self.send_secure_cmd(COMMAND.GET_OPTION, msg)\n\n def set_force_audit(self, audit):\n \"\"\"Set the FORCE_AUDIT mode of the YubiHSM.\n\n :param AUDIT audit: The AUDIT mode to set.\n \"\"\"\n self.put_option(OPTION.FORCE_AUDIT, struct.pack(\"B\", audit))\n\n def get_force_audit(self):\n \"\"\"Get the current setting for forced audit mode.\n\n :return: The AUDIT setting for FORCE_AUDIT.\n :rtype: AUDIT\n \"\"\"\n return AUDIT(six.indexbytes(self.get_option(OPTION.FORCE_AUDIT), 0))\n\n def set_command_audit(self, commands):\n \"\"\"Set audit mode of commands.\n\n Takes a dict of COMMAND -> AUDIT pairs and updates the audit settings\n for the commands given.\n\n :param commands: Settings to update.\n :type commands: dict[COMMAND, AUDIT]\n\n :Example:\n\n >>> session.set_comment_audit({\n ... COMMAND.ECHO: AUDIT.OFF,\n ... COMMAND.LIST_OBJECTS: AUDIT.ON\n ... })\n \"\"\"\n msg = b\"\".join(struct.pack(\"!BB\", k, v) for (k, v) in commands.items())\n self.put_option(OPTION.COMMAND_AUDIT, msg)\n\n def get_command_audit(self):\n \"\"\"Get a mapping of all available commands and their audit settings.\n\n :return: Dictionary of COMMAND -> AUDIT pairs.\n :rtype: dict[COMMAND, AUDIT]\n \"\"\"\n resp = self.get_option(OPTION.COMMAND_AUDIT)\n ret = {}\n for i in range(0, len(resp), 2):\n cmd = six.indexbytes(resp, i)\n val = AUDIT(six.indexbytes(resp, i + 1))\n try:\n ret[COMMAND(cmd)] = val\n except ValueError:\n ret[_UnknownCommand(cmd)] = val\n return ret\n\n def __repr__(self):\n return \"{0.__class__.__name__}(id={0._sid}, hsm={0._hsm})\".format(self)\n\n\nclass LogData(namedtuple(\"LogData\", [\"n_boot\", \"n_auth\", \"entries\"])):\n \"\"\"Data class holding response data from a GET_LOGS command.\n\n :param int n_boot: Number of unlogged boot events.\n :param int n_auth: Number of unlogged authentication events.\n :param list[LogEntry] entries: List of LogEntry items.\n \"\"\"\n\n __slots__ = ()\n\n\nclass LogEntry(\n namedtuple(\n \"LogEntry\",\n [\n \"number\",\n \"command\",\n \"length\",\n \"session_key\",\n \"target_key\",\n \"second_key\",\n \"result\",\n \"tick\",\n \"digest\",\n ],\n )\n):\n \"\"\"YubiHSM log entry.\n\n :param int number: The sequence number of the entry.\n :param int command: The COMMAND executed.\n :param int length: The length of the command.\n :param int session_key: The ID of the Authentication Key for the session.\n :param int target_key: The ID of the key used by the command.\n :param int second_key: The ID of the secondary key used by the command, if\n applicable.\n :param int result: The result byte of the response.\n :param int tick: The YubiHSM system tick value when the command was run.\n :param bytes digest: A truncated hash of the entry and previous digest.\n \"\"\"\n\n __slots__ = ()\n FORMAT = \"!HBHHHHBL16s\"\n LENGTH = struct.calcsize(FORMAT)\n\n @property\n def data(self):\n \"\"\"Get log entry binary data.\n\n :return: The binary LogEntry data, excluding the digest.\n :rtype: bytes\n \"\"\"\n return struct.pack(self.FORMAT, *self)[:-16]\n\n @classmethod\n def parse(cls, data):\n \"\"\"Parse a LogEntry from its binary representation.\n\n :param bytes data: Binary data to unpack from.\n :return: The parsed object.\n :rtype: LogEntry\n \"\"\"\n return cls(*struct.unpack(cls.FORMAT, data))\n\n def validate(self, previous_entry):\n \"\"\"Validate the hash of a single log entry.\n\n Validates the hash of this entry with regard to the previous entry's\n hash. The previous entry is the LogEntry with the previous number,\n previous_entry.number == self.number - 1\n\n :param LogEntry previous_entry: The previous log entry to validate\n against.\n :return: True if the digest is correct, False if not.\n :rtype: bool\n \"\"\"\n\n if (self.number - previous_entry.number) & 0xFFFF != 1:\n raise ValueError(\"previous_entry has wrong number!\")\n\n digest = sha256(self.data + previous_entry.digest).digest()[:16]\n return constant_time.bytes_eq(self.digest, digest)\n","sub_path":"yubihsm/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":22263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"246759857","text":"import tkinter as tk\nimport variables as var\nimport main\n\n\ndef modifyui():\n root = tk.Tk()\n root.geometry('300x400')\n root.title('Modify Records')\n\n def modifyrecord():\n var.alu_id_formodify = aluidentry.get()\n var.fieldname_for_modify = _fieldnameformodify.get()\n var.newvalue_formodify = newvalueentry.get()\n # main.test()\n main.modify()\n\n _alu_id_formodify = tk.StringVar()\n _fieldnameformodify = tk.StringVar()\n _newvalue = tk.StringVar()\n\n enteraluidlabel = tk.Label(root, text='Enter Alumni ID of the record to modify')\n enteraluidlabel.pack()\n\n aluidentry = tk.Entry(root, textvariable=_alu_id_formodify)\n aluidentry.pack()\n\n fieldlist = ['First Name', 'Last Name', 'Date of Birth', 'Gender', 'Add Corr', 'Add Offc', 'Email ID',\n 'Mobile No.', 'Current City', 'Current Company', 'Designation', 'Session From', 'Session To', 'Branch']\n\n setfieldnamelabel = tk.Label(root, text='Select field name to change')\n setfieldnamelabel.pack()\n\n fieldnamedroplist = tk.OptionMenu(root, _fieldnameformodify, *fieldlist)\n fieldnamedroplist.config(width=20)\n fieldnamedroplist.pack()\n\n newvaluelabel = tk.Label(root, text='Change to:')\n newvaluelabel.pack()\n\n newvalueentry = tk.Entry(root, textvariable=_newvalue)\n newvalueentry.pack()\n\n modifybutton = tk.Button(root, command=modifyrecord, text='Modify record')\n modifybutton.pack()\n\n root.mainloop()\n","sub_path":"modifyUI.py","file_name":"modifyUI.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"386999263","text":"import visdom\r\nimport torch\r\n\r\n\r\nclass VisdomLineLog(object):\r\n def __init__(self, vis: visdom.Visdom, name: str):\r\n self.vis = vis\r\n self.name = name\r\n self.log_index = 0\r\n\r\n def append(self, value):\r\n self.vis.line(X=torch.FloatTensor([self.log_index]),\r\n Y=torch.FloatTensor([value]),\r\n win=self.name,\r\n update=\"append\" if self.log_index > 1 else None,\r\n opts={\"title\": self.name})\r\n self.log_index += 1\r\n\r\n\r\nclass VisdomLog(object):\r\n def __init__(self, name: str):\r\n self.name = name\r\n self.vis = visdom.Visdom(env=self.name)\r\n self.log_dict = {}\r\n\r\n def line(self, name: str, value):\r\n logger = self.log_dict.setdefault(name, VisdomLineLog(self.vis, name))\r\n logger.append(value)\r\n","sub_path":"train/logs/visdom_log.py","file_name":"visdom_log.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"479726212","text":"\n## Example from Siraj Raval https://www.youtube.com/watch?v=q555kfIFUCM&t=260s\n\nimport numpy as np\n\ndef nonlin(x,deriv=False):\n\tif(deriv==True):\n\t return x*(1-x)\n\n\treturn 1/(1+np.exp(-x))\n \nX = np.array([[0,0,1],\n [0,1,1],\n [1,0,1],\n [1,1,1]])\n \nY = np.array([[0],\n\t\t\t[1],\n\t\t\t[1],\n\t\t\t[0]])\n\nnp.random.seed(1)\n\n# randomly initialize our weights with mean 0\nweights0 = 2*np.random.random((3,4)) - 1\nweights1 = 2*np.random.random((4,1)) - 1\n\nfor j in range(60000):\n\n\t# Feed forward through layers 0, 1, and 2\n layer0 = X\n layer1 = nonlin(np.dot(layer0,weights0))\n layer2 = nonlin(np.dot(layer1,weights1))\n\n # how much did we miss the target value?\n layer2_error = Y - layer2\n\n if (j % 10000) == 0:\n print(str(np.mean(np.abs(layer2_error))))\n \n # in what direction is the target value?\n # were we really sure? if so, don't change too much.\n layer2_delta = layer2_error*nonlin(layer2,deriv=True)\n\n # how much did each k1 value contribute to the k2 error (according to the weights)?\n layer1_error = layer2_delta.dot(weights1.T)\n \n # in what direction is the target k1?\n # were we really sure? if so, don't change too much.\n layer1_delta = layer1_error * nonlin(layer1,deriv=True)\n\n weights1 += layer1.T.dot(layer2_delta)\n weights0 += layer0.T.dot(layer1_delta)\n\n\ninput_data = np.array([ [0,0,0], [1,1,1], [1,0,1], [1, 0, 0] ])\nexpected_output_data = np.array([[0, 1, 1, 0]])\n\ntest_layer0 = input_data\ntest_layer1 = nonlin(np.dot(test_layer0, weights0))\ntest_layer2 = nonlin(np.dot(test_layer1, weights1))\n\nprint(test_layer2)","sub_path":"neural_network/backpropagation.py","file_name":"backpropagation.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"475598838","text":"import fileinput\n\n\ndef find_sum(lst, output_num):\n \"\"\"\n Print the product of the 2 numbers whose sum is 2020\n\n :param lst: list of integers\n \"\"\"\n for i, current_number in enumerate(lst):\n for j, other_number in enumerate(lst):\n if j != i and (current_number + other_number == output_num):\n return True\n return False\n\n\ndef process(input_list: list) -> int:\n \"\"\"\n\n :param input_list:\n :return:\n \"\"\"\n total = 0\n preamble_length = 25\n preamble = input_list[:25]\n for i in range(25, len(input_list)):\n if not find_sum(preamble, input_list[i]):\n return input_list[i]\n preamble.pop(0)\n preamble.append(input_list[i])\n return total\n\n\nif __name__ == '__main__':\n lines = [int(i.strip('\\n')) for i in fileinput.input()]\n print(lines[0:10])\n output = process(lines)\n print(f'Output: {output}')\n","sub_path":"src/9_1_xmas_sum_in_preamble.py","file_name":"9_1_xmas_sum_in_preamble.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"178324480","text":"import pytest\nfrom masonite.testing import UnitTest\nfrom app.http.controllers.BlogController import BlogController\nfrom app.models.Toppage import Toppage\n\nimport json\n\nclass TestToppage(UnitTest):\n def setup_method(self):\n super().setup_method()\n self.model = Toppage.find(1)\n _response = self.json('/api/blog/toppage', None,\n method=\"GET\").container.make('Response')\n self.response = json.loads(_response)\n\n _response_en = self.json('/api/blog/toppage_en', None,\n method=\"GET\").container.make('Response')\n self.response_en = json.loads(_response_en)\n\n def test_url_available(self):\n assert self.route('/api/blog/toppage').ok()\n assert self.route('/api/blog/toppage_en').ok()\n\n def test_has_controller(self):\n assert self.route(\n '/api/blog/toppage').has_controller(BlogController)\n assert self.route(\n '/api/blog/toppage_en').has_controller(BlogController)\n\n def test_api(self):\n assert self.model.title == self.response['value']['toppage']['title']\n assert self.model.article_html == self.response['value']['toppage']['article_html']\n assert self.model.meta_description == self.response['value']['toppage']['meta_description']\n\n def test_api_en(self):\n assert self.model.title_en == self.response_en['value']['toppage']['title']\n assert self.model.article_html_en == self.response_en['value']['toppage']['article_html']\n assert self.model.meta_description == self.response_en['value']['toppage']['meta_description']","sub_path":"project/tests/unit/api/test_toppage.py","file_name":"test_toppage.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"374032643","text":"'''\nhttps://www.interviewbit.com/problems/permutations/\n\nPermutations\n\nGiven a collection of numbers, return all possible permutations.\n\nExample:\n\n\t[1,2,3] will have the following permutations:\n\n\t[1,2,3]\n\t[1,3,2]\n\t[2,1,3] \n\t[2,3,1] \n\t[3,1,2] \n\t[3,2,1]\n\nNOTE\nNo two entries in the permutation sequence should be the same.\nFor the purpose of this problem, assume that all the numbers in the collection are unique.\n'''\n\n'''\nSolution Outline:\n\tA simple permutation-generator starts with only the first element,\n\t Then at level 2, Makes 2 copies, Inserts second element at indices [0,1]\n\t At level 3, Makes 3 copies of the previous level permutations, Inserts third element at indices [0,1,2] for each copy\n\n\te.g.,\n\tA: [1, 2, 3]\n\tl0: []\n\tl1: [1]\n\tl2: [1] [1] -> [1,2], [2,1]\n\tl3: [1,2], [2,1] * 3 -> [1,2], [1,2], [1,2], [2,1], [2,1], [2,1]\n\t\t-> [1,2,3], [1,3,2], [3,1,2], [2,1,3], [2,3,1], [3,2,1]\n\n\tFor a backtracking algorithm, Do a DFS traversal, at each (level, i), Add A[level] at index i and backtrack.\n\tAt level == length(A), add current permutation to results list.\n\n A: [x, y, z]\n\n f([], x, 0):\n / \\\n f([x], y, 0) f([x], y, 1)\n / | \\ / | \\\nf([y,x], z, 0) f([y,x], z, 1) f([y,x], z, 2) f([x,y], z, 0) f([x,y], z, 1) f([x,y], z, 2)\n \\ \\ \\ \\ \\ \\ \n [z,y,x] [y,z,x] [y,x,z] [z,x,y] [x,z,y] [x,y,z]\n\n'''\nclass Solution:\n def permutations(self, A):\n def permutations_(prefix, level):\n if len(prefix) == len(A):\n permutations_list.append(prefix)\n return\n\n for i in xrange(len(prefix)+1):\n permutations_(prefix[:i] + [A[level]] + prefix[i:], level+1)\n\n permutations_list = []\n permutations_([], 0)\n return sorted(permutations_list)\n\n\n\nif __name__ == '__main__':\n s = Solution()\n assert s.permutations([]) == [[]]\n assert s.permutations([1]) == [[1]]\n assert s.permutations([1,2]) == [[1,2], [2,1]]\n assert map(lambda x: ''.join(x), s.permutations(\"abc\")) == \\\n [\"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"]\n\n","sub_path":"python/interviewbit/backtracking/permutations/permutations.py","file_name":"permutations.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"6170449","text":"###Assignment 4\r\n###The program will set and get country along with information such as population, are and population density. Also you can modify, save and edit country list along with thier information\r\n\r\n#the following class is named Country and it will set and get country informatioon\r\n\r\nclass Country: #creating a country class\r\n ###### creating the construct method\r\n def __init__(self,name,pop,area,continent): #creating construct and accpting name, population, area and content prameter\r\n self._name = name # setting construct to class variables. This description applies for line 10 to 13\r\n self._pop = pop #setting self._pop\r\n self._area = area #setting up self._area\r\n self._continent = continent #setting up self._continet variable\r\n self._popDensity = round((self._pop/self._area), 2) #calculating population density which is equal to population /area\r\n ####creating repr method\r\n def __repr__(self): #setting up repesentation method\r\n return self._name + \" is in \" + self._continent + \" with a population density of \" + str(self._popDensity) + \"pop is \" +str(self._pop) + \" area \" + str(self._area) #will produce a genrilzed description of the instant\r\n #China is in Asia with a population density of 4.56\r\n\r\n ###creating setting method named set populatin which it will set up population\r\n def setPopulation(self,pop): #define population\r\n self._pop = pop #setting self.pop to equal pop which is provided upon calling\r\n\r\n ###setting population density method\r\n def setPopDensity(self): #define setPop Density method\r\n self._popDensity = self._pop/self._area #setting self._popDensity by applying the equation of population/area\r\n\r\n ####setting the getter method for name\r\n def getName(self): #creating the getName method\r\n return self._name #returing the name that was set in the construct\r\n\r\n ####definging getting area method which geting contry's area\r\n def getArea(self):\r\n return self._area #it return the area of the country\r\n\r\n ####defing get population which return the population of the conuntry\r\n def getPopulation(self): #definging the function\r\n return self._pop #returing the population\r\n\r\n ###definging the get continent which return the continent of a selected country\r\n def getContinent(self): #define the function\r\n return self._continent #returns the inforatmoin to the user\r\n\r\n ###defingin the get population density which returns the density of a country\r\n def getPopDensity(self): #definging the function\r\n return self._popDensity #it return the population density to the user\r\n\r\n\r\n########Creating a class called CountryCatalogue which reads a file, import the content of a file and modify the information and then save them to a file\r\nclass CountryCatalogue: #creating a class\r\n ###creating a construct that takes in a file name\r\n def __init__(self, file):\r\n try: #it tries the following line incase the name of the file was faults\r\n self._file = open(file, \"r\") #open the file\r\n self._catalogue = {} #creating a dictionary type list\r\n self._cDictionary = {} #same as upove\r\n\r\n self._cFile = open(\"continent.txt\", \"r\") #opening continenet.txt file\r\n self._cFile.readline() #reading and ignoring the first line\r\n for line in self._cFile: #read everyline after the first line and then perform the following actiosn\r\n line = line.split(\",\") #spliting and convering text into lists\r\n self._cDictionary[line[0]]=line[1].replace(\"\\n\",\"\")\r\n\r\n #print(self._cDictionary)\r\n\r\n self._file.readline() #read the first line\r\n for line in self._file: #for everyline in the self._file do the follwing\r\n line = line.replace(\",\",\"\").split(\"|\") #replace and split the line into lists\r\n lineC = Country(line[0],int(line[1]),float(line[2]),self._cDictionary[line[0]]) #creating an object using the Country class\r\n self._catalogue[line[0]]=lineC\r\n self._cFile.close() #close self._cFile\r\n self._file.close() #close self._file\r\n #print(self._catalogue)\r\n\r\n except IOError : #creat an exception incase the user input the wrong file name\r\n print(\"Error: file was not found.\")\r\n sys.exit() #it exit the program\r\n\r\n except ValueError :#create an aexcpetion incase the user ad unreadable file\r\n print(\"Error: invalid file.\")\r\n sys.exit() #it exits the program\r\n\r\n except RuntimeError as error :\r\n print(\"Error:\", str(error))\r\n sys.exit() #it exits the program\r\n #print(self._catalogue)\r\n\r\n ###defing a add country method that takes in country name, population, area and continent\r\n def addCountry(self, name, pop, area, continent): #defining the function\r\n if name.title() in self._cDictionary: #check if name exist in the cDictionary\r\n print(\"Country does not exist, Please renter the information\") #it alerts that country already exist\r\n name = str(input(\"Please input country's name: \")).title() #it asks for country name\r\n pop = int(input(\"Please input {} population: \".format(name))) #it asks for population\r\n area = float(input(\"Please input {} area: \".format(name))) #it asks for area of the country\r\n continent = str(input(\"Please input {} continent: \".format(name))).title() #it asks for the continent name\r\n self.addCountry(name.title(), pop, area, continent.title()) #it calls it self to check and add the country\r\n else:#if name does not exist\r\n self._catalogue[name] = Country(name.title(), int(pop), float(area), continent.title()) #it creates an object\r\n self._cDictionary[name] = continent #it adds the name and continent to cDictionary\r\n print(\"{} has successfully been added to the list\".format(name)) #it alerts that the name was sucessfull\r\n #print(self._cDictionary)\r\n #print(self._catalogue)\r\n\r\n ### define a method that delet a country information from cDictionary and catalogue lists\r\n def deletCountry(self, name): #defien a function\r\n if name in self._cDictionary: #for every item in cDictionary\r\n self._cDictionary.pop(name) #remove the name from cDictionary\r\n self._catalogue.pop(name) #remove the name from catalogue\r\n print(\"country has been remvoed\") #it alerts upon completion\r\n\r\n else:\r\n print(\"name does not exist\") #it alerts if country does not exist\r\n\r\n\r\n ###define a mothod that finds a countyr information\r\n def findCountry(self, name): #define a function\r\n if name in self._cDictionary: #for every itme on the list\r\n print(name, \" Summary: \",self._catalogue[name]) #it prints summary of countyr name\r\n print(name, \" Area: \",self._catalogue[name].getArea()) #it prints out the area\r\n print(name, \" Population: \", self._catalogue[name].getPopulation()) #it prints out the population\r\n else: #otherwise\r\n print(\"Country does not exist\") #it alerts that the county does exist\r\n\r\n\r\n ### define a method that filter countries by contient inputed by user\r\n def filterCountriesByContinent(self, name): #define a function\r\n countries = set() #define a set\r\n for cat in self._catalogue: #for every item in catalogue\r\n if self._catalogue[cat].getContinent() == name: #if name matches to alist itme\r\n countries.add(cat) #it adds the country\r\n\r\n print(\"the following countries belong to the continent of \", name, \" are \", countries) #it prints out the contires list\r\n\r\n\r\n ### define and print country's catalouge to the user\r\n def printCountryCatalogue(self):\r\n for cat in self._catalogue:\r\n print(self._catalogue[cat])\r\n\r\n ### define a function that sets the popualtion of a selected country\r\n def setPopulationOfASelectedCountry(self,name, pop): #defining the method that takes two variables\r\n if name.title() in self._catalogue: #if name exist in the list\r\n self._catalogue[name].setPopulation(pop) #set the population number\r\n self._catalogue[name].setPopDensity() #set the population density\r\n print(name, \" population has been modified to \", self._catalogue[name].getPopulation()) #print the population\r\n print(name, \" population density is \", self._catalogue[name].getPopDensity()) #print the population density\r\n #print(self._catalogue[name]) #print self._catalogue[name]\r\n else:\r\n print(\"You can not change the population because {} does not exist in the database\".format(name))\r\n\r\n ### find country with the largest population\r\n def findCountryWithLargestPop(self): #defien the function\r\n initPop = 0 #define initial population\r\n countryName = \"\" #define country name\r\n for cat in self._catalogue: #for each item in self._catalogue\r\n if self._catalogue[cat].getPopulation() > initPop: #if country populatrion is bigger than init\r\n initPop = self._catalogue[cat].getPopulation() #set initPop to equal to new population\r\n countryName = self._catalogue[cat].getName() #set country to equal the contry with the larger population\r\n print(\"The country with the largest population is \", countryName,\": \", initPop) #print country and population\r\n\r\n ### define a method that find the smallest area\r\n def findCountryWithSmallestArea(self): #define the function\r\n lowestTrue = True #set lowstTrue to True\r\n country = \"\" #set country to equal nothing\r\n lowestArea = 0 #set lowerstArea to equal 0\r\n for cat in self._catalogue: #for each item on the list\r\n if lowestTrue: #if true\r\n lowestArea = self._catalogue[cat].getArea() #set lowestARea to the lowestArea\r\n lowestTrue = False #change lowestTrue to false\r\n if self._catalogue[cat].getArea() < lowestArea: #if the current is lowest area is lower than the curnet lowestArea\r\n lowestArea = self._catalogue[cat].getArea() #set lowestArea to the new area\r\n country = self._catalogue[cat].getName() #set country to the current country with the lowest area\r\n print(country, \" has the smallest area of \", lowestArea) #print the country and area\r\n\r\n ### the following method\r\n def filterCountriesByPopDensity(self, min, max):\r\n countries = set() #it create a set\r\n for cat in self._catalogue: #for every item in the list\r\n if self._catalogue[cat].getPopDensity()>=min and self._catalogue[cat].getPopDensity()<=max:\r\n countries.add(self._catalogue[cat].getName()) #it adds to the list\r\n print(\"The following countries population density falls between {} and {}\".format(min,max), \" are \" ,str(countries).replace(\"{\", \"\").replace(\"'\",\"\").replace(\"}\",\"\")) #it prints out the list\r\n\r\n ###define a functionthat find the most populous continent\r\n def findMostPopulousContinent(self): #define the function\r\n northAmerica={} #define a dict for north america\r\n naTotal=0 #define north america to equal 0\r\n southAmerica = {} #define a dict for south america\r\n saTotal=0 #define south america to equal 0\r\n asia={} ##define a dict for aisa\r\n aTotal=0 #define asia to equal 0\r\n africa={} #define a dict for africa\r\n afTotal = 0 #define africa to equal 0\r\n europe = {} #define a dict for europe\r\n eTotal = 0 #define europe to equal 0\r\n australia={} #define a dict for australia\r\n auTotal = 0 #define australia to equal 0\r\n other = {}\r\n oTotal = 0\r\n for cat in self._catalogue: #for every item on the list\r\n if self._catalogue[cat].getContinent() == 'North America': #if item is equal to North America\r\n northAmerica[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population number\r\n naTotal = naTotal + self._catalogue[cat].getPopulation() #incrument the total with the population\r\n elif self._catalogue[cat].getContinent() == 'Asia': #if item is equal to North America\r\n asia[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num\r\n aTotal = aTotal + self._catalogue[cat].getPopulation() #incrument the total with the population\r\n elif self._catalogue[cat].getContinent() == 'South America': #if item is equal to south america\r\n southAmerica[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num\r\n saTotal = saTotal + self._catalogue[cat].getPopulation()#incrument the total with the population\r\n elif self._catalogue[cat].getContinent() == 'Africa': #if item is equal to africa\r\n africa[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num\r\n afTotal = afTotal + self._catalogue[cat].getPopulation() #incrument the total with the population\r\n elif self._catalogue[cat].getContinent() == 'Europe': #if item is equal to europe\r\n europe[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num\r\n eTotal = eTotal + self._catalogue[cat].getPopulation() #incrument the total with the population\r\n elif self._catalogue[cat].getContinent() == 'Australia': #if item is equal to australia\r\n australia[cat]=self._catalogue[cat].getPopulation() #save the contry name and the population num\r\n auTotal = auTotal + self._catalogue[cat].getPopulation() #incrument the total with the population\r\n else:\r\n other[cat]=self._catalogue[cat].getPopulation() ##if item is equal to something else\r\n oTotal = oTotal + self._catalogue[cat].getPopulation() #other content\r\n test = {\"North America\": naTotal, \"South America\":saTotal, \"Asia\":aTotal,\"Africa\":afTotal, \"Europe\": eTotal}\r\n total = 0\r\n continent = \"\"\r\n for i in test:\r\n if test[i]> total:\r\n total = test[i]\r\n continent = i\r\n print(continent, \"is the most populated continent with total of \", total)\r\n if continent ==\"North America\": #if continent is equal to North America\r\n self.displayList(northAmerica) #calculate the information using displayList\r\n elif continent =='South America': #if continent is equal to South America\r\n self.displayList(southAmerica) #calculate the information using displayList\r\n elif continent.title() =='Europe': #if continent is equal to Europe\r\n self.displayList(europe) #calculate the information using displayList\r\n elif continent.title()=='Asia': #if continent is equal to Asia\r\n self.displayList(asia) #calculate the information using displayList\r\n elif continent.title() =='Africa': #if continent is equal to Africa\r\n self.displayList(africa) #calculate the information using displayList\r\n elif continent.title() =='Australia': #if continent is equal to Australia\r\n self.displayList(australia) #calculate the information using displayList\r\n else:\r\n self.displayList(other) #if continent is equal to other\r\n\r\n\r\n ##defining a method that saves the information to a file\r\n def saveCountryCatalogue(self, fileName): #define a function\r\n file = open(fileName,'w') #it opens fileName and then write\r\n writeFile = False #set writeFile to false\r\n for i in sorted(self._catalogue): #for every item that is sorted in a list\r\n output = self._catalogue[i].getName()+\" | \"+ self._catalogue[i].getContinent()+\" | \"+ str(self._catalogue[i].getPopulation())+\" | \"+ str(self._catalogue[i].getPopDensity()) +\"\\n\" #it genrate a string\r\n file.write(output) #it writes to a file\r\n print(\"the file was saved\") #it alert the file was saved\r\n file.close() #it closes the file\r\n\r\n ###The following function will return the list in a point form style\r\n def displayList(self, list): #define the method that takes a list as an argument\r\n for i in list: #for each item on the list\r\n print(i,\": \", list[i],end=\" \\n\") #print the itme and end with a new line\r\n\r\n","sub_path":"countryCatalogue.py","file_name":"countryCatalogue.py","file_ext":"py","file_size_in_byte":16567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"303597826","text":"import time\nimport math\nimport random\nimport matplotlib.pyplot as plt\nimport numpy\n\ndef mergeSort(n, nums=[], begin=True):\n\t#print \"nums when n = %s: %s\" %(n, nums)\n\tif n==0:\n\t\treturn\n\tif begin:\n\t\tfor i in range(n):\n\t\t\tnums.append(random.random())\n\tmid = n//2\n\tleft = nums[:mid]\n\tright = nums[mid:]\n\tif n>2:\n\t\tleft = mergeSort(len(left), left, False)\n\t\tright = mergeSort(len(right), right, False)\n\telse:\n\t\tif len(nums)==1:\n\t\t\treturn nums\n\t\tif len(nums)==2:\n\t\t\tif left[0]>right[0]:\n\t\t\t\treturn [right[0], left[0]]\n\t\t\telse: return [left[0], right[0]]\n\t\t# else:\n# \t\t\tmini = nums[0]\n# \t\t\tfor i in nums:\n# \t\t\t\tif imaxi:\n# \t\t\t\t\tmaxi = i\n# \t\t\tmiddle = nums[0]\n# \t\t\tfor i in nums:\n# \t\t\t\tif i!=mini and i!=maxi:\n# \t\t\t\t\tmiddle = i\n# \t\t\treturn [mini, middle, maxi]\n\tleft_head = 0\n\tright_head = 0\n\tcopy = []\n\twhile (left_head < len(left) and right_head2:\n\t\tfor i in range(0, len(nums)-end_sorted-1):\n\t\t\tif nums[i]>nums[i+1]:\n\t\t\t\ttemp = nums[i+1]\n\t\t\t\tnums[i+1] = nums[i]\n\t\t\t\tnums[i] = temp\n\t\tend_sorted = 0\n\t\tfor j in range(1,len(nums)-1)[::-1]:\n\t\t\tif nums[j]>=nums[j-1]:\n\t\t\t\tend_sorted+=1\n\t\t\telse: break\n\t\tbubbleSort(n, nums, end_sorted, False)\n\treturn nums\n\t\n\t","sub_path":"Homework/HW4/hw4_sorts_mm.py","file_name":"hw4_sorts_mm.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"75678485","text":"import requests\r\nimport os\r\nfrom bs4 import BeautifulSoup\r\nfrom woocommerce import API\r\n\r\nsession = requests.Session()\r\n\r\nprint('GardenScraper by Django Claughan \\n')\r\n\r\n# Get login details form setup file\r\nthisFolder = os.path.dirname(os.path.abspath(__file__))\r\nsetupFile = os.path.join(thisFolder, 'SETUP.txt')\r\nf = open(setupFile, \"r\")\r\ndetails = f.read().split('\\n') \r\n\r\nprint('Gardeners details')\r\nprint(details[4])\r\nprint(details[5])\r\nprint(details[6])\r\nprint('')\r\nprint('WooCommerce details')\r\nprint(details[9])\r\nprint(details[12])\r\nprint(details[15])\r\nprint('')\r\n\r\n# Initialise Woocommerce\r\nwcapi = API(\r\n url = details[9],\r\n consumer_key = details[12],\r\n consumer_secret = details[15],\r\n version = 'wc/v3'\r\n)\r\n\r\n# Package Gardeners login details\r\npayload = {\r\n 'AccountNumber': details[4], \r\n 'UserName': details[5],\r\n 'Password': details[6]\r\n}\r\n\r\n# Post the payload to the site to log in\r\ns = session.post(\"https://www.gardners.com/Account/LogOn\", data=payload)\r\n\r\n# Start loop to add products\r\nbreakout = 'y'\r\nwhile breakout != 'n':\r\n\r\n # Get Gardeners url from user\r\n url = input('Please paste Gardeners product url ')\r\n\r\n # Navigate to the next page and scrape the data\r\n page = session.get(url)\r\n\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n results = soup.find(id='body')\r\n\r\n # Get title\r\n searchBlock = results.find('div', class_='titleContributor')\r\n title = searchBlock.find('h1')\r\n title = (title.text)\r\n\r\n # Get author(s)\r\n author = searchBlock.find_all('a')\r\n\r\n # Add author(s) to title\r\n n = 0\r\n for i in author:\r\n if n == 0:\r\n title = title + ' by ' + i.text\r\n elif n == len(author) - 1:\r\n title = title + ' and ' + i.text\r\n else:\r\n title = title + ', ' + i.text\r\n n = n + 1\r\n print(title)\r\n\r\n\r\n # Get ISBN\r\n searchBlock = results.find('li', class_='isbn')\r\n isbn = searchBlock.find_all('span')\r\n isbn = isbn[1].text\r\n print(isbn)\r\n\r\n # Get RRP\r\n searchBlock = results.find('div', class_='purchaseBlock')\r\n rrp = searchBlock.find('span', class_='retailPrice')\r\n rrp = rrp.text\r\n print(rrp)\r\n\r\n # Get stock and change number for site\r\n stock = searchBlock.find(class_='availability')['data-copies']\r\n if int(stock) > 4:\r\n stock = 4\r\n elif int(stock) > 0:\r\n stock = stock\r\n else:\r\n stock = 0\r\n print(stock)\r\n\r\n # Get description\r\n searchBlock = results.find('div', class_='description')\r\n description = searchBlock.find(class_='productDescription')\r\n if description == None:\r\n description = ''\r\n else:\r\n description = description.text\r\n\r\n # Get image url\r\n searchBlock = results.find(class_='imageContainer')\r\n imageSrc = searchBlock.find('img')['data-zoom-image']\r\n imageSrc = 'https:' + imageSrc\r\n print(imageSrc)\r\n print('')\r\n\r\n # Package data to post to Woocommerce\r\n data = {\r\n 'images': [{\r\n \"src\": imageSrc\r\n },\r\n ],\r\n 'name': title,\r\n 'regular_price': rrp,\r\n 'short_description': description,\r\n 'sku': isbn,\r\n 'manage_stock': True,\r\n 'stock_quantity': stock,\r\n 'status': 'publish',\r\n 'type': 'simple'\r\n }\r\n\r\n # Post data to the Woocommerce API\r\n print(wcapi.post('products',data).json())\r\n \r\n print('')\r\n\r\n # Ask user if they wish to add more products\r\n breakout = input('Do you wish to add another product? (y/n) ')\r\n print('')\r\n\r\nprint('Program finished')","sub_path":"GardenScraper2 - Copy.py","file_name":"GardenScraper2 - Copy.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599168319","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom .views import ProjectViewSet, ProjectDashboardViewSet, PastProjectViewSet\n\napp_name = 'projects'\n\n\nrouter = DefaultRouter()\nrouter.register('project', ProjectViewSet, basename='project')\nrouter.register('dashboard', ProjectDashboardViewSet, basename='dashboard')\nrouter.register('past-project', PastProjectViewSet, basename='past-project')\n\nurlpatterns = [\n path('', include(router.urls)),\n]","sub_path":"dod/projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286795193","text":"#!/usr/bin/python3.4\n# -*- coding: utf-8 -*-\n# encoding: utf-8\n#客户端调用,用于查看API返回结果\n\nfrom OkcoinSpotAPI import OKCoinSpot\nfrom OkcoinFutureAPI import OKCoinFuture\nimport time\n\n#初始化apikey,secretkey,url\napikey = 'db052c78-71e1-4db6-ae7f-f9c659568c30'\nsecretkey = '93CD90F4E914E8FD08A7DC5423F260C7'\nokcoinRESTURL = 'www.okcoin.cn' #请求注意:国内账号需要 修改为 www.okcoin.cn \ntime_sleep = 5\n\n#现货API\nokcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey)\n\ntrade_record_file = open(\"./btcTradeRecord.txt\", \"a+\")\nprint (u'Trade Info ')\n\n#print (okcoinSpot.trade('btc_cny','buy_market',price=250))\n#print (okcoinSpot.trade('btc_cny','sell_market',amount=0.1))\n\nprint (u' 现货订单信息查询 ')\nprint (okcoinSpot.orderinfo('btc_cny', '185184673'))\nprint (okcoinSpot.get_fee('btc_cny', '185184673'))\n\ntrade_record_file.close()\n","sub_path":"python/tradeFirst.py","file_name":"tradeFirst.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"201750869","text":"'''\nFrontend for xESMF, exposed to users.\n'''\n\nimport numpy as np\nimport xarray as xr\nimport os\n\nfrom .backend import (esmf_grid, add_corner, esmf_regrid_build,\n esmf_regrid_finalize)\n\nfrom .smm import read_weights, apply_weights\n\n\ndef get_latlon_name(ds, boundary=False):\n if boundary:\n try:\n # COARDS netCDF complaint\n if 'lat_b' in ds.variables:\n lat_name = 'lat_b'\n lon_name = 'lon_b'\n # NETCDF CF 1.6 complaint\n elif 'latitude_b' in ds.variables:\n lat_name = 'latitude_b'\n lon_name = 'longitude_b'\n else:\n raise ValueError\n except ValueError:\n print(\n \"\"\"Must have coordinates compliant with NETCDF COARDS or CF conventions\"\"\"\n )\n else:\n try:\n # COARDS netCDF complaint\n if 'lat' in ds.variables:\n lat_name = 'lat'\n lon_name = 'lon'\n # NETCDF CF 1.6 complaint\n elif 'latitude' in ds.variables:\n lat_name = 'latitude'\n lon_name = 'longitude'\n else:\n raise ValueError\n except ValueError:\n print(\n 'Must have coordinates compliant with NETCDF COARDS or CF conventions'\n )\n return lat_name, lon_name\n\n\ndef as_2d_mesh(lon, lat):\n\n if (lon.ndim, lat.ndim) == (2, 2):\n assert lon.shape == lat.shape, 'lon and lat should have same shape'\n elif (lon.ndim, lat.ndim) == (1, 1):\n lon, lat = np.meshgrid(lon, lat)\n else:\n raise ValueError('lon and lat should be both 1D or 2D')\n\n return lon, lat\n\n\ndef ds_to_ESMFgrid(ds,\n need_bounds=False,\n lat=None,\n lon=None,\n lat_b=None,\n lon_b=None,\n periodic=None,\n append=None):\n '''\n Convert xarray DataSet or dictionary to ESMF.Grid object.\n\n Parameters\n ----------\n ds : xarray DataSet or dictionary\n Contains variables ``lon``, ``lat``,\n and optionally ``lon_b``, ``lat_b`` if need_bounds=True.\n\n Shape should be ``(Nlat, Nlon)`` or ``(Ny, Nx)``,\n as normal C or Python ordering. Will be then tranposed to F-ordered.\n\n need_bounds : bool, optional\n Need cell boundary values?\n\n periodic : bool, optional\n Periodic in longitude?\n\n Returns\n -------\n grid : ESMF.Grid object\n\n '''\n\n # use np.asarray(dr) instead of dr.values, so it also works for dictionary\n if lat is None and lon is None:\n lon_name, lat_name = get_latlon_name(ds)\n else:\n lat_name = lat\n lon_name = lon\n lon = np.asarray(ds[lon_name])\n lat = np.asarray(ds[lat_name])\n lon, lat = as_2d_mesh(lon, lat)\n\n # tranpose the arrays so they become Fortran-ordered\n grid = esmf_grid(lon.T, lat.T, periodic=periodic)\n\n if need_bounds:\n if lat_b is None and lon_b is None:\n lon_b, lat_b = get_latlon_name(ds, boundary=True)\n lon_b = np.asarray(ds[lon_b])\n lat_b = np.asarray(ds[lat_b])\n lon_b, lat_b = as_2d_mesh(lon_b, lat_b)\n add_corner(grid, lon_b.T, lat_b.T)\n\n return grid, lon.shape\n\n\nclass Regridder(object):\n def __init__(self,\n ds_in,\n ds_out,\n method,\n periodic=False,\n filename=None,\n reuse_weights=False,\n lat_in=None,\n lon_in=None,\n lat_b_in=None,\n lon_b_in=None,\n lat_out=None,\n lon_out=None,\n lat_b_out=None,\n lon_b_out=None):\n \"\"\"\n Make xESMF regridder\n\n Parameters\n ----------\n ds_in, ds_out : xarray DataSet, or dictionary\n Contain input and output grid coordinates. Look for variables\n ``lon``, ``lat``, and optionally ``lon_b``, ``lat_b`` for\n conservative method.\n\n Shape can be 1D (Nlon,) and (Nlat,) for rectilinear grids,\n or 2D (Ny, Nx) for general curvilinear grids.\n Shape of bounds should be (N+1,) or (Ny+1, Nx+1).\n\n method : str\n Regridding method. Options are\n\n - 'bilinear'\n - 'conservative', **need grid corner information**\n - 'patch'\n - 'nearest_s2d'\n - 'nearest_d2s'\n\n periodic : bool, optional\n Periodic in longitude? Default to False.\n Only useful for global grids with non-conservative regridding.\n Will be forced to False for conservative regridding.\n\n filename : str, optional\n Name for the weight file. The default naming scheme is::\n\n {method}_{Ny_in}x{Nx_in}_{Ny_out}x{Nx_out}.nc\n\n e.g. bilinear_400x600_300x400.nc\n\n reuse_weights : bool, optional\n Whether to read existing weight file to save computing time.\n False by default (i.e. re-compute, not reuse).\n\n lat_in : string, optional\n Latitude name in ds_in xarray.DataArray. If none it will try to\n detect if the DataArray is netCDF CF 1.6 or COARDS compliant\n\n lon_in : string, optional\n Latitude name in ds_in xarray.DataArray. If none it will try to\n if the DataArray is netCDF CF 1.6 or COARDS compliant\n\n lat_b_in : string, optional\n Latitude name in ds_in xarray.DataArray. If none it will try to\n detect if the DataArray is netCDF CF 1.6 or COARDS compliant\n\n lon_b_in : string, optional\n Latitude name in ds_in xarray.DataArray. If none it will try to\n detect if the DataArray is netCDF CF 1.6 or COARDS compliant\n\n lat_out : string, optional\n Latitude name in ds_in xarray.DataArray. If none it will try to\n detect if the DataArray is netCDF CF 1.6 or COARDS compliant\n\n lon_out : string, optional\n Latitude name in ds_in xarray.DataArray. If none it will try to\n detect if the DataArray is netCDF CF 1.6 or COARDS compliant\n\n lat_b_out : string, optional\n Latitude name in ds_in xarray.DataArray. If none it will try to\n detect if the DataArray is netCDF CF 1.6 or COARDS compliant\n\n lon_b_out : string, optional\n Latitude name in ds_in xarray.DataArray. If none it will try to\n detectif the DataArray is netCDF CF 1.6 or COARDS compliant\n\n Returns\n -------\n regridder : xESMF regridder object\n\n \"\"\"\n\n # record basic switches\n if method == 'conservative':\n self.need_bounds = True\n periodic = False # bound shape will not be N+1 for periodic grid\n else:\n self.need_bounds = False\n\n self.method = method\n self.periodic = periodic\n self.reuse_weights = reuse_weights\n\n # get latitude and longitude names for ds_in and ds_out\n if lat_in is None and lon_in is None:\n self.lat_name_in, self.lon_name_in = get_latlon_name(ds_in)\n else:\n self.lat_name_in = lat_in\n self.lon_name_in = lon_in\n if lat_b_in is None and lon_b_in is None:\n self.lat_b_name_in, self.lon_b_name_in = get_latlon_name(\n ds_in, boundary=True)\n else:\n self.lat_b_name_in = lat_b_in\n self.lon_b_name_in = lon_b_in\n if lat_out is None and lon_out is None:\n self.lat_name_out, self.lon_name_out = get_latlon_name(ds_out)\n else:\n self.lat_name_out = lat_out\n self.lon_name_out = lon_out\n if lat_b_out is None and lon_b_out is None:\n self.lat_b_name_out, self.lon_b_name_out = get_latlon_name(\n ds_out, boundary=True)\n else:\n self.lat_b_name_out = lat_b_out\n self.lon_b_name_out = lon_b_out\n\n # construct ESMF grid, with some shape checking\n self._grid_in, shape_in = ds_to_ESMFgrid(\n ds_in,\n need_bounds=self.need_bounds,\n periodic=periodic,\n lat=self.lat_name_in,\n lon=self.lon_name_in,\n lat_b=self.lat_b_name_in,\n lon_b=self.lon_b_name_in)\n self._grid_out, shape_out = ds_to_ESMFgrid(\n ds_out,\n need_bounds=self.need_bounds,\n lat=self.lat_name_out,\n lon=self.lon_name_out,\n lat_b=self.lat_b_name_out,\n lon_b=self.lon_b_name_out)\n\n # record output grid and metadata\n self._lon_out = np.asarray(ds_out[self.lon_name_out])\n self._lat_out = np.asarray(ds_out[self.lat_name_out])\n\n if self._lon_out.ndim == 2:\n try:\n self.lon_dim = self.lat_dim = ds_out[self.lon_name_out].dims\n except:\n self.lon_dim = self.lat_dim = ('y', 'x')\n\n self.horiz_dims = self.lon_dim\n\n elif self._lon_out.ndim == 1:\n try:\n self.lon_dim = ds_out[self.lon_name_out].dims\n self.lat_dim = ds_out[self.lat_name_out].dims\n except:\n self.lon_dim = self.lon_name_out\n self.lat_dim = self.lat_name_out\n\n self.horiz_dims = (self.lat_dim, self.lon_dim)\n\n # get grid shape information\n # Use (Ny, Nx) instead of (Nlat, Nlon),\n # because ds can be general curvilinear grids.\n # For rectilinear grids, (Ny, Nx) == (Nlat, Nlon)\n self.Ny_in, self.Nx_in = shape_in\n self.Ny_out, self.Nx_out = shape_out\n self.N_in = self.Ny_in * self.Nx_in\n self.N_out = self.Ny_out * self.Nx_out\n\n if filename is None:\n self.filename = self._get_default_filename()\n else:\n self.filename = filename\n\n # get weight matrix\n self._write_weight_file()\n self.A = read_weights(self.filename, self.N_in, self.N_out)\n\n def _get_default_filename(self):\n # e.g. bilinear_400x600_300x400.nc\n filename = ('{0}_{1}x{2}_{3}x{4}'.format(\n self.method, self.Ny_in, self.Nx_in, self.Ny_out, self.Nx_out))\n if self.periodic:\n filename += '_peri.nc'\n else:\n filename += '.nc'\n\n return filename\n\n def _write_weight_file(self):\n\n if os.path.exists(self.filename):\n if self.reuse_weights:\n print('Reuse existing file: {}'.format(self.filename))\n return # do not compute it again, just read it\n else:\n print(\n 'Overwrite existing file: {} \\n'.format(self.filename),\n 'You can set reuse_weights=True to save computing time.')\n os.remove(self.filename)\n else:\n print('Create weight file: {}'.format(self.filename))\n\n regrid = esmf_regrid_build(\n self._grid_in, self._grid_out, self.method, filename=self.filename)\n esmf_regrid_finalize(regrid) # only need weights, not regrid object\n\n def clean_weight_file(self):\n \"\"\"\n Remove the offline weight file on disk.\n\n To save the time on re-computing weights, you can just keep the file,\n and set \"reuse_weights=True\" when initializing the regridder next time.\n \"\"\"\n if os.path.exists(self.filename):\n print(\"Remove file {}\".format(self.filename))\n os.remove(self.filename)\n else:\n print(\"File {} is already removed.\".format(self.filename))\n\n def __repr__(self):\n info = ('xESMF Regridder \\n'\n 'Regridding algorithm: {} \\n'\n 'Weight filename: {} \\n'\n 'Reuse pre-computed weights? {} \\n'\n 'Input grid shape: {} \\n'\n 'Output grid shape: {} \\n'\n 'Output grid dimension name: {} \\n'\n 'Periodic in longitude? {}'.format(\n self.method, self.filename, self.reuse_weights,\n (self.Ny_in, self.Nx_in), (self.Ny_out, self.Nx_out),\n self.horiz_dims, self.periodic))\n\n return info\n\n def __call__(self, a):\n \"\"\"\n Shortcut for ``regrid_numpy()`` and ``regrid_dataarray()``.\n\n Parameters\n ----------\n a : xarray DataArray or numpy array\n\n Returns\n -------\n xarray DataArray or numpy array\n Regridding results. Type depends on input.\n \"\"\"\n # TODO: DataSet support\n\n if isinstance(a, np.ndarray):\n regrid_func = self.regrid_numpy\n elif isinstance(a, xr.DataArray):\n regrid_func = self.regrid_dataarray\n else:\n raise TypeError(\"input must be numpy array or xarray DataArray!\")\n\n return regrid_func(a)\n\n def regrid_numpy(self, indata):\n \"\"\"\n Regrid pure numpy array. Shape requirement is the same as\n ``regrid_dataarray()``\n\n Parameters\n ----------\n indata : numpy array\n\n Returns\n -------\n outdata : numpy array\n\n \"\"\"\n\n # check shape\n shape_horiz = indata.shape[-2:] # the rightmost two dimensions\n assert shape_horiz == (self.Ny_in, self.Nx_in), (\n 'The horizontal shape of input data is {}, different from that of'\n 'the regridder {}!'.format(shape_horiz, (self.Ny_in, self.Nx_in)))\n\n outdata = apply_weights(self.A, indata, self.Ny_out, self.Nx_out)\n return outdata\n\n def regrid_dataarray(self, dr_in):\n \"\"\"\n Regrid xarray DataArray, track metadata.\n\n Parameters\n ----------\n dr_in : xarray DataArray\n The rightmost two dimensions must be the same as ``ds_in``.\n Can have arbitrary additional dimensions.\n\n Examples of valid shapes\n\n - (Nlat, Nlon), if ``ds_in`` has shape (Nlat, Nlon)\n - (N2, N1, Ny, Nx), if ``ds_in`` has shape (Ny, Nx)\n\n Returns\n -------\n dr_out : xarray DataArray\n On the same horizontal grid as ``ds_out``,\n with extra dims in ``dr_in``.\n\n Assuming ``ds_out`` has the shape of (Ny_out, Nx_out),\n examples of returning shapes are\n\n - (Ny_out, Nx_out), if ``dr_in`` is 2D\n - (N2, N1, Ny_out, Nx_out), if ``dr_in`` has shape\n (N2, N1, Ny, Nx)\n\n \"\"\"\n\n # apply regridding to pure numpy array\n outdata = self.regrid_numpy(dr_in.values)\n\n # track metadata\n varname = dr_in.name\n extra_dims = dr_in.dims[0:-2]\n\n dr_out = xr.DataArray(\n outdata, dims=extra_dims + self.horiz_dims, name=varname)\n dr_out.coords[self.lon_name_out] = xr.DataArray(\n self._lon_out, dims=self.lon_dim)\n dr_out.coords[self.lat_name_out] = xr.DataArray(\n self._lat_out, dims=self.lat_dim)\n\n # append extra dimension coordinate value\n for dim in extra_dims:\n dr_out.coords[dim] = dr_in.coords[dim]\n\n dr_out.attrs['regrid_method'] = self.method\n\n return dr_out\n\n def regrid_dataset(self, ds_in):\n raise NotImplementedError(\"Only support regrid_dataarray() for now.\")\n","sub_path":"xesmf/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":15397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11714358","text":"import sys\nimport json\nimport os\nimport re\nimport requests\nimport lxml.html\nimport openai\n\n\ndef get_article_summary(text, max_tokens):\n api_key = ''\n openai.api_key = api_key\n openai.organization = ''\n\n response = openai.Completion.create(\n engine=\"davinci\",\n prompt=text,\n max_tokens=max_tokens,\n top_p=1.0,\n frequency_penalty=0.0,\n presence_penalty=0.0,\n stop=[\"\\n\"])\n\n return response\n\nif __name__ == '__main__':\n filename = sys.argv[1]\n with open(filename) as f:\n data = json.load(f)\n\n output = []\n for article in data:\n output_text = []\n title = get_article_summary(article['title'][0].replace('| Southern Living', ''), 60)\n for text in article['text']:\n input_text = text + \"\\n\\ntl;dr:\"\n\n summary = get_article_summary(input_text, 90)\n output_text.append(summary['choices'][0]['text'])\n\n output.append({\n 'source_url': article['source_url'],\n 'source_text': article['text'],\n 'zobot': output_text,\n 'source_title': article['title'][0],\n 'output_tile': title['choices'][0]['text'].replace('| Southern Living', '')\n })\n\n json.dump(output, sys.stdout, indent=4)\n\n","sub_path":"data/scripts/zobot.py","file_name":"zobot.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372896818","text":"from copy import deepcopy\nfrom random import choice\n\n\ndef convert_repr(play_func):\n def wrapped_play_func(current_state, player):\n if current_state:\n current_state = from_str(current_state)\n next_state = play_func(current_state, player)\n return to_str(next_state)\n return wrapped_play_func\n\n\ndef get_next_opt_state(state=None, player='x'):\n if not state:\n state = [['e', 'e', 'e'],\n ['e', 'e', 'e'],\n ['e', 'e', 'e']]\n choice(state)[choice((0, 1, 2))] = player\n return state\n\n best_score = -2\n best_move = state\n for next_state in get_next_states(state, player):\n score = get_state_score(next_state,\n 'o' if player == 'x' else 'x',\n max_player=False,\n best_possible_score=1)\n if score > best_score:\n best_score = score\n best_move = next_state\n\n final_state = get_winning_state(best_move) or is_final(best_move)\n if final_state:\n return final_state\n\n return best_move\n\n\ndef get_state_score(state, player, max_player, best_possible_score):\n if get_winning_state(state):\n if max_player:\n return -best_possible_score\n elif not max_player:\n return best_possible_score\n elif is_final(state):\n return 0\n\n best_max_score = -best_possible_score - 1\n best_min_score = best_possible_score + 1\n for next_state in get_next_states(state, player):\n score = get_state_score(next_state,\n 'o' if player == 'x' else 'x',\n max_player=not max_player,\n best_possible_score=best_possible_score)\n if max_player:\n if score > best_max_score:\n best_max_score = score\n if best_max_score == best_possible_score:\n return best_max_score\n else:\n if score < best_min_score:\n best_min_score = score\n if best_min_score == -best_possible_score:\n return best_min_score\n if max_player:\n return best_max_score\n else:\n return best_min_score\n\n\ndef get_next_states(state, player):\n next_states = []\n for i, row in enumerate(state):\n for j, col_val in enumerate(row):\n if col_val == 'e':\n next_state = list(state)\n next_state[i] = list(row)\n next_state[i][j] = player\n next_states.append(next_state)\n return next_states\n\n\ndef get_winning_state(state):\n def upcase_straight_line(player, *indices):\n winning_state = deepcopy(state)\n player = player.upper()\n for r, c in indices:\n winning_state[r][c] = player\n return winning_state\n\n for i, row in enumerate(state):\n if row[0] == row[1] == row[2] != 'e':\n return upcase_straight_line(row[0], (i, 0), (i, 1), (i, 2))\n\n for j, col in enumerate(zip(*state)):\n if col[0] == col[1] == col[2] != 'e':\n return upcase_straight_line(col[0], (0, j), (1, j), (2, j))\n\n if state[0][0] == state[1][1] == state[2][2] != 'e':\n return upcase_straight_line(state[0][0], (0, 0), (1, 1), (2, 2))\n\n if state[0][2] == state[1][1] == state[2][0] != 'e':\n return upcase_straight_line(state[0][2], (0, 2), (1, 1), (2, 0))\n\n\ndef is_final(state):\n for row in state:\n if 'e' in row:\n return False\n return state\n\nfrom_str = lambda state: [list(state[i:i+3]) for i in (0, 3, 6)]\nto_str = lambda state: ''.join([''.join(r) for r in state])\n","sub_path":"coding_challenge/tic_tac_toe_play.py","file_name":"tic_tac_toe_play.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"323774946","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#update:2014-11-12 by 250305240@qq.com\n\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.shortcuts import render_to_response,RequestContext\nfrom django.contrib.auth.decorators import login_required\nfrom webapp.common.CommonPaginator import SelfPaginator\nfrom webapp.view.admin.permission import PermissionVerify\nfrom webapp.view.mysqlfab.mysqlfab_forms import MysqlfabMasterForm\nfrom webapp.models import MysqlfabMaster\n\n\n@login_required\n@PermissionVerify()\ndef ListMysqlFab(request):\n mList = MysqlfabMaster.objects.all()\n\n #分页功能\n lst = SelfPaginator(request,mList, 20)\n\n kwvars = {\n 'lPage':lst,\n 'request':request,\n }\n return render_to_response('mysqlfab/mysqlfab.list.html',kwvars,RequestContext(request))\n\n@login_required\n@PermissionVerify()\ndef AddMysqlFab(request):\n if request.method == \"POST\":\n form = MysqlfabMasterForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('listmysqlfaburl'))\n else:\n form = MysqlfabMasterForm()\n\n kwvars = {\n 'form':form,\n 'request':request,\n }\n return render_to_response('mysqlfab/mysqlfab.add.html',kwvars,RequestContext(request))\n\n@login_required\n@PermissionVerify()\ndef EditMysqlFab(request,ID):\n iModels = MysqlfabMaster.objects.get(id=ID)\n if request.method == \"POST\":\n form = MysqlfabMasterForm(request.POST,instance=iModels)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('listmysqlfaburl'))\n else:\n form = MysqlfabMasterForm(instance=iModels)\n kwvars = {\n 'ID':ID,\n 'form':form,\n 'request':request,\n }\n return render_to_response('mysqlfab/mysqlfab.edit.html',kwvars,RequestContext(request))\n\n@login_required\n@PermissionVerify()\ndef DeleteMysqlFab(request,ID):\n MysqlfabMaster.objects.filter(id = ID).delete()\n return HttpResponseRedirect(reverse('listmysqlfaburl'))\n\n","sub_path":"webapp/view/mysqlfab/mysqlfab.py","file_name":"mysqlfab.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"346943348","text":"from flask import Flask, render_template, request\nimport sqlite3 as sql\napp = Flask(__name__)\n\n@app.route('/home')\ndef home():\n return render_template('home.html')\n\n@app.route('/submitscore')\ndef new_student():\n return render_template('submitscore.html')\n\n@app.route('/addrec',methods = ['POST','GET'])\ndef addrec():\n # if request.method == 'GET':\n # try:\n name = request.form['name']\n score = request.form['score']\n\n\n\n with sql.connect(\"/var/www/ScorecardResearch/db/scores.db\") as con:\n cur = con.cursor()\n\n cur.execute(\"INSERT INTO scores (name,score) VALUES (?,?)\",(name,score))\n\n con.commit()\n msg = \"Record successfully added\"\n # except:\n # con.rollback()\n # msg = \"error in insert operation\"\n\n # finally:\n #return render_template(\"results.html\",msg = msg)\n con.close()\n con = sql.connect(\"/var/www/ScorecardResearch/db/scores.db\")\n con.row_factory = sql.Row\n\n cur = con.cursor()\n cur.execute(\"select * from scores ORDER BY Score DESC\")\n\n rows = cur.fetchall();\n return render_template(\"leaderboard.html\",rows=rows)\n\n #return render_template(\"leaderboard.html\")\n #con.close()\n@app.route('/leaderboard')\ndef list():\n con = sql.connect(\"/var/www/ScorecardResearch/db/scores.db\")\n con.row_factory = sql.Row\n\n cur = con.cursor()\n cur.execute(\"select * from scores ORDER BY Score DESC\")\n\n rows = cur.fetchall();\n return render_template(\"leaderboard.html\",rows=rows)\n\nif __name__ == '__main__':\n app.run(host='192.168.1.16')\n #app.run(debug=True)\n","sub_path":"newv1.py","file_name":"newv1.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167182880","text":"'''\nCloudFront Invalidation\n'''\n\ntry:\n import boto3\n import random\n import time\n import datetime\n from botocore.exceptions import ClientError\nexcept ImportError:\n HAS_BOTO = False\n\nclient = boto3.client('cloudfront')\n\n##샘플 변수\nDISTRIBUTIONID='E12OX8RSSI1M70'\nBUCKETNAME = 'cf-prefetch'\nKEY = 'test.txt'\n\n##Invalidation을 위한 랜덤 해쉬값 생성\nHASH = random.getrandbits(16)\nNOW = datetime.datetime.now()\nTIMEHASH = time.mktime(NOW.timetuple())\nCALLERREFERENCE = str(HASH+TIMEHASH)\n\n##Path, CF ID 확인(Invalidation 생성 전 체크)\ndef check_invalidation_path(distributionId, bucketName, key):\n print('[Started check_invalidation_path]')\n try:\n get_distribution_response = client.get_distribution(\n Id = distributionId\n )\n for i in get_distribution_response.get('Distribution').get('DistributionConfig').get('Origins').get('Items'):\n if(bucketName == i.get('DomainName').split('.s3')[0]):\n if(i.get('OriginPath') != ''):\n print(key.split(i.get('originPath'), 1)[1])\n print('[Completed check_invalidation_path]')\n return key.split(i.get('originPath'), 1)[1]\n else:\n print(key)\n print('[Completed check_invalidation_path]')\n return key\n except ClientError as e:\n print('Failed check_invInvalidation_path: {}' . format(e))\n\n##Invalidatoin 생성\ndef create_invalidation(distributionId, invalidationPath):\n print('[Started create_invalidation]')\n try:\n create_invalidation_response = client.create_invalidation(\n DistributionId = distributionId,\n InvalidationBatch = {\n 'Paths': {\n 'Quantity': 1,\n 'Items': [\n invalidationPath,\n ]\n },\n 'CallerReference': CALLERREFERENCE\n }\n )\n print(create_invalidation_response)\n print('[Completed create_invalidation]')\n return create_invalidation_response\n except ClientError as e:\n print('Failed create_invalidation: {}' . format(e))\n\n##Invalidation 상태 확인\ndef check_invalidation(distributionId, invalidationId):\n timewait = 0\n status = None\n print('[Started check_invalidation]')\n while 1:\n print('Inprogress Invalidation... {}'.format(timewait))\n try:\n get_invalidation_response = client.get_invalidation(\n DistributionId = distributionId,\n Id = invalidationId\n )\n status = get_invalidation_response.get('Invalidation').get('Status')\n if(status == 'Completed'):\n print(get_invalidation_response)\n print('[Completed Check_Invalidation]')\n return get_invalidation_response\n else:\n timewait += 5\n time.sleep(5)\n except ClientError as e:\n print('Failed check_Invalidation: {}' .format(e))\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n\n cloudfrontPath = check_invalidation_path(DISTRIBUTIONID, BUCKETNAME, KEY)\n invalidation_response = create_invalidation(DISTRIBUTIONID, '/' + cloudfrontPath)\n invalidation_check_response = check_invalidation(DISTRIBUTIONID, invalidation_response.get('Invalidation').get('Id'))\n\n print('Completed --- {}seconds ---'.format(time.time() - start_time))\n","sub_path":"invalidation_module.py","file_name":"invalidation_module.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372597394","text":"from pandas.compat import u\nimport matplotlib.pyplot as plt\nimport re\nimport numpy as np\nimport pandas as pd\nfrom unidecode import unidecode\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom sklearn.model_selection import train_test_split\nfrom nltk.tokenize.casual import casual_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation as LDiA\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.ensemble import RandomForestClassifier\n\n# TODO hide the names and load them from CSV\n# Remove the real names\n\n\ndef remove_stop_word(sentence, stopwords):\n temp = sentence.split(' ')\n temp = [x for x in temp if x not in stopwords]\n temp = ' '.join(temp)\n return temp\n\n\nnames = ['Jose Cáliz', 'Cristhiam Sánchez Jaramillo',\n 'Mateo Varela Martínez', 'Nicholas Benedetti Arévalo']\n\nstopwords = pd.read_csv('./data_grupo/stopwords.csv')['word'].to_list()\n\nexpression_1 = r'\\[.*?\\]\\s{0,}(.*?)\\:\\s{0,}(.*)'\nre_expression_1 = re.compile(expression_1)\n\nexpression_2 = r'^[^\\[].*'\nre_expression_2 = re.compile(expression_2)\n\nquote_expression = r'\\u200e\\[[0-9]{1,}\\/[0-9]{1,}\\/[0-9]{1,},.*'\nre_quote = re.compile(quote_expression)\n\nsentences = list()\nauthor = list()\n\nwith open('./data_grupo/_chat.txt', 'r', encoding=\"utf-8\") as f:\n count = 0\n for row in f:\n m_1 = re_expression_1.match(row)\n m_2 = re_expression_2.match(row)\n try:\n if(m_1):\n current_author = m_1.group(1)\n author.append(m_1.group(1))\n\n temp_sentence = m_1.group(2).lower()\n sentences.append(temp_sentence)\n elif(m_2):\n author.append(current_author)\n\n temp_sentence = m_2.group(0).lower()\n sentences.append(temp_sentence)\n except Exception as e:\n print(Exception)\n print(row)\n\ndata = pd.DataFrame({'Sentence': sentences, 'Author': author})\ndata = data[data.Author.isin(names)]\nmask_not_quotes = [False if re_quote.match(x)\n else True for x in data['Sentence']]\nmask_not_empty = [False if len(x) == 0\n else True for x in data['Sentence']]\n\n# Remove messages that are quotes\ndata['quote'] = mask_not_quotes\ndata['empty'] = mask_not_empty\n\ndata = data[(data['quote'] & data['empty'])]\n\n# Get the labels for each author\ntotal_labels = data['Author'].str.replace(' ', '').to_list()\nclassnames, indices = np.unique(total_labels, return_inverse=True)\ndata['label'] = indices\n\ndata.head(10)\nmessages = data['Sentence'].to_list()\nlabel = data['label'].to_list()\n\n# Prueba con LDiA\ncounter = CountVectorizer(tokenizer=casual_tokenize)\nbow_vector = pd.DataFrame(counter.fit_transform(raw_documents=messages)\n .toarray())\n\n# Extaer el vocabulario para ponérselo a las columnas de bow_vector\nvocabulario = counter.vocabulary_.values()\ncolumn_nums, terms = zip(*sorted(zip(counter.vocabulary_.values(),\n counter.vocabulary_.keys())))\nbow_vector.columns = terms\nldia = LDiA(n_components=30, learning_method='batch')\ntopic_vectors = ldia.fit_transform(bow_vector)\n\n# Split\nresults_train = []\nresults_test = []\nfor i in range(4):\n label = [1 if x == i else 0 for x in data['label']]\n X_train, X_test, y_train, y_test = train_test_split(topic_vectors, label,\n test_size=0.3)\n\n # Do the LDA\n lda = LDA(n_components=1)\n lda.fit(X_train, y_train)\n y_pred = lda.predict(X_test)\n\n results_train.append(round(float(lda.score(X_train, y_train)), 2))\n results_test.append(round(float(lda.score(X_test, y_test)), 2))\n print(i)\n\nprint(results_train)\nprint(results_test)\n\nresults = dict(zip(classnames, results))\ntopic_vector_df = pd.DataFrame(ldia.components_.T, index=terms)\ntopic_vector_df[10].nlargest(20)\n\n\ndata = [u'\\\\x96 Jose caliz']\ndata[0].decode('utf-8')\n\nno_unicode = pd.Series(['Steve', 'Jason', 'Jake'])\n#yes_unicode = pd.Series(['tea', 'caf\\xe9', 'beer'])\n","sub_path":"TFIDF.py","file_name":"TFIDF.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179835622","text":"from django.conf.urls import url, include #gives us access to function url\nfrom . import views # to import the sibling VIEW file\n\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^process$', views.process),\n url(r'^result$', views.result), \n url(r'^reset$', views.reset),\n # url(r'^(?P\\d+)$', views.show),\n \n]","sub_path":"apps/word/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"499500291","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# doc du lieu tu file\nf = open('../Data/ex1data1.txt', 'r')\nx = f.readline()\nX = []\ny = []\nwhile x != \"\":\n z = x.split(',')\n X.append(float(z[0]))\n y.append(float(z[1]))\n\n x = f.readline()\n\nX = np.array([X]).T\ny = np.array([y]).T\nprint(X)\n\n# X la du lieu cot dau tien\n# y la du lieu cot thu 2\n\n# thuat toan hoi quy\n# tao cot 1\none = np.ones((X.shape[0], 1))\nprint(len(one))\n# X.shape[0] tra ve so hang cua ma tran X\n\n# ma tran dung de tinh toan\nXbar = np.concatenate((one, X), axis = 1)\n# print(len(Xbar))\n\n# tinh toan\nA = np.dot(Xbar.T, Xbar)\nb = np.dot(Xbar.T, y)\nw = np.dot(np.linalg.pinv(A), b)\n# print('w = ', w)\nw_0 = w[0][0]\nw_1 = w[1][0]\nx0 = np.linspace(5, 25)\ny0 = w_0 + w_1 * x0\n# print('x0 =', x0)\nprint(type(x0))\n# print(y0)\n\n# ve do thi\nplt.plot(X.T, y.T, 'ro')\nplt.plot(x0, y0)\nplt.axis([4, 25, -5, 25])\nplt.xlabel(\"abc\")\nplt.ylabel(\"xyz\")\n# plt.show()","sub_path":"exercise-of-machine-learning-notebooks/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"440923142","text":"# coding:utf-8\n\nimport controller.home\nimport controller.admin\nfrom tornado.web import url\n# 路由映射\n\nurl_mapping = [\n\n # test\n # url(r\"/test/base\", controller.test_handler.TestHandler),\n\n # user\n url(r\"/\", controller.home.HomeHandler, name=\"index\"),\n #login\n url(r\"/auth/login\", controller.home.LoginHandler, name=\"login\"),\n # logout\n url(r\"/auth/logout\", controller.home.LogoutHandler, name=\"logout\"),\n # articleType\n url(r\"/type/([0-9]+)/articles\", controller.home.HomeHandler, name=\"articleType\"),\n # sources\n url(r\"/source/([0-9]+)/articles\", controller.home.HomeHandler, name=\"source\"),\n # admin\n url(r\"/admin/submitArticles\", controller.home.HomeHandler, name=\"admin.submitArticles\"),\n url(r\"/admin/account\", controller.admin.AdminAccountHandler, name=\"admin.account\"),\n url(r\"/admin/changePassword\", controller.admin.AdminAccountHandler, name=\"admin.change_password\"),\n url(r\"/admin/editUserInfo\", controller.admin.AdminAccountHandler, name=\"admin.edit_user_info\"),\n url(r\"/admin/manageArticles\", controller.admin.AdminAccountHandler, name=\"admin.manage_articles\"),\n # admin.article_type\n url(r\"/admin/articleType\", controller.admin.AdminArticleTypeHandler, name=\"admin.articleTypes\"),\n url(r\"/admin/articleType/(add)\",\n controller.admin.AdminArticleTypeHandler, name=\"admin.articleType.action\"),\n url(r\"/admin/articleType/([0-9]+)/(sort-down|sort-up|delete|edit)\",\n controller.admin.AdminArticleTypeHandler, name=\"admin.articleType.update\"),\n # admin.menu\n url(r\"/admin/articleType/nav\",\n controller.admin.AdminArticleTypeNavHandler, name=\"admin.articleTypeNavs\"),\n url(r\"/admin/articleType/nav/(add)\",\n controller.admin.AdminArticleTypeNavHandler, name=\"admin.articleTypeNav.action\"),\n url(r\"/admin/articleType/nav/([0-9]+)/(sort-down|sort-up|delete|edit)\",\n controller.admin.AdminArticleTypeNavHandler, name=\"admin.articleTypeNav.update\"),\n # admin comments\n url(r\"/admin/manageComments\", controller.admin.AdminAccountHandler, name=\"admin.manage_comments\"),\n # CustomBlogInfo\n url(r\"/admin/customBlogInfo\", controller.admin.AdminCustomBlogInfoHandler, name=\"admin.custom_blog_info\"),\n # EditBlogInfo\n url(r\"/admin/editBlogInfo\", controller.admin.AdminCustomBlogInfoHandler, name=\"admin.edit_blog_info\"),\n url(r\"/admin/customBlogPlugin\", controller.admin.AdminAccountHandler, name=\"admin.custom_blog_plugin\"),\n # Plugin\n url(r\"/admin/custom/plugin\", controller.admin.AdminCustomPluginHandler, name=\"admin.custom.plugin\"),\n url(r\"/admin/custom/plugin/(add)\", controller.admin.AdminCustomPluginHandler, name=\"admin.custom.plugin.action\"),\n url(r\"/admin/custom/plugin/([0-9]+)/(sort-down|sort-up|disable|enable|edit|delete)\",\n controller.admin.AdminCustomPluginHandler, name=\"admin.custom.plugin.update\"),\n # Help\n url(r\"/admin/help\", controller.admin.AdminHelpHandler, name=\"admin.help\"),\n]","sub_path":"url_mapping.py","file_name":"url_mapping.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"233084475","text":"def nob(a,b):\n valor1=0\n valor2=0\n for i in range(len(a)):\n valor1+=int(a[i])\n for j in range(len(b)):\n valor2+=int(b[j])\n resposta = valor1 + valor2\n return resposta\ndef main():\n print('Digite valores de 1 a 99')\n a = input('Valor 1\\n')\n b = input('Valor 2\\n')\n print(nob(a,b))\nmain()","sub_path":"Q4_Corrigida.py","file_name":"Q4_Corrigida.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467914543","text":"import numpy as np\nimport agama\nimport utilities as ut\n\nimport matplotlib.pyplot as plt\nimport h5py as h5\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nimport matplotlib as mpl\nfrom matplotlib import rc\nrc('font', **{'family': 'serif', 'serif': ['Computer Modern']})\nrc('text', usetex=True)\nmpl.rcParams['text.latex.preamble'] = [r'\\usepackage{amsmath}']\n\ntextwidth = 7.10000594991\ncolumnwidth = 3.35224200913\n\ntb_c = ['#4e79a7', '#f28e2b', '#e15759', '#76b7b2', '#59a14f',\n '#edc948', '#b07aa1', '#ff9da7', '#9c755f', '#bab0ac']\n\nRcut = 0.2\nxrng = [0.7, 1.15]\nyrng = [0.0, 0.005]\nres = [128, 128]\n\noff1 = np.array([0, 0, 100./1000.0, 0, 0, 0])\n# off2 = np.array([0, 0, 100./1000.0, 0, 0, 0])\n\nvmin=10\nvmax=50\n\nvmin_diff = -1\nvmax_diff = 1\n\nagama.setUnits(mass=1, length=1, velocity=1)\nG = 4.30092e-06\n\nbulge = agama.Potential(type='Dehnen', gamma=1, mass=5E9, scaleRadius=1.0)\nnucleus = agama.Potential(type='Dehnen', gamma=1, mass=1.71E09, scaleRadius=0.07)\ndisk = agama.Potential(type='MiyamotoNagai', mass=6.80e+10, scaleRadius=3.0, scaleHeight=0.28)\nhalo = agama.Potential(type='NFW', mass=5.4E11, scaleRadius=15.62)\nmwpot = agama.Potential(bulge, nucleus, disk, halo)\n\nR0 = 8.135\nz0 = 20.3/1000.\nv0 = np.sqrt(-R0*mwpot.force([R0, 0, 0])[0])\nJ0 = R0*v0\n\nRd = 2.4\nq = 0.45\nSigma0_thin_Binney = 36.42\nSigma0_thick_Binney = 4.05\n\nSigma0_thin = np.exp(R0/Rd)*Sigma0_thin_Binney\nSigma0_thick = np.exp(R0/Rd)*Sigma0_thick_Binney\n# Sigma0_thin = Sigma0_thin_Binney\n# Sigma0_thick = Sigma0_thick_Binney\n\ncoefJr = 1\ncoefJz = 1\n\nhdisk_thin = 0.36\nhdisk_thick = 1.0\n\nRsigmar = Rd/q\n\nsigmar0_thin_binney = 27.\nsigmar0_thick_binney = 48.\n\nsigmar0_thin = sigmar0_thin_binney * np.exp(R0/Rsigmar)\nsigmar0_thick = sigmar0_thick_binney * np.exp(R0/Rsigmar)\n\nsigmamin_thin = 0.05*sigmar0_thin\nsigmamin_thick = 0.05*sigmar0_thick\nJmin = 0.05*J0\n\ndf_thin = agama.DistributionFunction(type='QuasiIsothermal', potential=mwpot, coefJr=coefJr, coefJz=coefJz, \n Sigma0=Sigma0_thin, Rdisk=Rd, Hdisk=hdisk_thin, sigmar0=sigmar0_thin, \n Rsigmar=Rsigmar, sigmamin=sigmamin_thin, Jmin=Jmin)\n\ndf_thick = agama.DistributionFunction(type='QuasiIsothermal', potential=mwpot, coefJr=coefJr, coefJz=coefJz, \n Sigma0=Sigma0_thick, Rdisk=Rd, Hdisk=hdisk_thick, sigmar0=sigmar0_thick, \n Rsigmar=Rsigmar, sigmamin=sigmamin_thick, Jmin=Jmin)\n\ndf = agama.DistributionFunction(df_thin, df_thick)\n# df = df_thin\ngm = agama.GalaxyModel(mwpot, df)\n\ntry:\n f = h5.File('posvel_mass.h5', 'r')\n posvel = np.array(f['posvel'])\n mass = np.array(f['mass'])\n f.close()\nexcept:\n posvel, mass = gm.sample(int(4E7))\n f = h5.File('posvel_mass.h5', 'w')\n f.create_dataset('posvel', data=posvel)\n f.create_dataset('mass', data=mass)\n f.close()\n\nRstar = np.linalg.norm(posvel[:,:2], axis=1)\nzstar = posvel[:,2]\n\nRdiff = np.subtract(Rstar, R0)\nzdiff = np.subtract(zstar, z0)\ndiff = np.sqrt(np.add(np.square(Rdiff), np.square(zdiff))) \n\nkeys = np.where(diff < Rcut)[0]\nprint(keys[:10])\nzoff = np.random.uniform(0, 100, len(keys))/1000.0\n\noff2 = np.array([[0, 0, z, 0, 0, 0] for z in zoff])\n\nposvel, mass = posvel[keys], mass[keys]\n\nposvel_off1 = np.subtract(posvel, off1)\nposvel_off2 = np.subtract(posvel, off2)\n\nactions = gm.af(posvel)\nactions[:,[1, 2]] = actions[:,[2, 1]] # transpose Jphi and Jz\n\nactions_off1 = gm.af(posvel_off1)\nactions_off1[:,[1, 2]] = actions_off1[:,[2, 1]] # transpose Jphi and Jz\n\nactions_off2 = gm.af(posvel_off2)\nactions_off2[:,[1, 2]] = actions_off2[:,[2, 1]] # transpose Jphi and Jz\n\nfig, (ax, ax_off1, ax_off2) = plt.subplots(1, 3, sharey=True, figsize=(10,4))\nrng = [xrng, yrng]\n\nheatmap, xedges, yedges = np.histogram2d(actions[:,1]/J0, actions[:,2]/J0, bins=res, range=rng)\nheatmap.T[heatmap.T == 0] = np.nan\nextent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\nim = ax.imshow(heatmap.T, extent=extent, origin='lower', norm=mpl.colors.LogNorm(), vmin=vmin, vmax=vmax, aspect=1.5*(xrng[1]-xrng[0])/(yrng[1]-yrng[0]))\nax.set_title('no offset')\n\nheatmap, xedges, yedges = np.histogram2d(actions_off1[:,1]/J0, actions_off1[:,2]/J0, bins=res, range=rng)\nheatmap.T[heatmap.T == 0] = np.nan\nextent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\nim = ax_off1.imshow(heatmap.T, extent=extent, origin='lower', norm=mpl.colors.LogNorm(), vmin=vmin, vmax=vmax, aspect=1.5*(xrng[1]-xrng[0])/(yrng[1]-yrng[0]))\nax_off1.set_title(r'$z_{\\text{offset}} = 100\\,\\text{pc}$')\n\nheatmap, xedges, yedges = np.histogram2d(actions_off2[:,1]/J0, actions_off2[:,2]/J0, bins=res, range=rng)\nheatmap.T[heatmap.T == 0] = np.nan\nextent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\nim = ax_off2.imshow(heatmap.T, extent=extent, origin='lower', norm=mpl.colors.LogNorm(), vmin=vmin, vmax=vmax, aspect=1.5*(xrng[1]-xrng[0])/(yrng[1]-yrng[0]))\nfig.colorbar(im, label='number')\nax_off2.set_title(r'$z_{\\text{offset}} = \\mathcal{N}(0, (100\\,\\text{pc})^2)$')\n\nax.set_xlabel(r'$J_{\\phi} / J_0$')\nax_off1.set_xlabel(r'$J_{\\phi} / J_0$')\nax_off2.set_xlabel(r'$J_{\\phi} / J_0$')\nax.set_ylabel(r'$J_z / J_0$')\n\nax.set_xlim(xrng)\nax_off1.set_xlim(xrng)\nax_off2.set_xlim(xrng)\nax.set_ylim(yrng)\n\nfig.tight_layout()\nfig.savefig('action_df.pdf')\n\n\n\n# now plot the difference between the two\n\nfig, (ax_off1, ax_off2) = plt.subplots(1, 2, sharey=True, figsize=(6,4))\n# fig.set_size_inches(10, 4)\n\nheatmap, xedges, yedges = np.histogram2d(actions[:,1]/J0, actions[:,2]/J0, bins=res, range=rng)\nheatmap_off1, xedges, yedges = np.histogram2d(actions_off1[:,1]/J0, actions_off1[:,2]/J0, bins=res, range=rng)\nheatmap_off2, xedges, yedges = np.histogram2d(actions_off2[:,1]/J0, actions_off2[:,2]/J0, bins=res, range=rng)\n\nheatmap_diff1 = (heatmap_off1 - heatmap)/heatmap\nheatmap_diff2 = (heatmap_off2 - heatmap)/heatmap\n\nheatmap_diff1.T[heatmap_diff1.T == 0] = np.nan\nextent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\nim = ax_off1.imshow(heatmap_diff1.T, extent=extent, origin='lower', cmap='seismic', vmin=vmin_diff, vmax=vmax_diff, aspect=1.5*(xrng[1]-xrng[0])/(yrng[1]-yrng[0]))\nax_off1.set_title(r'$z_{\\text{offset}} = 100\\,\\text{pc}$')\n\nheatmap_diff2.T[heatmap_diff2.T == 0] = np.nan\nextent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\nim = ax_off2.imshow(heatmap_diff2.T, extent=extent, origin='lower', cmap='seismic', vmin=vmin_diff, vmax=vmax_diff, aspect=1.5*(xrng[1]-xrng[0])/(yrng[1]-yrng[0]))\n# fig.colorbar(im, label='number')\nax_off2.set_title(r'$z_{\\text{offset}} = \\mathcal{N}(0, (100\\,\\text{pc})^2)$')\n\n# fig.colorbar(im, fraction=0.06, pad=0.15)\n# fig.colorbar(im, shrink=.5, pad=.2, aspect=10)\nfig.colorbar(im, label='fractional difference')\n\nax.set_xlabel(r'$J_{\\phi} / J_0$')\nax_off1.set_xlabel(r'$J_{\\phi} / J_0$')\nax_off2.set_xlabel(r'$J_{\\phi} / J_0$')\nax.set_ylabel(r'$J_z / J_0$')\n\nax.set_xlim(xrng)\nax_off1.set_xlim(xrng)\nax_off2.set_xlim(xrng)\nax.set_ylim(yrng)\n\nfig.tight_layout()\nfig.savefig('action_df_diff.pdf')\n\n# fig, ax = plt.subplots(1,1)\n# cylpos = ut.coordinate.get_positions_in_coordinate_system(posvel[:,:3])\n# cylvel = ut.coordinate.get_velocities_in_coordinate_system(posvel[:,3:], posvel[:,:3])\n\n# ax.scatter(cylvel[:,0], cylvel[:,2], s=0.1)\n\n# ax.set_xlabel('vR [km/s]')\n# ax.set_ylabel('vphi [km/s]')\n\n# fig.tight_layout()\n# fig.savefig('vR_vphi.png')\n\n","sub_path":"df/plot_df.py","file_name":"plot_df.py","file_ext":"py","file_size_in_byte":7330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"454982255","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nScript to handle skype notifications\n\"\"\"\n\n\nimport argparse \nimport pynotify\nimport logging\n\nignored = [\"SkypeLoginFailed\",\n \"CallConnecting\",\n \"CallRingingIn\",\n \"CallRingingOut\",\n \"CallAnswered\",\n \"CallBusy\",\n \"CallFailed\",\n \"CallMissed\",\n \"ContactAuthRequest\",\n \"ChatOutgoing\",\n \"Birthday\"]\n \ndef notify(summary,body=\"\", icon=\"skype-chat\"):\n pynotify.init(\"Skype Notification\")\n notification = pynotify.Notification(summary, body, icon)\n notification.set_timeout(10)\n notification.show()\n notification.close()\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-m', dest=\"message\")\nparser.add_argument(\"-a\", dest=\"action\")\nparser.add_argument(\"-u\", dest=\"user\")\noptions = parser.parse_args()\n\nimport sys\ntest = open('/home/joaosantos/util/skype_log', 'a+')\ntest.write(str(sys.argv))\ntest.write('\\n')\n\nif options.action not in ignored:\n if options.action == \"SkypeLogin\":\n notify(options.user, \"Logged in to Skype\")\n elif options.action == \"SkypeLogout\":\n notify(options.user, \"Logged out of Skype\")\n elif options.action in [\"ChatIncoming\", \"ChatIncomingInitial\"]:\n watch = ['turtle', 'joao', 'joão', 'example']\n show = any(word in options.message.lower() for word in watch)\n if show:\n notify(options.user, options.message)\n elif options.action == \"ContactOnline\":\n pass\n #notify(\"{0} has appeared online\".format(options.user))\n elif options.action == \"ContactOffline\":\n pass\n #notify(\"{0} has gone offline\".format(options.user))\n else:\n message = options.action + \" \" + options.message\n notify(options.user, message)\n","sub_path":"skypenot.py","file_name":"skypenot.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"548490729","text":"\"\"\"\r\nScan a magnet, take data on three machines, analyse it, plot results\r\n\"\"\"\r\nfrom __future__ import print_function\r\n\r\n# deal with Limits on Blocks. Does cset(block, value=too_large) raise an exception?\r\n\r\n# return to default/original at end of scan\r\n# auxiliary tables named xx_Reference with cols \"name\" \"value\"\r\n# columns for all magnets\r\n# \"last setpoint\" table named \"SE_Block_Cache\", same format\r\nCACHENAME=\"SE_Block_Cache\"\r\n\r\n# select test mode\r\n# DAQ=True (simulated), \"abort\" (real DAE but don't save) or False (real working system)\r\nTESTMODE_DAQ=False\r\nTESTMODE_BLOCKS=False\r\n\r\n# script top level (maybe not Algorithm unless Workflow is debugged)\r\n# stage 0 get input\r\n# multi section scan pars permitted, as Rebin() - x1 dx12 x2 dx23 x3\r\n\r\n# stage 1 run ScanAndMeasureMagnet\r\n# output an intermediate table? has headings \"scanvar\" \"inst1\" \"inst2\" and rows \r\n# can edit this table to insert old data and go on to run AnalyseTuningScan\r\n\r\n# stage 2 run AnalyseTuningScan\r\n\r\n# table \"comment\" fields gives starting currents/slits and scan variable?\r\n\r\n# if old table given:\r\n# calculate extra points so that no gap exceeds specified step. Generally have equal sized gaps in between old points. Don't repeat old points.\r\n# re-run all analysis (old and new points).\r\n\r\n# table column names\r\n# left column type x, named for Magnet (or other tunable)\r\n# for instruments, always prefix with inst name, then...\r\n# Run Rate RateErr Asym AsymErr Alpha AlphaErr Prompt PromptErr DoubleP DoublePErr\r\n# for cameras, suffixes\r\n# File Xpos XposErr Ypos YposErr Width WidthErr Height HeightErr Ellip EllipErr Intens IntensErr Backgd BackgdErr\r\n\r\n# auxiliary table for scan conditions, named _Conditions\r\n# three columns\r\n# col 1 for scanned name, magnet and slit names, instrument and camera names (run number ranges)\r\n# col 2 for starting value\r\n# col 3 for end value (same if that magnet not scanned)\r\n\r\nfrom mantid.api import * # PythonAlgorithm, registerAlgorithm, WorkspaceProperty\r\nfrom mantid.kernel import *\r\nfrom mantid.simpleapi import *\r\nfrom logger import Logger\r\n#import inspect\r\n#from genie_python.genie_startup import *\r\nimport os\r\nimport re\r\nimport time\r\nimport numpy\r\nimport math\r\n\r\n####################################\r\n# SETUP PARAMETERS\r\n####################################\r\n\r\n# camera control subroutine(s)\r\n# params are fileformat, lastRunNum, flag -1=initialise 0=just started data taking, 1=about to end\r\n# return tuple (run num,flag) for this time, valid on 2nd call. flag=True if good data taken\r\ndef getRecentFile(fmt,lastRunNum,flag):\r\n\t# continuous dumping of files, use latest one\r\n\tif(flag==-1):\r\n\t\tdir=os.path.dirname(fmt)\r\n\t\tmatcher=re.compile(\"^\"+os.path.basename(fmt).replace(\"%d\",\"([0-9]+)\")+\"$\",re.IGNORECASE)\r\n\t\tnum=0\r\n\t\tallFiles=os.listdir(dir)\r\n\t\tfor f in allFiles:\r\n\t\t\tm=matcher.match(f)\r\n\t\t\tif(m):\r\n\t\t\t\tnum=max(num,int(m.group(1)))\r\n\t\treturn (num,False) # highest numbered matching file\r\n\telse:\r\n\t\tN=lastRunNum\r\n\t\twhile (os.access(fmt % (N+1), os.F_OK)):\r\n\t\t\tN=N+1\r\n\t\tif(flag==1):\r\n\t\t\tif(N-lastRunNum>=2):\r\n\t\t\t\treturn (N,True)\r\n\t\t\telse:\r\n\t\t\t\treturn (N,False)\r\n\t\telse:\r\n\t\t\treturn (N,False)\r\n\r\ndef processHifiCam(filename):\r\n\timg=LoadBeamCameraFile(SourceFile=filename, FilterNoiseLevel='50', BinSize='1', OutputWorkspace='IMG',EnableLogging=False)\r\n\t#img=LoadFITS(Filename=filename, LoadAsRectImg=True, FilterNoiseLevel='50', BinSize='1', Scale='80', OutputWorkspace='IMG')\r\n\tsquash=MaskAndFlattenCameraImage(img,120,590,80,440,EnableLogging=False)\r\n\t\r\n\tfplist=Fit(Function=\"name=TwoDimGaussianPlusBG,Intensity=40000\",\r\n\t\tInputWorkspace='squash',\r\n\t\tOutput='squash',\r\n\t\tOutputCompositeMembers=True,\r\n\t\tStartX=0,\r\n\t\tEndX=100000000,\r\n\t\tEnableLogging=False)\r\n\t\r\n\t#print fplist\r\n\t(YesNo, CostFn, CovarMat, Params,Workspace)=fplist\t\r\n\t(X0,Y0,XSig,YSig,Skew,Background,Intens,CostF2)=Params.column(1)\r\n\t(eX0,eY0,eXSig,eYSig,eSkew,eBackground,eIntens,eCostF2)=Params.column(2)\r\n\treturn (X0,eX0,Y0,eY0,XSig,eXSig,YSig,eYSig,Skew,eSkew,Intens,eIntens,Background,eBackground)\r\n\t\r\nWAITFOR_TIMEOUT_SECONDS = 60\r\nMAGNETS=[\"UQ1\",\"UQ2\",\"UQ3\",\"UQ4\",\"UQ5\",\"UQ6\",\"UQ7\",\"UQ8\",\"UQ9\",\"UQ10\",\"UQ11\",\"UQ12\",\"UB1\",\"UB2\",\"SEPARATOR\",\"SEPTUM_A\",\"SEPTUM_C\",\"UQ13A\",\"UQ14A\",\"UQ15A\",\"UQ13B\",\"UQ14B\",\"UQ13C\",\"UQ14C\",\"UQ15C\"] # example\r\nMAGNETSETS=[\"H123\",\"V123\",\"M123\",\"H456\",\"V456\",\"M456\",\"H789\",\"V789\",\"M789\",\"H101112\",\"V101112\",\"M101112\",\"H131415A\",\"V131415A\",\"M131415A\",\"H1314B\",\"V1314B\",\"H131415C\",\"V131415C\",\"M131415C\",\"Momentum\"]\r\nOTHERS=[] # [\"Mslits\"] not yet connected this way\r\n\r\nBLOCKNAMES={\"UQ1\":\"UQ1_CURR\",\"UQ2\":\"UQ2_CURR\",\"UQ3\":\"UQ3_CURR\",\r\n\t\"UQ4\":\"UQ4_CURR\",\"UQ5\":\"UQ5_CURR\",\"UQ6\":\"UQ6_CURR\",\"UQ7\":\"UQ7_CURR\",\r\n\t\"UQ8\":\"UQ8_CURR\",\"UQ9\":\"UQ9_CURR\",\"UQ10\":\"UQ10_CURR\",\"UQ11\":\"UQ11_CURR\",\r\n\t\"UQ12\":\"UQ12_CURR\",\"UB1\":\"UB1_CURR\",\"UB2\":\"UB2_CURR\",\"SEPARATOR\":\"SEPARATOR_CURR\",\r\n\t\"SEPTUM_A\":\"SEPTUM_A_CURR\",\"SEPTUM_C\":\"SEPTUM_C_CURR\",\"UQ13A\":\"UQ13A_CURR\",\r\n\t\"UQ14A\":\"UQ14A_CURR\",\"UQ15A\":\"UQ15A_CURR\",\"UQ13B\":\"UQ13B_CURR\",\r\n\t\"UQ14B\":\"UQ14B_CURR\",\"UQ13C\":\"UQ13C_CURR\",\"UQ14C\":\"UQ14C_CURR\",\"UQ15C\":\"UQ15C_CURR\"}\r\n\r\n# *********** override for tests\r\n#MAGNETS=[\"SEPTUM_A_CURR\",\"SEPTUM_C_CURR\"]\r\n#OTHERS=[]\r\n\r\n# full list for convenience\r\nTUNABLES=MAGNETS+MAGNETSETS+OTHERS\r\n\r\nDPARS={} # how to analyse data\r\nDPARS[\"MUSR\"]={\"machine\":\"NDXMUSR\",\"data\":\"//musr/data/musr%08d.nxs\",\"tgbegin\":0.5,\"tgend\":10.0,\"p1begin\":-0.23,\"p1end\":-0.1,\"promptbegin\":-0.4,\"promptend\":-0.3,\"pulse\":2}\r\nDPARS[\"EMU\"]={\"machine\":\"NDXEMU\",\"data\":\"//emu/data/emu%08d.nxs\",\"tgbegin\":0.5,\"tgend\":10.0,\"p1begin\":0.1,\"p1end\":0.23,\"promptbegin\":-0.2,\"promptend\":0.0,\"pulse\":1}\r\nDPARS[\"HIFI\"]={\"machine\":\"NDXHIFI\",\"data\":\"//hifi/data/hifi%08d.nxs\",\"tgbegin\":0.5,\"tgend\":10.0,\"p1begin\":0.1,\"p1end\":0.23,\"promptbegin\":-0.2,\"promptend\":0.0,\"pulse\":1}\r\nMACHINES0 = list(DPARS.keys())\r\n\r\nCPARS={} # how to get camera data\r\nCPARS[\"HIFI\"]={\"data\":\"//ndlt626/Users/Public/Documents/sxvh9usb/Test for Sept2016/IMG%d.fit\",\"finder\":getRecentFile,\"processor\":processHifiCam}\r\n#CPARS[\"MUSR\"]={finder=TakeMusrPic,processor=processMusrCam} # filenames specified by user\r\nCAMERAS0=list(CPARS.keys())\r\n\r\n\r\nif(TESTMODE_DAQ is True):\r\n\tDPARS[\"MUSR\"][\"data\"]=\"//musr/data/musr%08d.nxs\"\r\n\tDPARS[\"EMU\"][\"data\"]=\"//emu/data/Cycle 14_3/emu%08d.nxs\"\r\n\tDPARS[\"HIFI\"][\"data\"]=\"//hifi/data/cycle_14_3/hifi%08d.nxs\"\r\n\tclass MultipleDaeController:\r\n\t\tdef __init__(self):\r\n\t\t\tself.startrunnums={\"NDXMUSR\":51909,\"NDXEMU\":50690,\"NDXHIFI\":77061} # B1B2 tune starting 20 Mar 2015 13:52 approx\r\n\t\t\tself.runnums={}\r\n\t\t\tself.states={}\r\n\t\t\tself.frames={}\r\n\t\tdef add_machine(self,mac,timeout):\r\n\t\t\tself.states[mac]=\"SETUP\"\r\n\t\t\tself.frames[mac]=0\r\n\t\t\tself.runnums[mac]=self.startrunnums[mac]\r\n\t\t\tprint(\"registered \"+str(mac))\r\n\t\tdef run_on_all(self,code,**kwds):\r\n\t\t\tif(code==\"get_run_state\"):\r\n\t\t\t\treturn self.states\r\n\t\t\tif(code==\"begin\"):\r\n\t\t\t\tprint(\"doing BEGIN, \"+str(kwds))\r\n\t\t\t\tfor m in list(self.states.keys()):\r\n\t\t\t\t\tself.states[m]=\"RUNNING\"\r\n\t\t\t\t\tself.frames[m]=0\r\n\t\t\t\tif(\"waitfor_frames\" in kwds):\r\n\t\t\t\t\tprint(\"waiting for frames=\"+str(kwds[\"waitfor_frames\"]))\r\n\t\t\t\t\ttime.sleep(1)\r\n\t\t\t\t\tfor m in list(self.states.keys()):\r\n\t\t\t\t\t\tself.frames[m]=kwds[\"waitfor_frames\"]+1\r\n\t\t\tif(code==\"get_run_number\"):\r\n\t\t\t\treturn self.runnums\r\n\t\t\tif(code==\"end\"):\r\n\t\t\t\tprint(\"ending runs\")\r\n\t\t\t\tfor m in list(self.states.keys()):\r\n\t\t\t\t\tself.states[m]=\"SETUP\"\r\n\t\t\t\t\tself.runnums[m]+=1\r\n\t\t\tif(code==\"abort\"):\r\n\t\t\t\tprint(\"aborting runs\")\r\n\t\t\t\tfor m in list(self.states.keys()):\r\n\t\t\t\t\tself.states[m]=\"SETUP\"\r\nelse:\r\n\tfrom multiple_dae_controller import MultipleDaeController\r\n\timport inspect\r\n\r\nif(TESTMODE_BLOCKS):\r\n\tblockvals={}\r\n\tfor b in MAGNETS+OTHERS:\r\n\t\tblockvals[BLOCKNAMES[b]]=50.0\r\n\tdef cset(block=None,value=None,wait=False,lowlimit=-99999.9,highlimit=99999.9,**args):\r\n\t\tif(len(args)==1):\r\n\t\t\tblock=list(args.keys())[0]\r\n\t\t\tvalue=list(args.values())[0]\r\n\t\tprint(\"setting \"+str(block)+\" to \"+str(value))\r\n\t\tblockvals[block]=value\r\n\t\tif(wait):\r\n\t\t\tprint(\"waiting for value to stabilise\")\r\n\t\t\ttime.sleep(1)\r\n\tdef cshow(block):\r\n\t\tprint(\"CSHOW: \"+str(blockvals[block]))\r\n\t\treturn None\r\n\tdef cget(block):\r\n\t\tif block in blockvals:\r\n\t\t\treturn {\"name\":\"TEST:\"+block,\"value\":blockvals[block],\"lowlimit\":0.0,\"highlimit\":1.0}\r\n\t\telse:\r\n\t\t\treturn None\r\n\tdef waitfor_block(block,lowlimit=-99999.9,highlimit=99999.9):\r\n\t\tprint(\"waiting for \"+block+\" to stabilise\")\r\n\t\ttime.sleep(1)\r\nelse:\r\n\tfrom genie_python.genie_startup import *\r\n\tset_instrument(\"IN:MUONFE:\")\r\n\t\r\ndef cached_cset(block,val,wait=False,lowlimit=-99999.9,highlimit=99999.9):\r\n\t# translate magnet name to block name\r\n\t# set the block\r\n\t# also update the cache\r\n\tca=mtd[CACHENAME]\r\n\tnames=ca.column(0)\r\n\targs={BLOCKNAMES[block]:val} # ,\"wait\":wait\r\n\tcset(**args)\r\n\tif block in names:\r\n\t\tca.setCell(names.index(block),1,val) # only on successful cset\r\n\t\r\ndef cached_get_block(block):\r\n\t# translate magnet name to block name\r\n\t# get block val from cache\r\n\t# get actual value\r\n\t# get value from table tt (_Reference) if supplied\r\n\t# return cached value if all close\r\n\t# or raise exception\r\n\tprint(\"doing cget(\"+block+\")\")\r\n\trbk=cget(BLOCKNAMES[block])[\"value\"]\r\n\tca=mtd[CACHENAME]\r\n\tcnames=ca.column(0)\r\n\tif(block in cnames):\r\n\t\tcval=ca.column(1)[cnames.index(block)]\r\n\t\tif(abs(rbk-cval)>1.0):\r\n\t\t\traise Exception(\"Readback of \"+block+\"(\"+str(rbk)+\") is not close to cached setpoint(\"+str(cval)+\")\")\r\n\t\treturn cval\r\n\telse:\r\n\t\treturn rbk # uncached\r\n\r\ndef raw_cget(block):\r\n\t# translate magnet name to block name\r\n\treturn cget(BLOCKNAMES[block])[\"value\"]\r\n\r\n\r\ndef setTune(startPars,magName,tuneVal):\r\n\ttoSet={}\r\n\tif( (magName in MAGNETS) or (magName in OTHERS) ): # direct setting\r\n\t\ttoSet[magName]=tuneVal\r\n\telif(magName==\"H123\"): # delta amps (largest change) for all triplet options\r\n\t\ttoSet[\"UQ1\"]=startPars[\"UQ1\"]+tuneVal*0.25\r\n\t\ttoSet[\"UQ2\"]=startPars[\"UQ2\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ3\"]=startPars[\"UQ3\"]+tuneVal*0.25\r\n\telif(magName==\"V123\"):\r\n\t\ttoSet[\"UQ1\"]=startPars[\"UQ1\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ2\"]=startPars[\"UQ2\"]+tuneVal*0.4\r\n\t\ttoSet[\"UQ3\"]=startPars[\"UQ3\"]+tuneVal*0.6\r\n\telif(magName==\"M123\"):\r\n\t\ttoSet[\"UQ1\"]=startPars[\"UQ1\"]+tuneVal*0.5\r\n\t\ttoSet[\"UQ2\"]=startPars[\"UQ2\"]+tuneVal*-0.5\r\n\t\ttoSet[\"UQ3\"]=startPars[\"UQ3\"]+tuneVal*-1.0\r\n\telif(magName==\"H456\"):\r\n\t\ttoSet[\"UQ4\"]=startPars[\"UQ4\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ5\"]=startPars[\"UQ5\"]+tuneVal*0.67\r\n\t\ttoSet[\"UQ6\"]=startPars[\"UQ6\"]+tuneVal*1.0\r\n\telif(magName==\"V456\"):\r\n\t\ttoSet[\"UQ4\"]=startPars[\"UQ4\"]+tuneVal*0.25\r\n\t\ttoSet[\"UQ5\"]=startPars[\"UQ5\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ6\"]=startPars[\"UQ6\"]+tuneVal*0.25\r\n\telif(magName==\"M456\"):\r\n\t\ttoSet[\"UQ4\"]=startPars[\"UQ4\"]+tuneVal*-1.0\r\n\t\ttoSet[\"UQ6\"]=startPars[\"UQ6\"]+tuneVal*1.0\r\n\telif(magName==\"H789\"):\r\n\t\ttoSet[\"UQ7\"]=startPars[\"UQ7\"]+tuneVal*0.25\r\n\t\ttoSet[\"UQ8\"]=startPars[\"UQ8\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ9\"]=startPars[\"UQ9\"]+tuneVal*0.25\r\n\telif(magName==\"V789\"):\r\n\t\ttoSet[\"UQ7\"]=startPars[\"UQ7\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ8\"]=startPars[\"UQ8\"]+tuneVal*0.67\r\n\t\ttoSet[\"UQ9\"]=startPars[\"UQ9\"]+tuneVal*1.0\r\n\telif(magName==\"M789\"):\r\n\t\ttoSet[\"UQ7\"]=startPars[\"UQ7\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ9\"]=startPars[\"UQ9\"]+tuneVal*-1.0\r\n\telif(magName==\"H101112\"):\r\n\t\ttoSet[\"UQ10\"]=startPars[\"UQ10\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ11\"]=startPars[\"UQ11\"]+tuneVal*0.67\r\n\t\ttoSet[\"UQ12\"]=startPars[\"UQ12\"]+tuneVal*1.0\r\n\telif(magName==\"V101112\"):\r\n\t\ttoSet[\"UQ10\"]=startPars[\"UQ10\"]+tuneVal*0.25\r\n\t\ttoSet[\"UQ11\"]=startPars[\"UQ11\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ12\"]=startPars[\"UQ12\"]+tuneVal*0.25\r\n\telif(magName==\"M101112\"):\r\n\t\ttoSet[\"UQ10\"]=startPars[\"UQ10\"]+tuneVal*-1.0\r\n\t\ttoSet[\"UQ12\"]=startPars[\"UQ12\"]+tuneVal*1.0\r\n\telif(magName==\"H131415A\"):\r\n\t\ttoSet[\"UQ13A\"]=startPars[\"UQ13A\"]+tuneVal*0.2\r\n\t\ttoSet[\"UQ14A\"]=startPars[\"UQ14A\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ15A\"]=startPars[\"UQ15A\"]+tuneVal*0.4\r\n\telif(magName==\"V131415A\"):\r\n\t\ttoSet[\"UQ13A\"]=startPars[\"UQ13A\"]+tuneVal*0.6\r\n\t\ttoSet[\"UQ14A\"]=startPars[\"UQ14A\"]+tuneVal*0.4\r\n\t\ttoSet[\"UQ15A\"]=startPars[\"UQ15A\"]+tuneVal*1.0\r\n\telif(magName==\"M131415A\"):\r\n\t\ttoSet[\"UQ13A\"]=startPars[\"UQ13A\"]+tuneVal*-1.0\r\n\t\ttoSet[\"UQ15A\"]=startPars[\"UQ15A\"]+tuneVal*1.0\r\n\telif(magName==\"H131415C\"):\r\n\t\ttoSet[\"UQ13C\"]=startPars[\"UQ13C\"]+tuneVal*0.25\r\n\t\ttoSet[\"UQ14C\"]=startPars[\"UQ14C\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ15C\"]=startPars[\"UQ15C\"]+tuneVal*0.25\r\n\telif(magName==\"V131415C\"):\r\n\t\ttoSet[\"UQ13C\"]=startPars[\"UQ13C\"]+tuneVal*0.6\r\n\t\ttoSet[\"UQ14C\"]=startPars[\"UQ14C\"]+tuneVal*0.4\r\n\t\ttoSet[\"UQ15C\"]=startPars[\"UQ15C\"]+tuneVal*1.0\r\n\telif(magName==\"M131415C\"):\r\n\t\ttoSet[\"UQ13B\"]=startPars[\"UQ13B\"]+tuneVal*-1.0\r\n\t\ttoSet[\"UQ14C\"]=startPars[\"UQ14C\"]+tuneVal*-0.5\r\n\t\ttoSet[\"UQ15C\"]=startPars[\"UQ15C\"]+tuneVal*0.5\r\n\telif(magName==\"H1314B\"):\r\n\t\ttoSet[\"UQ13B\"]=startPars[\"UQ13B\"]+tuneVal*1.0\r\n\t\ttoSet[\"UQ14B\"]=startPars[\"UQ14B\"]+tuneVal*0.33\r\n\telif(magName==\"V1314B\"):\r\n\t\ttoSet[\"UQ13B\"]=startPars[\"UQ13B\"]+tuneVal*0.16\r\n\t\ttoSet[\"UQ14B\"]=startPars[\"UQ14B\"]+tuneVal*1.0\r\n\telif(magName==\"Momentum\"): # units of \"B1\"\r\n\t\tfor mag in MAGNETS:\r\n\t\t\tif(mag==\"SEPARATOR\"):\r\n\t\t\t\ttoSet[\"SEPARATOR\"]=startPars[\"SEPARATOR\"]*startPars[\"UB1\"]/tuneVal\r\n\t\t\telse:\r\n\t\t\t\ttoSet[mag]=startPars[mag]/startPars[\"UB1\"]*tuneVal\r\n\treturn toSet\r\n\r\nclass Beamline_cset(PythonAlgorithm):\r\n\tdef PyInit(self):\r\n\t\tself.declareProperty(\"Operation\",\"\",StringListValidator([\"Set to value\",\"Refresh\",\"Refresh All\",\"Set All from Table\"]))\r\n\t\tself.declareProperty(\"Magnet\",\"\",StringListValidator(MAGNETS+OTHERS))\r\n\t\tself.declareProperty(\"Value\",0.0)\r\n\t\tself.declareProperty(ITableWorkspaceProperty(\"Table\",\"\",direction=Direction.Input,optional=PropertyMode.Optional))\r\n\t\r\n\tdef category(self):\r\n\t\treturn \"Muon\\\\Tuning\"\r\n\r\n\tdef PyExec(self):\r\n\t\tif(CACHENAME not in mtd):\r\n\t\t\t# create and initialise?\r\n\t\t\ttt2=WorkspaceFactory.createTable()\r\n\t\t\ttt2.addColumn(\"str\",\"MagnetName\",6)\r\n\t\t\ttt2.addColumn(\"double\",\"Reference\",2)\r\n\t\t\tfor mag1 in MAGNETS+OTHERS:\r\n\t\t\t\ttt2.addRow([mag1,-1.0]) # initially unknown\r\n\t\t\tAnalysisDataService.addOrReplace(CACHENAME,tt2)\r\n\t\t\tself.log().notice(\"Creating block cache\")\r\n\t\top=self.getProperty(\"Operation\").value\r\n\t\tblock=self.getProperty(\"Magnet\").value\r\n\t\tif(op==\"Set to value\"):\r\n\t\t\tval=self.getProperty(\"Value\").value\r\n\t\t\tcached_cset(block,val,wait=True)\r\n\t\telif(op==\"Refresh\"):\r\n\t\t\tval=raw_cget(block) # bypass cache, get readback\r\n\t\t\tcached_cset(block,val)\r\n\t\telif(op==\"Refresh All\"):\r\n\t\t\tfor block in MAGNETS+OTHERS:\r\n\t\t\t\tval=raw_cget(block) # bypass cache, get readback\r\n\t\t\t\tcached_cset(block,val)\r\n\t\telif(op==\"Set All from Table\"):\r\n\t\t\t# fairly free options in table. Meant for x_Reference tables, but can use Parameters table from a fit for example. Not all values need be set!\r\n\t\t\tt=self.getProperty(\"Table\").value\r\n\t\t\ttblks=t.column(0)\r\n\t\t\ttvals=t.column(1)\r\n\t\t\tfor block in tblks:\r\n\t\t\t\tif(block in (MAGNETS+OTHERS)):\r\n\t\t\t\t\tval=tvals[tblks.index(block)] # table entry\r\n\t\t\t\t\tcached_cset(block,val,wait=True)\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.log().notice(\"Ignoring table row \"+block)\r\n\t\telse:\r\n\t\t\traise Exception(\"Unknown operation\")\r\nAlgorithmFactory.subscribe(Beamline_cset)\r\n\r\nclass TuneMagnet(DataProcessorAlgorithm):\r\n\t\"\"\" workflow algorithm, scan a magnet, analyse results, plot curve \"\"\"\r\n\tdef PyInit(self):\r\n\t\t#self.declareProperty(StringArrayProperty(\"Machines\",MACHINES0))\r\n\t\tfor mac in MACHINES0:\r\n\t\t\tself.declareProperty(mac,True,doc=\"Measure data from this instrument\")\r\n\t\tfor cam in CAMERAS0:\r\n\t\t\tself.declareProperty(cam+\"cam\",True,doc=\"Measure spot on this camera\") # eg //laptop/directory/picture%d.fit\"\r\n\t\tself.declareProperty(\"Magnet\",\"\",StringListValidator(TUNABLES))\r\n\t\tself.declareProperty(FloatArrayProperty(\"ScanRange\",[0.0,1.0,10.0]),doc=\"first,step,[midpt,step2]*n,end, or blank just to re-analyse old results\")\r\n\t\tself.declareProperty(\"Frames\",5000)\r\n\t\tself.declareProperty(ITableWorkspaceProperty(\"OldResultTable\",\"\",direction=Direction.Input,optional=PropertyMode.Optional),doc=\"Already measured points to append to\") # will copy from this table and append new points\r\n\t\tself.declareProperty(ITableWorkspaceProperty(\"ResultTable\",\"\",direction=Direction.Output)) # out; will analyse all new and old runs; string only here\r\n\t\tself.declareProperty(\"DoDeadTimeCorr\",True)\r\n\t\tself.declareProperty(\"MeasureTF20asym\",False)\r\n\t\tself.declareProperty(\"MeasurePromptPeaks\",False)\r\n\t\tself.declareProperty(\"MeasureDoublePulse\",False)\r\n\t\tself.declareProperty(FileProperty(\"AutoSaveDir\",\"\",action=FileAction.OptionalDirectory),doc=\"Somewhere to save the results\")\r\n\tdef category(self):\r\n\t\treturn \"Muon\\\\Tuning\"\r\n\r\n\tdef CalcScanValues(self,ScanRange,ExistingPoints,tolerance=0.3):\r\n\t\t#self.declareProperty(FloatArrayProperty(\"ScanRange\",[0.0,1.0,10.0]),doc=\"first,step,[midpt,step2]*n,end\")\r\n\t\t#self.declareProperty(FloatArrayProperty(\"ExistingPoints\",[1.5,2.5]),doc=\"already measured, not to duplicate\")\r\n\t\t#self.declareProperty(FloatArrayProperty(\"ScanValues\",[0.0]),direction=Direction.Output,doc=\"chosen values to scan\")\r\n\t\t# fill ranges\r\n\t\t# end and break points done exactly unless duplicates\r\n\t\t# don't add new points if within tolerance*stepsize of an existing point\r\n\t\tScanR2=list(ScanRange)\r\n\t\tnewPts=[]\r\n\t\ttol2=0.001 # default for a single point\r\n\t\twhile(len(ScanR2)>2):\r\n\t\t\tExPts=sorted(ExistingPoints+newPts) # existing, and new already added points\r\n\t\t\ttol2=tolerance*ScanR2[1]\r\n\t\t\tmorePts=numpy.arange(ScanR2[0],ScanR2[2],ScanR2[1])\r\n\t\t\tfor morePt in morePts:\r\n\t\t\t\ti=numpy.searchsorted(ExPts,morePt) # i points to old point just above new one\r\n\t\t\t\tif((i==0 or abs(ExPts[i-1]-morePt)>tol2) and(i==len(ExPts) or abs(ExPts[i]-morePt)>tol2)):\r\n\t\t\t\t\tnewPts.append(morePt)\r\n\t\t\tdel ScanR2[0:2]\r\n\t\tif(len(ScanR2)==1):\r\n\t\t\tExPts=sorted(ExistingPoints+newPts) # existing, and new break points\r\n\t\t\ti=numpy.searchsorted(ExPts,ScanR2[0]) # i points to old point just above new one\r\n\t\t\tif((i==0 or abs(ExPts[i-1]-ScanR2[0])>tol2) and(i==len(ExPts) or abs(ExPts[i]-ScanR2[0])>tol2)):\r\n\t\t\t\tnewPts.append(ScanR2[0])\r\n\t\treturn newPts\r\n\r\n\tdef PyExec(self):\r\n\t\t# get old scan values\r\n\t\ttunable=self.getProperty(\"Magnet\").value\r\n\r\n\t\tif not self.getProperty(\"OldResultTable\").isDefault:\r\n\t\t\toldTab=self.getProperty(\"OldResultTable\").value\r\n\t\t\toldScanVals=oldTab.column(0)\r\n\t\t\tif(oldTab.getColumnNames()[0] != tunable):\r\n\t\t\t\traise Exception(\"The old table was scanning a different magnet, can't use it\")\r\n\t\t\t# check _References table matches current settings (allow one magnet being tuned to differ)\r\n\t\t\ttt2=mtd[self.getProperty(\"OldResultTable\").valueAsStr+\"_Reference\"]\r\n\t\t\tfor r in tt2:\r\n\t\t\t\tif(r[\"MagnetName\"] != tunable and abs(r[\"Reference\"]-cached_get_block(r[\"MagnetName\"]))>0.01):\r\n\t\t\t\t\traise Exception(\"Magnet \"+r[\"MagnetName\"]+\" is not at the value used last time\")\r\n\t\t\t\r\n\t\telse:\r\n\t\t\toldTab=None\r\n\t\t\toldScanVals=[]\r\n\t\tnewScanPars=self.getProperty(\"ScanRange\").value\r\n\t\t#print \"newScanPars=\", newScanPars\r\n\t\tnewScanPts=self.CalcScanValues(newScanPars,oldScanVals)\r\n\t\tif(len(newScanPts)==0):\r\n\t\t\tself.log().notice(\"No values to scan, or already measured\")\r\n\t\t\trunNumList=oldTab\r\n\t\t\toldTab=None\r\n\t\telse:\r\n\t\t\tMACHINES=[]\r\n\t\t\tfor mac in MACHINES0:\r\n\t\t\t\tif(self.getProperty(mac).value):\r\n\t\t\t\t\tMACHINES.append(DPARS[mac][\"machine\"])\r\n\t\t\tCAMERAS=[]\r\n\t\t\tfor cam in CAMERAS0:\r\n\t\t\t\tif(self.getProperty(cam+\"cam\").value):\r\n\t\t\t\t\tCAMERAS.append(cam)\r\n\t\t\t#runNumList=ScanMagnet(Machines=MACHINES,Cameras=CAMERAS,Magnet=Tunable,ScanValues=newScanPts,Frames=self.getProperty(\"Frames\").value,RunNumList=\"__NewRuns\")\r\n\t\t\tscmag=self.createChildAlgorithm(\"ScanMagnet\",startProgress=0.0,endProgress=0.9)\r\n\t\t\tscmag.setProperty(\"Machines\",MACHINES)\r\n\t\t\tscmag.setProperty(\"Cameras\",CAMERAS)\r\n\t\t\tscmag.setProperty(\"Magnet\",tunable)\r\n\t\t\tscmag.setProperty(\"ScanValues\",newScanPts)\r\n\t\t\tscmag.setProperty(\"Frames\",self.getProperty(\"Frames\").value)\r\n\t\t\tscmag.setPropertyValue(\"RunNumList\", \"__NewRuns\")\r\n\t\t\t#scmag.setAlwaysStoreInADS(True)\r\n\t\t\tscmag.execute()\r\n\t\t\trunNumList = scmag.getProperty(\"RunNumList\").value\r\n\t\t\tAnalysisDataService.addOrReplace(\"__NewRuns\", runNumList)\r\n\r\n\t\tats=self.createChildAlgorithm(\"AnalyseTuningScan\",startProgress=0.9,endProgress=1.0)\r\n\t\tif(oldTab):\r\n\t\t\tats.setProperty(\"OldTable\",oldTab)\r\n\t\tats.setProperty(\"NewRuns\",runNumList)\r\n\t\tats.setProperty(\"OutputTable\",self.getProperty(\"ResultTable\").valueAsStr)\r\n\t\tats.setProperty(\"DoDeadTimeCorr\",self.getProperty(\"DoDeadTimeCorr\").value)\r\n\t\tats.setProperty(\"MeasureTF20asym\",self.getProperty(\"MeasureTF20asym\").value)\r\n\t\tats.setProperty(\"MeasurePromptPeaks\",self.getProperty(\"MeasurePromptPeaks\").value)\r\n\t\tats.setProperty(\"MeasureDoublePulse\",self.getProperty(\"MeasureDoublePulse\").value)\r\n\t\t#ats.setAlwaysStoreInADS(True)\r\n\t\tats.execute()\r\n\t\toptab=ats.getProperty(\"OutputTable\").value\r\n\t\tself.setProperty(\"ResultTable\",optab)\r\n\t\t\r\n\t\tif(not self.getProperty(\"AutoSaveDir\").isDefault):\r\n\t\t\tasdir=self.getProperty(\"AutoSaveDir\").value\r\n\t\t\tAnalysisDataService.addOrReplace(self.getProperty(\"ResultTable\").valueAsStr, optab)\r\n\t\t\tSaveNexus(InputWorkspace=self.getProperty(\"ResultTable\").valueAsStr,Filename=os.path.join(asdir,self.getProperty(\"ResultTable\").valueAsStr+\".nxs\"))\r\n\t\t\tSaveNexus(InputWorkspace=self.getProperty(\"ResultTable\").valueAsStr+\"_Reference\",Filename=os.path.join(asdir,self.getProperty(\"ResultTable\").valueAsStr)+\"_Reference.nxs\")\r\n\t\t\t\r\nAlgorithmFactory.subscribe(TuneMagnet)\r\n\r\nclass ChooseBestValue(PythonAlgorithm):\r\n\t\"\"\" given scan table and best value of X, calculate and set magnet values \"\"\"\r\n\tdef PyInit(self):\r\n\t\tself.declareProperty(ITableWorkspaceProperty(\"ResultTable\",\"\",direction=Direction.Input))\r\n\t\tself.declareProperty(\"BestValue\",-1000.0,direction=Direction.InOut,doc=\"Specify best X coord, or default to let algorithm guess\") # default is to guess based on rates\r\n\tdef category(self):\r\n\t\treturn \"Muon\\\\Tuning\"\r\n\t\t\r\n\tdef PyExec(self):\r\n\t\tx=self.getProperty(\"BestValue\").value\r\n\t\ttab=self.getProperty(\"ResultTable\").value\r\n\t\tmag=tab.getColumnNames()[0]\r\n\t\tif(x==-1000):\r\n\t\t\t# guess best\r\n\t\t\trmax=0.0\r\n\t\t\tfor row in tab:\r\n\t\t\t\trates=[]\r\n\t\t\t\tfor (key,val) in list(row.items()):\r\n\t\t\t\t\tif(key[-4:]==\"Rate\"):\r\n\t\t\t\t\t\trates.append(val)\r\n\t\t\t\trthis=sum(rates)\r\n\t\t\t\tif(rthis>rmax):\r\n\t\t\t\t\tx=row[mag]\r\n\t\t\t\t\trmax=rthis\r\n\t\t\tself.log().notice(\"Found best value \"+mag+\"=\"+str(x))\r\n\t\trefvals={}\r\n\t\tfor mag0 in MAGNETS+OTHERS:\r\n\t\t\trefvals[mag0]=cached_get_block(mag0)\r\n\t\ttoSet=setTune(refvals,mag,x)\r\n\t\ttry:\r\n\t\t\tfor tsb,tsv in list(toSet.items()):\r\n\t\t\t\t#print \"doing cached_cset(\",tsb,\",\",tsv,\",wait=True)\"\r\n\t\t\t\tcached_cset(tsb,tsv,wait=True) # all at once with one \"Wait\"\r\n\t\t\t\t#print \"done the cached cset.\"\r\n\t\t\tself.setProperty(\"BestValue\",x)\r\n\t\texcept:\r\n\t\t\tself.log().warning(\"Couldn't set one of the magnets, resetting all other values\")\r\n\t\t\tfor tsb in list(toSet.keys()):\r\n\t\t\t\ttsv=refvals[tsb]\r\n\t\t\t\tcached_cset(tsb,tsv,wait=True) # all at once with one \"Wait\"\r\n\t\t\tself.setProperty(\"BestValue\",-1000.0)\r\n\t\t\ttoSet={}\r\n\t\tfor mag0 in MAGNETS+OTHERS:\r\n\t\t\tif(mag0 in toSet):\r\n\t\t\t\tself.log().notice(mag0+\" changed from \"+str(refvals[mag0])+\" to \"+str(toSet[mag0]))\r\n\t\t\telse:\r\n\t\t\t\tself.log().notice(mag0+\" unchanged, still \"+str(refvals[mag0]))\r\nAlgorithmFactory.subscribe(ChooseBestValue)\r\n\r\nclass ScanMagnet(PythonAlgorithm):\r\n\tdef PyInit(self):\r\n\t\tself.declareProperty(StringArrayProperty(\"Machines\",[])) # NDX.. names\r\n\t\tself.declareProperty(StringArrayProperty(\"Cameras\",[])) # names\r\n\t\tself.declareProperty(\"Magnet\",\"\",StringListValidator(TUNABLES))\r\n\t\tself.declareProperty(FloatArrayProperty(\"ScanValues\",[0.0]),doc=\"list of values to scan\")\r\n\t\tself.declareProperty(\"Frames\",5000) # only if New Runs\r\n\t\tself.declareProperty(ITableWorkspaceProperty(\"RunNumList\",\"\",direction=Direction.Output)) # output table, new x vals and run numbers only\r\n\tdef category(self):\r\n\t\treturn \"Muon\\\\Tuning\"\r\n\t\t\r\n\tdef PyExec(self):\r\n\t\t# catch errors in cset and omit the out of range points from the result table\r\n\t\t# sanity check that the algorithm isn't already running!\r\n\t\tif (len(AlgorithmManager.runningInstancesOf(self.name()))>1):\r\n\t\t\traise Exception(\"TuneMagnet is already running\")\r\n\t\t\r\n\t\tMACHINES=self.getProperty(\"Machines\").value\r\n\t\tCAMERAS=self.getProperty(\"Cameras\").value\r\n\t\t\r\n\t\tMag=self.getProperty(\"Magnet\").value\r\n\t\tscanvals=self.getProperty(\"ScanValues\").value\r\n\t\tframes=self.getProperty(\"Frames\").value\r\n\t\ttt=WorkspaceFactory.createTable()\r\n\t\ttt.addColumn(\"double\",Mag,1)\r\n\t\tfor mac in MACHINES:\r\n\t\t\tmac0=mac.replace(\"NDX\",\"\",1)\r\n\t\t\ttt.addColumn(\"int\",mac0+\"Run\",6)\r\n\t\tfor cam in CAMERAS:\r\n\t\t\ttt.addColumn(\"int\",cam+\"File\",6)\r\n\r\n\t\tProg=Progress(self,start=0.0,end=1.0,nreports=2*len(scanvals))\r\n\t\tframes=self.getProperty(\"Frames\").value\r\n\t\tcontroller = MultipleDaeController()\r\n\t\tfor m in MACHINES:\r\n\t\t\tcontroller.add_machine(m, WAITFOR_TIMEOUT_SECONDS)\r\n\t\tcontroller.run_on_all(\"set_waitfor_sleep_interval\",5)\r\n\t\tstatuses=controller.run_on_all(\"get_run_state\")\r\n\t\terrstr=\"\"\r\n\t\tfor m,status in list(statuses.items()):\r\n\t\t\tif(status != \"SETUP\"):\r\n\t\t\t\terrstr=errstr+\" \"+m+\"=\"+status\r\n\t\tif(errstr != \"\"):\r\n\t\t\traise Exception(\"Instruments are not all in SETUP state:\"+errstr)\r\n\t\t# initialise cameras\r\n\t\tcnums=[0]*len(CAMERAS)\r\n\t\tfor i,cam in enumerate(CAMERAS):\r\n\t\t\tcs=CPARS[cam][\"finder\"](CPARS[cam][\"data\"],0,-1)\r\n\t\t\tcnums[i]=cs[0]\r\n\t\t\tself.log().notice(\"camera \"+str(i)+\" starting file=\"+str(cnums[i]))\r\n\r\n\t\trefvals={}\r\n\t\tfor mag0 in MAGNETS+OTHERS:\r\n\t\t\trefvals[mag0]=cached_get_block(mag0)\r\n\r\n\t\tfor x in scanvals:\r\n\t\t\ttry:\r\n\t\t\t\ttoSet=setTune(refvals,Mag,x)\r\n\t\t\t\t#for (mag,value) in toSet.items():\r\n\t\t\t\t#\tcset(mag,value,wait=True)\r\n\t\t\t\tfor tsb,tsv in list(toSet.items()):\r\n\t\t\t\t\tself.log().notice(\"doing cached_cset(\"+str(tsb)+\",\"+str(tsv)+\")\")\r\n\t\t\t\t\tcached_cset(tsb,tsv,wait=True) # all at once with one \"Wait\"\r\n\t\t\t\t\t#print \"done cached cset.\"\r\n\t\t\texcept:\r\n\t\t\t\tself.log().warning(\"Couldn't set magnets for x=\"+str(x))\r\n\t\t\telse: # successful cset, take data, report errors here\r\n\t\t\t\t# camera call 1\r\n\t\t\t\tfor i,cam in enumerate(CAMERAS):\r\n\t\t\t\t\tcs=CPARS[cam][\"finder\"](CPARS[cam][\"data\"],cnums[i],0)\r\n\t\t\t\t\tcnums[i]=cs[0]\r\n\t\t\t\t\t#print \"camera\",i,\"file now=\",cnums[i]\r\n\t\t\t\tProg.report(\"Data collection\")\r\n\t\t\t\tcontroller.run_on_all(\"begin\",waitfor_frames=frames) # assumes waits for this many frames to be reached on all before continuing\r\n\t\t\t\truns0=controller.run_on_all(\"get_run_number\") # new method which will return a list of the run numbers in progress?\r\n\t\t\t\truns={}\r\n\t\t\t\tfor m,r in list(runs0.items()):\r\n\t\t\t\t\truns[m]=r[0] # real get_run_number returns tuple of number and an empty string!\r\n\t\t\t\tself.log().notice(\"runs in progress are\"+str(runs))\r\n\t\t\t\t# ensure runs really have finished\r\n\t\t\t\tfinished=False\r\n\t\t\t\tabandon=False\r\n\t\t\t\twhile(not finished):\r\n\t\t\t\t\tfinished=True\r\n\t\t\t\t\tstatuses=controller.run_on_all(\"get_run_state\")\r\n\t\t\t\t\terrstr=\"\"\r\n\t\t\t\t\tfor m,status in list(statuses.items()):\r\n\t\t\t\t\t\tif(status != \"RUNNING\"):\r\n\t\t\t\t\t\t\terrstr=errstr+\" \"+m+\"=\"+status\r\n\t\t\t\t\tif(errstr != \"\"):\r\n\t\t\t\t\t\tself.log().warning(\"Instruments are not all in RUNNING state:\"+errstr+\"; abandoning scan and saving previous completed runs\")\r\n\t\t\t\t\t\tabandon=True # to get out of for() scan loop\r\n\t\t\t\t\t\tbreak # out of while loop\r\n\t\t\t\t\tallframes=controller.run_on_all(\"get_frames\")\r\n\t\t\t\t\tfor m,ff in list(allframes.items()):\r\n\t\t\t\t\t\tself.log().notice(str(m)+\" is at \"+str(ff)+\"frames out of \"+str(frames))\r\n\t\t\t\t\t\tif(ff0)):\r\n\t\t\t\t\t\tcs=CPARS[cam][\"finder\"](CPARS[cam][\"data\"],cnums[i],1)\r\n\t\t\t\t\t\tif(not cs[1]):\r\n\t\t\t\t\t\t\tself.log().notice(\"camera \"+cam+\" has not taken a good picture yet, waiting for it\")\r\n\t\t\t\t\t\t\ttime.sleep(5)\r\n\t\t\t\t\t\t\tci=ci-1\r\n\t\t\t\t\tself.log().notice(\"chosen picture \"+str(cs[0])+\" from camera \"+cam)\r\n\t\t\t\t\tcnums[i]=cs[0]\r\n\t\t\t\tif(TESTMODE_DAQ==\"abort\"):\r\n\t\t\t\t\tcontroller.run_on_all(\"abort\") # end but don't fill the archive disks.\r\n\t\t\t\t\tfor mac in list(runs.keys()):\r\n\t\t\t\t\t\truns[mac]-=1 # current run not saved, use the previous run instead!\r\n\t\t\t\telse:\r\n\t\t\t\t\tcontroller.run_on_all(\"end\") # end and save them all.\r\n\t\t\t\tself.log().notice(\"measured at x=\"+str(x)+\" into runs \"+str(runs))\r\n\t\t\t\truns2=[]\r\n\t\t\t\tfor mac in MACHINES:\r\n\t\t\t\t\truns2.append(runs[mac])\r\n\t\t\t\tProg.report(\"Data collection\")\r\n\t\t\t\ttt.addRow([x]+runs2+cnums)\r\n\r\n\t\tfor tsb in list(toSet.keys()):\r\n\t\t\ttsv=refvals[tsb]\r\n\t\t\tself.log().notice(\"doing cached_cset(\"+str(tsb)+\",\"+str(tsv)+\")\")\r\n\t\t\tcached_cset(tsb,tsv,wait=True) # all at once with one \"Wait\"\r\n\t\tself.setProperty(\"RunNumList\",tt)\r\n\t\t# create reference file\r\n\t\ttt2=WorkspaceFactory.createTable()\r\n\t\ttt2.addColumn(\"str\",\"MagnetName\",6)\r\n\t\ttt2.addColumn(\"double\",\"Reference\",2)\r\n\t\tfor mag1 in MAGNETS+OTHERS:\r\n\t\t\ttt2.addRow([mag1,refvals[mag1]])\r\n\t\tAnalysisDataService.addOrReplace(self.getProperty(\"RunNumList\").valueAsStr+\"_Reference\",tt2)\r\nAlgorithmFactory.subscribe(ScanMagnet)\r\n\r\nclass AnalyseTuningScan(PythonAlgorithm):\r\n\tdef PyInit(self):\r\n\t\t#self.declareProperty(StringArrayProperty(\"Machines\",MACHINES0))\r\n\t\t#self.declareProperty(\"Magnet\",\"\",StringListValidator(TUNABLES))\r\n\t\t#self.declareProperty(\"LowerLimit\",0.0)\r\n\t\t#self.declareProperty(\"UpperLimit\",100.0)\r\n\t\t#self.declareProperty(\"Steps\",10)\r\n\t\t#self.declareProperty(\"Frames\",5000) # only if New Runs\r\n\t\tself.declareProperty(ITableWorkspaceProperty(\"OldTable\",\"\",direction=Direction.Input,optional=PropertyMode.Optional),doc=\"If already measured, run numbers on each machine\") # table with old run numbers vs X to re-analyse; old analysis will be redone if present\r\n\t\tself.declareProperty(ITableWorkspaceProperty(\"NewRuns\",\"\",direction=Direction.Input),doc=\"run numbers on each machine\") # table with newly measured run numbers to analyse\r\n\t\tself.declareProperty(ITableWorkspaceProperty(\"OutputTable\",\"\",direction=Direction.Output),doc=\"Full analysis as requested\")\r\n\t\tself.declareProperty(\"DoDeadTimeCorr\",True)\r\n\t\tself.declareProperty(\"MeasureTF20asym\",False)\r\n\t\tself.declareProperty(\"MeasurePromptPeaks\",False)\r\n\t\tself.declareProperty(\"MeasureDoublePulse\",False)\r\n\tdef category(self):\r\n\t\treturn \"Muon\\\\Tuning\"\r\n\r\n\tdef PyExec(self):\r\n\t\tself.setAlgStartupLogging=False # attempt to reduce unnecessary log messages\r\n\t\tdoDead=self.getProperty(\"DoDeadTimeCorr\").value\r\n\t\tdoTF=self.getProperty(\"MeasureTF20asym\").value\r\n\t\tdoPrompt=self.getProperty(\"MeasurePromptPeaks\").value\r\n\t\tdo2nd=self.getProperty(\"MeasureDoublePulse\").value\r\n\r\n\t\t# determine machine/analysis options and column names and build new table header\r\n\t\ttt=WorkspaceFactory.createTable()\r\n\t\tcolNames=self.getProperty(\"NewRuns\").value.getColumnNames()\r\n\t\tmacNames=[]\r\n\t\tcamNames=[]\r\n\t\ttt.addColumn(\"double\",colNames[0],1) # scan variable\r\n\t\tfor cc in colNames:\r\n\t\t\tif(cc.endswith(\"Run\")):\r\n\t\t\t\tmac=cc[:-3]\r\n\t\t\t\tmacNames.append(mac)\r\n\t\t\t\ttt.addColumn(\"int\",mac+\"Run\",6)\r\n\t\t\t\ttt.addColumn(\"double\",mac+\"Rate\",2)\r\n\t\t\t\ttt.addColumn(\"double\",mac+\"RateErr\",5)\r\n\t\t\t\tif(doTF):\r\n\t\t\t\t\ttt.addColumn(\"double\",mac+\"Alpha\",2)\r\n\t\t\t\t\ttt.addColumn(\"double\",mac+\"AlphaErr\",5)\r\n\t\t\t\t\ttt.addColumn(\"double\",mac+\"Asym\",2)\r\n\t\t\t\t\ttt.addColumn(\"double\",mac+\"AsymErr\",5)\r\n\t\t\t\tif(doPrompt):\r\n\t\t\t\t\ttt.addColumn(\"double\",mac+\"Prompt\",2)\r\n\t\t\t\t\ttt.addColumn(\"double\",mac+\"PromptErr\",5)\r\n\t\t\t\tif(do2nd):\r\n\t\t\t\t\ttt.addColumn(\"double\",mac+\"DoubleP\",2)\r\n\t\t\t\t\ttt.addColumn(\"double\",mac+\"DoublePErr\",5)\r\n\t\t\tif(cc.endswith(\"File\")):\r\n\t\t\t\tcam=cc[:-4]\r\n\t\t\t\tcamNames.append(cam)\r\n\t\t\t\ttt.addColumn(\"int\",cam+\"File\",6)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"Xpos\",2)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"XposErr\",5)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"Ypos\",2)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"YposErr\",5)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"Width\",2)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"WidthErr\",5)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"Height\",2)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"HeightErr\",5)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"Ellip\",2)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"EllipErr\",5)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"Intens\",2)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"IntensErr\",5)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"Backgd\",2)\r\n\t\t\t\ttt.addColumn(\"double\",cam+\"BackgdErr\",5)\r\n\t\t\r\n\t\t#print \"grand list of columns:\",tt.getColumnNames()\r\n\t\trowsToDo=[]\r\n\t\tif(not self.getProperty(\"OldTable\").isDefault):\r\n\t\t\tfor r in self.getProperty(\"OldTable\").value:\r\n\t\t\t\trowsToDo.append(r)\r\n\t\tfor r in self.getProperty(\"NewRuns\").value:\r\n\t\t\trowsToDo.append(r)\r\n\t\t# determine MACHINES from column headings *Run and *File\r\n\t\t#MACHINES=self.getProperty(\"Machines\").value\r\n\t\t\r\n\t\t# determine magnet scanned by column 1 in all tables, actual name just to be copied to output\r\n\t\t#Mag=self.getProperty(\"Magnet\").value\r\n\t\tMag=colNames[0]\r\n\r\n\t\t# clone reference file for output (parent alg already checked consistency)\r\n\t\ttt2=WorkspaceFactory.createTable()\r\n\t\ttt2.addColumn(\"str\",\"MagnetName\",6)\r\n\t\ttt2.addColumn(\"double\",\"Reference\",2)\r\n\t\ttt3=mtd[self.getProperty(\"NewRuns\").valueAsStr+\"_Reference\"]\r\n\t\tfor r in tt3:\r\n\t\t\ttt2.addRow([r[\"MagnetName\"],r[\"Reference\"]])\r\n\t\tAnalysisDataService.addOrReplace(self.getProperty(\"OutputTable\").valueAsStr+\"_Reference\",tt2)\r\n\r\n\t\tProg=Progress(self,start=0.0,end=1.0,nreports=len(rowsToDo))\r\n\t\tfor r in rowsToDo:\r\n\t\t\ttr=[r[Mag]]\r\n\t\t\tfor mac in macNames:\r\n\t\t\t\tf=DPARS[mac][\"data\"] % r[mac+\"Run\"]\r\n\t\t\t\ttoload=10\r\n\t\t\t\twhile toload>0:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\twss=LoadMuonNexus(Filename=f,DeadTimeTable=\"dttab\",DetectorGroupingTable=\"groups\",EnableLogging=False)\r\n\t\t\t\t\t\ttoload=0\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tself.log().notice(\"file\"+str(f)+\"isn't in the archive yet, waiting 10 seconds\")\r\n\t\t\t\t\t\ttime.sleep(10)\r\n\t\t\t\t\t\ttoload = toload-1\r\n\t\t\t\tws=wss[0]\r\n\t\t\t\tframes=wss[0].getRun().getProperty(\"goodfrm\").value\r\n\t\t\t\tif(doDead):\r\n\t\t\t\t\t# correct for dead time\r\n\t\t\t\t\tws=ApplyDeadTimeCorr(InputWorkspace=ws,DeadTimeTable=wss[4],EnableLogging=False)\r\n\t\t\t\t# rate by default\r\n\t\t\t\tgrouped=MuonGroupDetectors(InputWorkspace=ws,DetectorGroupingTable=wss[5],EnableLogging=False)\r\n\t\t\t\tif(doTF):\r\n\t\t\t\t\talpha=AlphaCalc(grouped,FirstGoodValue=0.5,LastGoodValue=10.0,EnableLogging=False)\r\n\t\t\t\t\tself.log().notice(\"First guess of alpha=\"+str(alpha))\r\n\t\t\t\t\tasy=AsymmetryCalc(grouped,Alpha=alpha,EnableLogging=False)\r\n\t\t\t\t\tfguess=ws.getRun().getProperty(\"sample_magn_field\").value*0.01355\r\n\t\t\t\t\tfitdat=Fit(Function=\"name=ExpDecayOsc,A=0.2,Lambda=0.01,Frequency=\"+str(fguess)+\",Phi=0.1;name=FlatBackground,A0=0.0\",InputWorkspace=asy,StartX=DPARS[mac][\"tgbegin\"],EndX=DPARS[mac][\"tgend\"],Output=\"Fitted\",EnableLogging=False)\r\n\t\t\t\t\talpha=alpha+(2.0*alpha*fitdat[3].cell(\"Value\",4)) # refined value, redo fit\r\n\t\t\t\t\tself.log().notice(\"Second guess of alpha=\"+str(alpha)+\" using A0=\"+str(fitdat[3].cell(\"Value\",4)))\r\n\t\t\t\t\tasy=AsymmetryCalc(grouped,Alpha=alpha,EnableLogging=False)\r\n\t\t\t\t\tfitdat=Fit(Function=\"name=ExpDecayOsc,A=0.2,Lambda=0.01,Frequency=\"+str(fguess)+\",Phi=0.1;name=FlatBackground,A0=0.0\",InputWorkspace=asy,StartX=DPARS[mac][\"tgbegin\"],EndX=DPARS[mac][\"tgend\"],Output=\"Fitted\",EnableLogging=False)\r\n\t\t\t\t\talpha=alpha+(2.0*alpha*fitdat[3].cell(\"Value\",4)) # refined value, redo fit\r\n\t\t\t\t\tself.log().notice(\"Third guess of alpha=\"+str(alpha)+\" using A0=\"+str(fitdat[3].cell(\"Value\",4)))\r\n\t\t\t\t\tasy=AsymmetryCalc(grouped,Alpha=alpha,EnableLogging=False)\r\n\t\t\t\t\tfitdat=Fit(Function=\"name=ExpDecayOsc,A=0.2,Lambda=0.01,Frequency=\"+str(fguess)+\",Phi=0.1;name=FlatBackground,A0=0.0\",InputWorkspace=asy,StartX=DPARS[mac][\"tgbegin\"],EndX=DPARS[mac][\"tgend\"],Output=\"Fitted\",EnableLogging=False)\r\n\t\t\t\t\talpha=alpha+(2.0*alpha*fitdat[3].cell(\"Value\",4))\r\n\t\t\t\t\tself.log().notice(\"Fourth guess of alpha=\"+str(alpha)+\" using A0=\"+str(fitdat[3].cell(\"Value\",4)))\r\n\t\t\t\telse:\r\n\t\t\t\t\talpha=1.0\r\n\t\t\t\tsf=ExtractSingleSpectrum(InputWorkspace=grouped,WorkspaceIndex=0,EnableLogging=False)\r\n\t\t\t\tsb=ExtractSingleSpectrum(InputWorkspace=grouped,WorkspaceIndex=1,EnableLogging=False)\r\n\t\t\t\tsba=Scale(InputWorkspace=sb,Factor=alpha,Operation=\"Multiply\",EnableLogging=False)\r\n\t\t\t\ts=Plus(LHSWorkspace=sf,RHSWorkspace=sba,EnableLogging=False)\r\n\t\t\t\tinteg=Integration(InputWorkspace=s,RangeLower=DPARS[mac][\"tgbegin\"],RangeUpper=DPARS[mac][\"tgend\"],EnableLogging=False)\r\n\t\t\t\trate=integ.dataY(0)[0]/frames\r\n\t\t\t\trateErr=integ.dataE(0)[0]/frames\r\n\t\t\t\ttr.extend([r[mac+\"Run\"],rate,rateErr])\r\n\t\t\t\tif(doTF):\r\n\t\t\t\t\t# check that Phi is close to 0, Asym might be negative if muons are polarised the wrong way. Or save phi too?\r\n\t\t\t\t\tmAsym=fitdat[3].cell(\"Value\",0) # from xx_Parameters table\r\n\t\t\t\t\teAsym=fitdat[3].cell(\"Error\",0)\r\n\t\t\t\t\teAlpha=fitdat[3].cell(\"Error\",4)*2*alpha\r\n\t\t\t\t\tif(math.cos(fitdat[3].cell(\"Value\",3)) < 0):\r\n\t\t\t\t\t\tmAsym=-mAsym\r\n\t\t\t\t\ttr.extend([alpha,eAlpha,mAsym,eAsym])\r\n\t\t\t\tif(doPrompt):\r\n\t\t\t\t\tprws=Integration(InputWorkspace=ws,RangeLower=DPARS[mac][\"promptbegin\"],RangeUpper=DPARS[mac][\"promptend\"],EnableLogging=False)\r\n\t\t\t\t\ttr.extend([prws.dataY(0)[0]/frames,prws.dataE(0)[0]/frames])\r\n\t\t\t\t\t# integrate a suggested region or regions\r\n\t\t\t\t\t# give absolute rate as counts/frame\r\n\t\t\t\t\tpass\r\n\t\t\t\tif(do2nd):\r\n\t\t\t\t\t# contamination factor, 0.0=pure correct single pulse, 1.0=equal double pulse, >1 = wrong pulse!\r\n\t\t\t\t\tecs=RemoveExpDecay(s,EnableLogging=False)\r\n\t\t\t\t\tp1ws=Integration(InputWorkspace=ecs,RangeLower=DPARS[mac][\"p1begin\"],RangeUpper=DPARS[mac][\"p1end\"],EnableLogging=False)\r\n\t\t\t\t\tp12ws=Integration(InputWorkspace=ecs,RangeLower=DPARS[mac][\"tgbegin\"],RangeUpper=DPARS[mac][\"tgend\"],EnableLogging=False)\r\n\t\t\t\t\tr1=p1ws.dataY(0)[0]/(p1ws.dataX(0)[1]-p1ws.dataX(0)[0])\r\n\t\t\t\t\tr12=p12ws.dataY(0)[0]/(p12ws.dataX(0)[1]-p12ws.dataX(0)[0])\r\n\t\t\t\t\tif(DPARS[mac][\"pulse\"]==1):\r\n\t\t\t\t\t\ttr.extend([(r12-r1)/r1,0.0]) # do error analysis!\r\n\t\t\t\t\telif(DPARS[mac][\"pulse\"]==2):\r\n\t\t\t\t\t\ttr.extend([r1/(r12-r1),0.0])\r\n\t\t\t\t\t# integrate region between pulses, avoiding prompt pulses = P1\r\n\t\t\t\t\t# also get final count rate extrapolated back = P12\r\n\t\t\t\t\t# for MuSR: fraction = P1/(P12-P1)\r\n\t\t\t\t\t# for EMU/HIFI: fraction=(P12-P1)/P1\r\n\t\t\t\t\t# if TF data, having got alpha, calc \"sum\" = F+alpha*B rather than F+B.\r\n\t\t\tfor cam in camNames:\r\n\t\t\t\t# load camera file and analyse it, append to tr[]\r\n\t\t\t\tparset=CPARS[cam][\"processor\"](CPARS[cam][\"data\"] % r[mac+\"File\"])\r\n\t\t\t\ttr.append(r[mac+\"File\"])\r\n\t\t\t\ttr.extend(parset)\r\n\t\t\t#print \"row ready to add:\",tr\r\n\t\t\ttt.addRow(tr)\r\n\t\t\tProg.report(\"Data analysis\")\r\n\t\tself.setProperty(\"OutputTable\",tt)\r\nAlgorithmFactory.subscribe(AnalyseTuningScan)\r\n","sub_path":"muon/CommonBeamTuning.py","file_name":"CommonBeamTuning.py","file_ext":"py","file_size_in_byte":38005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"572426857","text":"class Usuario():\n def __init__(self, usuario, clave, correo_electronico, nombre, dinero, productos = []):\n self.usuario = usuario\n self.clave = clave\n self.correo_electronico = correo_electronico\n self.nombre = nombre\n self.dinero = int(dinero)\n self.productos = productos\n\n\n# ------------- Lectura de Archivo ----------------\nlista_de_personas = {}\narchivo = open('usuarios.txt', 'r+')\nlines = archivo.readlines()\nnombre =''\nclave = ''\ndinero = 0\ncorreo_electronico = ''\nusuario = ''\nproductos = []\nfor i in range(2,len(lines)-4):\n if lines[i].find('\"nombre\": ') != -1:\n nombre = lines[i].lstrip('\"nombre\": \"').split('\"')[0]\n # print(nombre)\n if lines[i].find('\"clave\": ') != -1:\n clave = lines[i].lstrip('\"clave\":\"')[14:]\n clave = clave.split('\"')[0]\n if lines[i].find('\"dinero\": ') != -1:\n dinero = int(lines[i].lstrip('\"dinero\": ').split(',')[0])\n # print(dinero)\n if lines[i].find('\"correo electronico\": ') != -1:\n correo_electronico = lines[i].lstrip('\"correo electronico\": ').split('\"')[0]\n # print(correo_electronico)\n if lines[i].find('\"usuario\": ') != -1:\n usuario = lines[i].lstrip('\"usuario\":').split('\"')[3]\n # print(usuario)\n if lines[i].find('\"productos\": [') != -1:\n productos = []\n for n in range(0,100):\n if lines[i+n].find(']') != -1:\n for j in range(0, n-1):\n productos.append(int(lines[i+j+1].lstrip().split(',')[0]))\n break\n # print(productos)\n # print('---------------------')\n persona = Usuario(correo_electronico = correo_electronico, dinero = dinero, productos = productos, nombre = nombre, clave = clave, usuario = usuario)\n lista_de_personas[usuario] = persona\n# ------------- Lectura de Archivo ----------------\n\ndef ranking_de_vendedores(lista_subastas_finalizadas, lista_de_personas):\n lista=[]\n for i in lista_de_personas:\n suma_vendidada = 0\n for j in lista_subastas_finalizadas:\n if lista_subastas_finalizadas[j].vendedor == i:\n suma_vendidada = suma_vendidada + lista_subastas_finalizadas[j].precio\n lista.append((i,suma_vendidada))\n lista_de_vendedores = []\n contador = 0\n contador2 = 0\n for n in lista:\n if contador == 0:\n lista_de_vendedores.append(n)\n contador += 1\n else:\n dinero_usuario_actual = n[1]\n for j in range(0, len(lista_de_vendedores)):\n if dinero_usuario_actual > lista_de_vendedores[j][1]:\n lista_de_vendedores.insert(j, n)\n contador2 += 1\n break\n if contador2 == 0:\n lista_de_vendedores.append(n)\n print('')\n print('Los 10 usuarios que msa han obtenido dinero por ventas son: ')\n for b in range(0,9):\n print('El usuario',lista_de_vendedores[b][0],'ha vendido',lista_de_vendedores[b][1])\n\ndef cerrar_usuarios(lista_de_personas):\n archivo = open('usuarios.txt', 'w')\n archivo.write('[\\n')\n contador = 0\n for i in lista_de_personas:\n archivo.write(' {\\n')\n archivo.write(' \"nombre\": \"')\n archivo.write(str(lista_de_personas[i].nombre))\n archivo.write('\",\\n')\n archivo.write(' \"clave\": \"')\n archivo.write(str(lista_de_personas[i].clave))\n archivo.write('\",\\n')\n archivo.write(' \"dinero\": ')\n archivo.write(str(lista_de_personas[i].dinero))\n archivo.write(',\\n')\n archivo.write(' \"correo electronico\": \"')\n archivo.write(str(lista_de_personas[i].correo_electronico))\n archivo.write('\",\\n')\n archivo.write(' \"usuario\": \"')\n archivo.write(str(lista_de_personas[i].usuario))\n archivo.write('\",\\n')\n archivo.write(' \"productos\": [\\n')\n for n in range(0, len(lista_de_personas[i].productos)):\n if n == len(lista_de_personas[i].productos)-1:\n archivo.write(' ')\n archivo.write(str(lista_de_personas[i].productos[n]))\n archivo.write('\\n')\n else:\n archivo.write(' ')\n archivo.write(str(lista_de_personas[i].productos[n]))\n archivo.write(',\\n')\n if contador == (len(lista_de_personas) -1):\n archivo.write(' ]\\n }\\n')\n contador += 1\n else:\n archivo.write(' ]\\n },\\n')\n contador += 1\n archivo.write(']')","sub_path":"Tareas/Tarea 01/usuario.py","file_name":"usuario.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"459576286","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\story_progression\\story_progression_action_university.py\n# Compiled at: 2019-10-01 02:14:09\n# Size of source mod 2**32: 6666 bytes\nfrom date_and_time import create_time_span, create_date_and_time, DateAndTime\nfrom math import floor\nfrom sims.university.university_housing_tuning import UniversityHousingTuning\nfrom sims4.random import weighted_random_item\nfrom sims4.tuning.tunable import Tunable, TunableInterval, TunableList, TunableTuple, TunableRange\nfrom sims.university.university_enums import EnrollmentStatus\nfrom story_progression.story_progression_action import _StoryProgressionAction\nfrom tunable_time import TunableTimeOfDay\nimport services, sims4\nlogger = sims4.log.Logger('StoryProgressionActionUniversity', default_owner='jmorrow')\n\nclass StoryProgressionActionUniversity(_StoryProgressionAction):\n UNSET = 0\n FACTORY_TUNABLES = {'time_to_update_progress':TunableTimeOfDay(description='\\n The approximate time of day when the action should update story \\n progress.\\n ',\n default_hour=20), \n 'performance_gain_per_day':TunableInterval(description='\\n The amount of work performance to give a university student per day.\\n ',\n tunable_type=float,\n default_lower=70,\n default_upper=90,\n minimum=0), \n 'number_of_classes_to_take_on_reenrollment':TunableList(description='\\n A list of weighted numbers of classes to take when this story\\n progression action re-enrolls a sim.\\n ',\n tunable=TunableTuple(weight=Tunable(description='\\n The relative chance of taking this number of classes.\\n ',\n tunable_type=int,\n default=1),\n number_of_classes=TunableRange(description='\\n The number of classes to take.\\n ',\n tunable_type=int,\n default=3,\n minimum=1)))}\n\n def __init__(self, **kwargs):\n (super().__init__)(**kwargs)\n self._next_update_time = None\n self._weighted_class_counts = []\n for pair in self.number_of_classes_to_take_on_reenrollment:\n self._weighted_class_counts.append((pair.weight, pair.number_of_classes))\n\n def save(self, data):\n if self._next_update_time is None:\n data.university_action.next_update_time = StoryProgressionActionUniversity.UNSET\n else:\n data.university_action.next_update_time = self._next_update_time.absolute_ticks()\n\n def load(self, data):\n university_data = data.university_action\n if university_data.next_update_time == StoryProgressionActionUniversity.UNSET:\n self._next_update_time = None\n else:\n self._next_update_time = DateAndTime(university_data.next_update_time)\n\n def should_process(self, options):\n now = services.time_service().sim_now\n if self._next_update_time is None:\n self._next_update_time = create_date_and_time(days=(floor(now.absolute_days())), hours=(self.time_to_update_progress.hour()))\n if self._next_update_time < now:\n self._next_update_time += create_time_span(days=1)\n if now >= self._next_update_time:\n self._next_update_time += create_time_span(days=1)\n return True\n return False\n\n def process_action(self, story_progression_flags):\n for sim_info in services.sim_info_manager().get_all():\n degree_tracker = sim_info.degree_tracker\n if degree_tracker is None:\n continue\n else:\n if sim_info in services.active_household():\n continue\n enrollment_status = degree_tracker.get_enrollment_status()\n if enrollment_status == EnrollmentStatus.ENROLLED:\n if degree_tracker.term_started_time is None:\n continue\n course_slots = degree_tracker.get_career_course_slots()\n for course_slot in course_slots:\n performance = self.performance_gain_per_day.random_float()\n course_slot.add_work_performance(performance)\n\n if enrollment_status == EnrollmentStatus.NOT_ENROLLED:\n if not sim_info.is_played_sim:\n self._reenroll(sim_info)\n elif enrollment_status == EnrollmentStatus.GRADUATED:\n if sim_info.zone_id in UniversityHousingTuning.get_university_housing_zone_ids():\n household = sim_info.is_played_sim or sim_info.household\n if household.household_size == 1:\n household.clear_household_lot_ownership()\n household_manager = services.household_manager()\n target_household = household_manager.create_household(sim_info.account)\n household_manager.switch_sim_from_household_to_target_household(sim_info, household, target_household)\n\n def _reenroll(self, sim_info):\n degree_tracker = sim_info.degree_tracker\n degree_tracker.enroll(degree_tracker.get_major(), degree_tracker.get_university(), weighted_random_item(self._weighted_class_counts), [])","sub_path":"Scripts/simulation/story_progression/story_progression_action_university.py","file_name":"story_progression_action_university.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"73713657","text":"import abc\nfrom ifind.common.language_model import LanguageModel\n\nclass BaseTextClassifier(object):\n \"\"\"\n \"\"\"\n def __init__(self, topic, stopword_file=[], background_file=[]): # Refactor; is this the best way to pass in details?\n self._stopword_file = stopword_file\n self._background_file = background_file\n self._topic = topic\n \n if self._background_file:\n self.read_in_background(self._background_file)\n \n @abc.abstractmethod\n def is_relevant(self, document):\n \"\"\"\n Returns True if the given document is relevant.\n This is an abstract method; override this method with an inheriting text classifier.\n \"\"\"\n return True\n \n def read_in_background(self, vocab_file):\n \"\"\"\n Helper method to read in a file containing terms and construct a background language model.\n \"\"\"\n vocab = {}\n f = open(vocab_file, 'r')\n \n for line in f:\n tc = line.split(',')\n vocab[tc[0]] = int(tc[1])\n \n f.close()\n self.background_language_model = LanguageModel(term_dict=vocab)","sub_path":"ifind/apps/simuser/text_classifiers/base_classifier.py","file_name":"base_classifier.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"537956478","text":"from Instruccion import InstruccionDosOperandos\nfrom EnumRegistrosNucleo import EnumRegistrosNucleo\nfrom Palabra import TAMANNO_PALABRA_INSTRUCION\n\nDIR_MINIMA_INSTRUCCIONES = 384\nDIR_MAXIMA_INSTRUCCIONES = 1020\n\nclass InstruccionBne(InstruccionDosOperandos):\n \n def __init__(self):\n InstruccionDosOperandos.__init__(self)\n \n def imprimir(self):\n print(\"Tipo: BNE\")\n InstruccionDosOperandos.imprimir(self)\n\n def decodificar(self, palabra):\n self.registroDestino = palabra.dato[1]\n self.registroFuente1 = palabra.dato[2]\n self.inmediato = palabra.dato[3]\n\n def ejecutar(self, nucleo):\n operando1 = nucleo.obtenerContenidoRegistro(self.registroDestino)\n operando2 = nucleo.obtenerContenidoRegistro(self.registroFuente1)\n if operando1 != operando2:\n pc = nucleo.obtenerContenidoRegistro(EnumRegistrosNucleo.PC.value)\n nuevoPC = (pc + self.inmediato*TAMANNO_PALABRA_INSTRUCION)\n #Revisar si esta bien el PC dado\n if(nuevoPC < DIR_MINIMA_INSTRUCCIONES or nuevoPC > DIR_MAXIMA_INSTRUCCIONES or nuevoPC % 4 != 0):\n print(\"ERROR En BNE se dio la direccion \" + str(nuevoPC) + \" la cual no es valida.\")\n return False\n nucleo.guardarContenidoRegistro(EnumRegistrosNucleo.PC.value, nuevoPC)\n return True","sub_path":"src/InstruccionBne.py","file_name":"InstruccionBne.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"315275646","text":"# -*- coding: utf-8 -*-\n\n'''The stuff in this module is for Python 2 only.\nSee the bag.csv3 module if you use Python 3.\n'''\n\nfrom __future__ import (absolute_import, division, print_function)\nimport csv\n\n\nclass CsvWriter(object):\n '''A CSV writer that encapsulates a stream and supports encodings.'''\n\n def __init__(self, file, encoding='utf8', delimiter=',',\n quoting=csv.QUOTE_MINIMAL, lineterminator='\\r\\n'):\n self._file = file\n self._writer = csv.writer(file, delimiter=str(delimiter),\n quoting=quoting,\n lineterminator=lineterminator)\n self._enc = encoding\n\n def close(self):\n '''Closes the underlying \"file\". If it has a getvalue() method\n (StringIO objects do), the content is returned.\n '''\n s = self._file.getvalue() if hasattr(self._file, 'getvalue') \\\n else None\n if hasattr(self._file, 'close'):\n self._file.close()\n return s\n\n def put(self, vals):\n '''Writes the passed values to the CSV stream.\n Argument: an iterable of unicode or bytes objects. Unicode objects are\n encoded into the output encoding.\n '''\n try:\n self._writer.writerow([\n v.encode(self._enc) if isinstance(v, unicode)\n else v for v in vals])\n except UnicodeEncodeError as e:\n print(vals)\n raise e\n\n @staticmethod\n def file_extension(encoding='utf8'):\n '''Returns an appropriate file extension such as \".utf8.csv\".'''\n return '.{0}.csv'.format(encoding)\n\n\ndef decoding_csv(csv_stream, encoding='utf8'):\n '''\n Generator that wraps a simple CSV reader in order to give you\n unicode objects in the returned rows. Example:\n\n f = open('filepath.csv', 'r')\n for vals in decoding_csv(csv.reader(f, delimiter=b','), \\\n encoding='utf8'):\n print(vals)\n f.close()\n\n This generator removes the UTF8 BOM if the file contains it.\n '''\n # This is the only opportunity I found to remove the UTF8 BOM\n # and still use the csv module.\n row = csv_stream.next()\n if row and row[0].startswith('\\xef\\xbb\\xbf'):\n row[0] = row[0][3:]\n encoding = 'utf8'\n yield([v.decode(encoding) for v in row])\n while True: # eventually, StopIteration is raised by csv_stream\n row = csv_stream.next()\n yield([v.decode(encoding) for v in row])\n\n\nclass UnicodeDictReader(object):\n '''Reads a CSV stream, returning for each row a dictionary where\n the keys are column headers and the values are unicode objects.\n\n Example:\n\n csv = UnicodeDictReader(open('myfile', 'r'), delimiter=b',',\n encoding='iso-8859-1')\n # The constructor has read the first row and memorized the headers,\n # because a 'fieldnames' parameter was not provided.\n for row in csv:\n print(row) # shows a dictionary\n csv.close()\n\n It also removes the UTF8 BOM from your data if the file contains it.\n\n Implementation note: of course the correct way would have been to\n read the file, decode it, then parse it as CSV. That is impossible\n while the Python CSV module does not support unicode objects.\n\n Apparently, in Python 3 we don't need this class anymore.\n '''\n\n def __iter__(self):\n return self\n\n def close(self):\n if hasattr(self.f, 'close'):\n self.f.close()\n\n def __init__(self, f, fieldnames=None, restkey=None, restval=None,\n dialect=\"excel\", encoding='utf8', *args, **kwds):\n self.fieldnames = fieldnames # list of keys for the dict\n self.restkey = restkey # key to catch long rows\n self.restval = restval # default value for short rows\n self.encoding = encoding\n self.f = f\n self.reader = csv.reader(f, dialect, *args, **kwds)\n self.dialect = dialect\n self.line_num = 0\n if not fieldnames: # read fieldnames from the first line now\n try:\n row = self.reader.next()\n except StopIteration:\n pass\n else:\n self.line_num = self.reader.line_num\n if row and row[0].startswith('\\xef\\xbb\\xbf'):\n row[0] = row[0][3:]\n self.encoding = 'utf8'\n self.fieldnames = [v.decode(encoding) for v in row]\n\n def next(self):\n row = self.reader.next()\n while row == []:\n row = self.reader.next()\n self.line_num = self.reader.line_num\n d = dict(zip(self.fieldnames, [v.decode(self.encoding) for v in row]))\n # unlike the basic reader, we prefer not to return blanks,\n # because we will typically wind up with a dict full of\n # None values.\n lf = len(self.fieldnames)\n lr = len(row)\n if lf < lr:\n d[self.restkey] = row[lf:]\n elif lf > lr:\n for key in self.fieldnames[lr:]:\n d[key] = self.restval\n return d\n","sub_path":"bag/csv2.py","file_name":"csv2.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"170255585","text":"################################################################################\n# Neopixel LED Strips\n#\n# Created by VIPER Team 2015 CC\n# Authors: G. Baldi, D. Mazzei\n################################################################################\n\nimport threading\nfrom neopixel import ledstrips as neo\n\n# create all the needed layers\nleds = neo.LedStrip(D6,16)\nlayer0 = neo.LedStrip(D6,16)\nlayer1 = neo.LedStrip(D6,16)\nlayer2 = neo.LedStrip(D6,16)\n\n# fill layers with their initial values\nleds.clear()\nlayer0[0]=(100,0,0)\nlayer0[1]=(100,0,0)\nlayer0[2]=(100,0,0)\nlayer1[0]=(0,100,0)\nlayer1[1]=(0,100,0)\nlayer1[2]=(0,100,0) \nlayer2.clear()\n\n# let's define some coefficients for smooth animation (half a sinus wave)\nanimation_coefficients = [\n 0,\n 0.2588190451,\n 0.5,\n 0.7071067812,\n 0.8660254038,\n 0.9659258263,\n 1,\n 0.9659258263,\n 0.8660254038,\n 0.7071067812,\n 0.5,\n 0.2588190451]\n\n# A Lock is needed to prevent conflicts between threads\nlock = threading.Lock()\n\n# Create a function to handle background animation\ndef animate_background(delay):\n step=0\n while True:\n lock.acquire()\n layer2.setall(0,0,int(50*animation_coefficients[step]))\n lock.release()\n step += 1\n if step >= len(animation_coefficients):\n step=0\n sleep(delay)\n\ndef animate_foreground(delay):\n while True:\n lock.acquire()\n layer0.lshift()\n layer1.rshift()\n lock.release()\n sleep(delay)\n\n# start the background animation thread\nthread(animate_background,500)\n# start the foreground animation thread\nthread(animate_foreground,50)\n\n\nwhile True:\n # clear leds\n leds.clear()\n # now, acquire the lock\n lock.acquire()\n # merge the first and second layer\n leds.merge(layer0)\n leds.merge(layer1)\n # merge the background layer only where leds is transparent (0,0,0) \n leds.merge(layer2,neo.first_color)\n # release the lock\n lock.release()\n # and light it up!\n leds.on()\n sleep(10)\n ","sub_path":"examples/Neopixel_Advanced/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"261449181","text":"\"\"\"\n\n--- Day 25: The Halting Problem ---\n\nFollowing the twisty passageways deeper and deeper into the CPU, you finally reach the core of the computer. Here, in the expansive central chamber, you find a grand apparatus that fills the entire room, suspended nanometers above your head.\n\nYou had always imagined CPUs to be noisy, chaotic places, bustling with activity. Instead, the room is quiet, motionless, and dark.\n\nSuddenly, you and the CPU's garbage collector startle each other. \"It's not often we get many visitors here!\", he says. You inquire about the stopped machinery.\n\n\"It stopped milliseconds ago; not sure why. I'm a garbage collector, not a doctor.\" You ask what the machine is for.\n\n\"Programs these days, don't know their origins. That's the Turing machine! It's what makes the whole computer work.\" You try to explain that Turing machines are merely models of computation, but he cuts you off. \"No, see, that's just what they want you to think. Ultimately, inside every CPU, there's a Turing machine driving the whole thing! Too bad this one's broken. We're doomed!\"\n\nYou ask how you can help. \"Well, unfortunately, the only way to get the computer running again would be to create a whole new Turing machine from scratch, but there's no way you can-\" He notices the look on your face, gives you a curious glance, shrugs, and goes back to sweeping the floor.\n\nYou find the Turing machine blueprints (your puzzle input) on a tablet in a nearby pile of debris. Looking back up at the broken Turing machine above, you can start to identify its parts:\n\n A tape which contains 0 repeated infinitely to the left and right.\n A cursor, which can move left or right along the tape and read or write values at its current position.\n A set of states, each containing rules about what to do based on the current value under the cursor.\n\nEach slot on the tape has two possible values: 0 (the starting value for all slots) and 1. Based on whether the cursor is pointing at a 0 or a 1, the current state says what value to write at the current position of the cursor, whether to move the cursor left or right one slot, and which state to use next.\n\nFor example, suppose you found the following blueprint:\n\nBegin in state A.\nPerform a diagnostic checksum after 6 steps.\n\nIn state A:\n If the current value is 0:\n - Write the value 1.\n - Move one slot to the right.\n - Continue with state B.\n If the current value is 1:\n - Write the value 0.\n - Move one slot to the left.\n - Continue with state B.\n\nIn state B:\n If the current value is 0:\n - Write the value 1.\n - Move one slot to the left.\n - Continue with state A.\n If the current value is 1:\n - Write the value 1.\n - Move one slot to the right.\n - Continue with state A.\n\nRunning it until the number of steps required to take the listed diagnostic checksum would result in the following tape configurations (with the cursor marked in square brackets):\n\n... 0 0 0 [0] 0 0 ... (before any steps; about to run state A)\n... 0 0 0 1 [0] 0 ... (after 1 step; about to run state B)\n... 0 0 0 [1] 1 0 ... (after 2 steps; about to run state A)\n... 0 0 [0] 0 1 0 ... (after 3 steps; about to run state B)\n... 0 [0] 1 0 1 0 ... (after 4 steps; about to run state A)\n... 0 1 [1] 0 1 0 ... (after 5 steps; about to run state B)\n... 0 1 1 [0] 1 0 ... (after 6 steps; about to run state A)\n\nThe CPU can confirm that the Turing machine is working by taking a diagnostic checksum after a specific number of steps (given in the blueprint). Once the specified number of steps have been executed, the Turing machine should pause; once it does, count the number of times 1 appears on the tape. In the above example, the diagnostic checksum is 3.\n\nRecreate the Turing machine and save the computer! What is the diagnostic checksum it produces once it's working again?\n\n\n--- Part Two ---\n\nThe Turing machine, and soon the entire computer, springs back to life. A console glows dimly nearby, awaiting your command.\n\n> reboot printer\nError: That command requires priority 50. You currently have priority 0.\nYou must deposit 50 stars to increase your priority to the required level.\n\nThe console flickers for a moment, and then prints another message:\n\nStar accepted.\nYou must deposit 49 stars to increase your priority to the required level.\n\nThe garbage collector winks at you, then continues sweeping.\n\n\nYou deposit all fifty stars and reboot the printer. Suddenly, everything seems a lot less pixelated than before.\n\n\"--raise your priority level enough to send the reboot command and... hey look, it's printing! I'll bring it to Santa. Thanks!\" She runs off.\n\nCongratulations! You've finished every puzzle in Advent of Code 2017! I hope you had as much fun solving them as I had making them for you. I'd love to hear about your adventure; you can get in touch with me via contact info on my website or through Twitter.\n\nIf you'd like to see more things like this in the future, please consider supporting Advent of Code and sharing it with others.\n\nTo hear about future projects, you can follow me on Twitter.\n\nI've highlighted the easter eggs in each puzzle, just in case you missed any. Hover your mouse over them, and the easter egg will appear.\n\"\"\"\n\n\nclass TuringMachine():\n\n def __init__(self, state):\n self.state = state\n self.pos = 0\n self.ones = []\n\n def _move(self, move, next_state=None, op=None):\n if next_state is not None:\n self.state = next_state\n if op == 1:\n self.ones.append(self.pos)\n elif op == 0:\n self.ones.pop(self.ones.index(self.pos))\n self.pos += move\n\n\nclass TestTuringMachine(TuringMachine):\n\n def move(self):\n value = 1 if self.pos in self.ones else 0\n if self.state == 'A':\n if value == 0:\n self._move(1, 'B', 1)\n else:\n self._move(-1, 'B', 0)\n else:\n if value == 0:\n self._move(-1, 'A', 1)\n else:\n self._move(+1, 'A')\n\n\ndef test1():\n machine = TestTuringMachine('A')\n for i in range(6):\n machine.move()\n assert 3 == len(machine.ones)\n\n\nclass Part1TuringMachine(TuringMachine):\n\n def move(self):\n value = 1 if self.pos in self.ones else 0\n if self.state == 'A':\n if value == 0:\n self._move(1, 'B', 1)\n else:\n self._move(-1, 'C', 0)\n elif self.state == 'B':\n if value == 0:\n self._move(-1, 'A', 1)\n else:\n self._move(1, 'D')\n elif self.state == 'C':\n if value == 0:\n self._move(-1, 'B')\n else:\n self._move(-1, 'E', 0)\n elif self.state == 'D':\n if value == 0:\n self._move(1, 'A', 1)\n else:\n self._move(1, 'B', 0)\n elif self.state == 'E':\n if value == 0:\n self._move(-1, 'F', 1)\n else:\n self._move(-1, 'C')\n elif self.state == 'F':\n if value == 0:\n self._move(1, 'D', 1)\n else:\n self._move(1, 'A')\n\n\ndef part1():\n machine = Part1TuringMachine('A')\n for i in range(12667664):\n machine.move()\n print( len(machine.ones))\n\n\nif __name__ == '__main__':\n # test1()\n part1()\n","sub_path":"2017/iker/day25.py","file_name":"day25.py","file_ext":"py","file_size_in_byte":7429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"590747043","text":"import rhinoscriptsyntax as rs\r\n\r\n#Example 02\r\n\r\n#Attractors\r\n#Select a single attractor point using the 'GetObject' command\r\nattPt = rs.GetObject(\"Select Attractor\",1)\r\n\r\n#Allow the user to select multiple points using the 'GetObjects' \r\n#command and filtering it to points using the parameter '1'\r\npts = rs.GetObjects(\"Select Pts\",1)\r\n\r\n#Extract out each point in the points variable and place a circle around that point\r\nfor point in pts:\r\n #Vary the size of the circle based on its distance from the attractor point\r\n dist = rs.Distance(attPt,point)\r\n radius = dist/10\r\n #Add a circle to each point using the variables for the point and radius\r\n rs.AddCircle(point, radius)","sub_path":"06 Attractors_B.py","file_name":"06 Attractors_B.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"311020731","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport json\r\nimport os\r\nfrom os.path import join, dirname\r\nimport sys\r\nimport requests\r\nimport subprocess\r\n\r\nfrom django.core.files.storage import FileSystemStorage\r\nfrom django.shortcuts import render, redirect\r\nfrom googletrans import Translator\r\nfrom django.conf import settings\r\nfrom imp import reload\r\n\r\nfrom .models import mediau\r\nfrom .recorder import Recorder\r\nfrom watson_developer_cloud import SpeechToTextV1 as SpeechToText\r\n\r\n\r\ndef home(request):\r\n\r\n return render(request, 'base.html')\r\n\r\ndef convert_file(request):\r\n reload(sys)\r\n sys.setdefaultencoding('utf-8')\r\n hide = request.POST['hide']\r\n print(type(hide))\r\n if int(hide) == 1:\r\n recorder = Recorder(\"speech.wav\")\r\n recorder.record_to_file()\r\n print(\"Transcribing audio....\\n\")\r\n result = transcribe_audio('speech.wav')\r\n else:\r\n if request.method == 'POST' and request.FILES['abc']:\r\n myfile = request.FILES['abc']\r\n filename, file_extension = os.path.splitext(request.FILES['abc'].name)\r\n file_extension = file_extension[1:]\r\n location = settings.MEDIA_ROOT\r\n base_url = settings.MEDIA_URL\r\n print(myfile)\r\n fs = FileSystemStorage(location, base_url)\r\n file_name = fs.save(myfile.name, myfile)\r\n uploaded_file_url = fs.url(file_name)\r\n fileurl = mediau(url=uploaded_file_url, name=filename)\r\n fileurl.save()\r\n\r\n result = transcribe_audio_file(settings.MEDIA_ROOT+\"/\" + filename+\".\" + file_extension, file_extension)\r\n text = \"\"\r\n for x in result:\r\n if (x == \"results\"):\r\n data_in = result[x]\r\n for y in data_in:\r\n new_data = y['alternatives'][0]\r\n for z in new_data:\r\n if (z == \"transcript\"):\r\n text = text + new_data[z]\r\n\r\n print(\"Text: \" + text + \"\\n\")\r\n\r\n translated_text_hi = translate_to_hindi(text)\r\n translated_text_ta = translate_to_tamil(text)\r\n translated_text_te = translate_to_telugu(text)\r\n translated_text_kn = translate_to_kannada(text)\r\n\r\n data = text\r\n if len(data) >= 1:\r\n results = analyze_tone(data)\r\n if results != False:\r\n sentiment = display_results(results)\r\n category_name = sentiment['category_name']\r\n tones = sentiment['tones']\r\n exit\r\n else:\r\n print(\"Something went wrong\")\r\n\r\n context = {\r\n 'text' : text,\r\n 'translated_text_hi':translated_text_hi,\r\n 'translated_text_ta':translated_text_ta,\r\n 'translated_text_te':translated_text_te,\r\n 'translated_text_kn':translated_text_kn,\r\n 'results':results,\r\n 'sentiment':sentiment,\r\n 'tones':tones,\r\n 'category_name':category_name\r\n }\r\n return render(request, 'base.html', context)\r\n\r\n\r\ndef transcribe_audio(path_to_audio_file):\r\n username = \"b6edc1f8-d2c3-4aaf-97d3-d16dd0ad1d61\"\r\n password = \"Ypj577gNJvPi\"\r\n speech_to_text = SpeechToText(username=username,password=password)\r\n\r\n with open(path_to_audio_file, 'rb') as audio_file:\r\n return speech_to_text.recognize(audio_file,content_type='audio/wav')\r\n\r\n\r\ndef transcribe_audio_file(path_to_audio_file, file_extension):\r\n username = \"b6edc1f8-d2c3-4aaf-97d3-d16dd0ad1d61\"\r\n password = \"Ypj577gNJvPi\"\r\n speech_to_text = SpeechToText(username=username,password=password)\r\n\r\n with open(path_to_audio_file, 'rb') as audio_file:\r\n return speech_to_text.recognize(audio_file,content_type='audio/'+file_extension)\r\n\r\n\r\n\r\n\r\n\r\ndef analyze_tone(text):\r\n username = '6de40222-d8a8-44be-8300-b9d5c022a6bb'\r\n password = 'AT7oh5YTq1aO'\r\n watsonUrl = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-18'\r\n headers = {\"content-type\": \"text/plain\"}\r\n data = text\r\n try:\r\n r = requests.post(watsonUrl, auth=(username,password),headers = headers,\r\n data=data)\r\n return r.text\r\n except:\r\n return False\r\n\r\ndef display_results(data):\r\n data = json.loads(str(data))\r\n # for i in data['document_tone']['tone_categories']:\r\n # print(i['category_name'])\r\n # print(\"-\" * len(i['category_name']))\r\n # for j in i['tones']:\r\n # print(j['tone_name'].ljust(20),(str(round(j['score'] * 100,1)) + \"%\").rjust(10))\r\n # print()\r\n # print()\r\n return data['document_tone']['tone_categories'][0]\r\n\r\ndef translate_to_tamil(text):\r\n translator = Translator()\r\n translated_text = translator.translate(text, dest='ta')\r\n # print(translated_text)\r\n return translated_text\r\n\r\ndef translate_to_telugu(text):\r\n translator = Translator()\r\n translated_text = translator.translate(text, dest='te')\r\n print(translated_text)\r\n return translated_text\r\n\r\ndef translate_to_hindi(text):\r\n translator = Translator()\r\n translated_text = translator.translate(text, dest='hi')\r\n print(translated_text)\r\n return translated_text\r\n\r\ndef translate_to_kannada(text):\r\n translator = Translator()\r\n translated_text = translator.translate(text, dest='kn')\r\n print(translated_text)\r\n return translated_text\r\n\r\n","sub_path":"mysite/pollapp/music/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"86615990","text":"from keras.models import Model, load_model\n\nfrom load_model import load_DC_model, load_ER_model\nfrom load_data import load_DAIC_WOZ_training_data, load_DAIC_WOZ_development_data, load_CMU_MOSEI_training_data, load_CMU_MOSEI_development_data\nimport keras\nimport keras.backend as K\n\nimport numpy as np\nimport os\nfrom os import path\n\nimport random\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\n\n\ndef mean_squared_error(y_true, y_pred):\n\terror = K.square(y_pred - y_true)\n\treturn K.mean(K.sum(K.sum(error, axis=2), axis = 1))\n\n\n\n#if(path.exists('training_progress.csv')):\n#\tprogress = np.loadtxt('training_progress.csv', delimiter=',').tolist()\n\n#else:\nprogress = []\n\n#if(path.exists('optimal_weights.h5')):\n#\tmodel = load_model()\n#\tmodel.load_weights('optimal_weights.h5')\n\n#else:\n#\tmodel = load_model()\n#\tmodel.compile(optimizer='adam', loss='mse', metrics = ['mae'])\n\n\nDC_model = load_DC_model()\nDC_model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\n\nER_model = load_ER_model()\nER_model.compile(optimizer = 'adam', loss = mean_squared_error)\n\n\nX_train_DC, Y_train_DC, X_train_gender_DC = load_DAIC_WOZ_training_data()\n\n#X_train_DC = np.array(X_train_DC)\n#X_train_gender_DC = np.array(X_train_gender_DC)\n\nX_dev_DC, Y_dev_DC, X_dev_gender_DC = load_DAIC_WOZ_development_data()\n\n#X_dev_DC = np.array(X_dev_DC)\n#X_dev_gender_DC = np.array(X_dev_gender_DC)\n\n\nX_train_ER, Y_train_ER = load_CMU_MOSEI_training_data()\n#X_train_ER = np.array(X_train_ER)\n\nX_dev_ER, Y_dev_ER = load_CMU_MOSEI_development_data()\n#X_dev_ER = np.array(X_dev_ER)\n\n\n\nmini1_loss = 100000\nmini1_accuracy = -1\nmini2 = 100000\n\nDC_development_curve = []\nER_development_curve = []\n\ntotal_epoch_count = 0\n\nwhile(True):\n\n\tif(path.exists('ER_model_weights.h5')):\n\t\tDC_model.load_weights('ER_model_weights.h5', by_name = True)\n\n\tfor epoch in range(25):\n\t\t\n\t\tDC_model.fit(X_train_DC, Y_train_DC, batch_size = X_train_DC.shape[0])\n\t\tDC_model.save_weights('DC_model_weights.h5')\n\t\tloss_dev_DC = DC_model.evaluate(X_dev_DC, Y_dev_DC)\n\t\t\n\t\tER_model.load_weights('DC_model_weights.h5', by_name = True)\n\t\tloss_dev_ER = ER_model.evaluate(X_dev_ER, Y_dev_ER)\n\t\t\n\t\tDC_development_curve.append([total_epoch_count, loss_dev_DC[0], loss_dev_DC[1]])\n\t\tER_development_curve.append([total_epoch_count, loss_dev_ER])\n\n\t\tif(loss_dev_DC[0] < mini1_loss):\n\t\t\tprint(\"* \"*500)\n\n\t\t\tmini1_loss = loss_dev_DC[0]\n\t\t\tDC_model.save_weights('optonDC_loss_DC_weights.h5')\n\t\t\tER_model.save_weights('optonDC_loss_ER_weights.h5')\n\n\t\t\twith open('DC_loss_current_best.txt', 'w') as f:\n\t\t\t\tf.write(str(loss_dev_DC[0]))\n\t\t\t\tf.write('\\t')\n\t\t\t\tf.write(str(loss_dev_DC[1]))\n\n\n\t\tif(loss_dev_DC[1] > mini1_accuracy):\n\t\t\tprint(\"~ \"*500)\n\n\t\t\tmini1_accuracy = loss_dev_DC[1]\n\t\t\tDC_model.save_weights('optonDC_accuracy_DC_weights.h5')\n\t\t\tER_model.save_weights('optonDC_accuracy_ER_weights.h5')\n\n\t\t\twith open('DC_accuracy_current_best.txt', 'w') as f:\n\t\t\t\tf.write(str(loss_dev_DC[0]))\n\t\t\t\tf.write('\\t')\n\t\t\t\tf.write(str(loss_dev_DC[1]))\n\n\n\t\tif(loss_dev_ER < mini2):\n\t\t\tprint(\"| \"*500)\n\n\t\t\tmini2 = loss_dev_ER\n\n\t\t\tDC_model.save_weights('optonER_DC_weights.h5')\n\t\t\tER_model.save_weights('optonER_ER_weights.h5')\n\n\t\t\twith open('ER_current_best.txt', 'w') as f:\n\t\t\t\tf.write(str(loss_dev_ER))\n\n\t\ttotal_epoch_count = total_epoch_count + 1\n\n\tDC_model.save_weights('DC_model_weights.h5')\n\n\n\n\n\n\n\n\n\n\n\n\tif(path.exists('DC_model_weights.h5')):\n\t\tER_model.load_weights('DC_model_weights.h5', by_name = True)\n\n\n\tfor epoch in range(25):\n\t\t\n\t\tER_model.fit(X_train_ER, Y_train_ER, batch_size = X_train_ER.shape[0])\n\t\tER_model.save_weights('ER_model_weights.h5')\n\t\tloss_dev_ER = ER_model.evaluate(X_dev_ER, Y_dev_ER)\n\n\t\tDC_model.load_weights('ER_model_weights.h5', by_name = True)\n\t\tloss_dev_DC = DC_model.evaluate(X_dev_DC, Y_dev_DC)\n\t\t\n\t\tDC_development_curve.append([total_epoch_count, loss_dev_DC[0], loss_dev_DC[1]])\n\t\tER_development_curve.append([total_epoch_count, loss_dev_ER])\n\n\n\t\tif(loss_dev_DC[0] < mini1_loss):\n\t\t\tprint(\"* \"*500)\n\n\t\t\tmini1_loss = loss_dev_DC[0]\n\t\t\tDC_model.save_weights('optonDC_loss_DC_weights.h5')\n\t\t\tER_model.save_weights('optonDC_loss_ER_weights.h5')\n\n\t\t\twith open('DC_loss_current_best.txt', 'w') as f:\n\t\t\t\tf.write(str(loss_dev_DC[0]))\n\t\t\t\tf.write('\\t')\n\t\t\t\tf.write(str(loss_dev_DC[1]))\n\n\n\t\tif(loss_dev_DC[1] > mini1_accuracy):\n\t\t\tprint(\"~ \"*500)\n\n\t\t\tmini1_accuracy = loss_dev_DC[1]\n\t\t\tDC_model.save_weights('optonDC_accuracy_DC_weights.h5')\n\t\t\tER_model.save_weights('optonDC_accuracy_ER_weights.h5')\n\n\t\t\twith open('DC_accuracy_current_best.txt', 'w') as f:\n\t\t\t\tf.write(str(loss_dev_DC[0]))\n\t\t\t\tf.write('\\t')\n\t\t\t\tf.write(str(loss_dev_DC[1]))\n\n\t\tif(loss_dev_ER < mini2):\n\t\t\tprint(\"| \"*500)\n\n\t\t\tmini2 = loss_dev_ER\n\n\t\t\tDC_model.save_weights('optonER_DC_weights.h5')\n\t\t\tER_model.save_weights('optonER_ER_weights.h5')\n\n\t\t\twith open('ER_current_best.txt', 'w') as f:\n\t\t\t\tf.write(str(loss_dev_ER))\n\n\t\ttotal_epoch_count = total_epoch_count + 1\n\n\tER_model.save_weights('ER_model_weights.h5')\n\n\tnp.save('DC_development_progress.npy', np.array(DC_development_curve))\n\tnp.save('ER_development_progress.npy', np.array(ER_development_curve))","sub_path":"fully_shared/DC_X_ER/archived_models/archived_model_2 (ER_best)/fit_model.py","file_name":"fit_model.py","file_ext":"py","file_size_in_byte":5089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"70047901","text":"from itertools import count\n\ncontador = count()\n\n# start = começo, step = de quanto em quanto ele vai pular\nlista = ['Luiz', 'Maria', 'João', 'Eduardo']\nlista = zip(contador, lista)\n\nprint(list(lista))\n\n\n\n\"\"\"\nfor v in contador:\n print(v)\n if v <= 0:\n break\n\"\"\"\n\n","sub_path":"count/exemplo.py","file_name":"exemplo.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"527284275","text":"from flask import render_template\n\nfrom . import app\nfrom . import models\nfrom . import config\n\n\n@app.route('/reviews')\ndef review_board_dashboard():\n users = sorted(\n models.User.list_by_column_values(config.users, 'username'),\n key=lambda user: -len(user.primary_reviews)\n )\n return render_template(\n 'reviewboard_dashboard.html',\n users=sorted(users, key=lambda x: len(x.primary_reviews), reverse=True),\n review_url_generator=lambda review_id: '%s/r/%s' % (config.url, review_id),\n team_name=config.team_name,\n length=len\n )\n\n\n@app.route('/tickets')\ndef tickets():\n return render_template(\n 'tickets.html',\n team_name=config.team_name,\n users=models.User.list_by_column_values(config.users, 'username')\n )\n\n@app.route('/board')\ndef board():\n return render_template(\n 'board.html',\n users=models.User.list_by_column_values(config.users, 'username')\n )\n\n@app.route('/status')\ndef status():\n return render_template(\n 'status.html',\n review_url_generator=lambda review_id: '%s/r/%s' % (config.url, review_id),\n users=models.User.list_by_column_values(config.users, 'username'),\n team_name=config.team_name,\n )\n","sub_path":"xp_board/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"409730905","text":"import abc\n\nfrom ..abc.lookup import MappingLookup\nimport aiomysql.cursors\nimport pymysql.cursors\nimport pymysql\n\n\n\n\nclass MySQLLookup(MappingLookup):\n\n\t'''\nThe lookup that is linked with a MySQL.\nIt provides a mapping (dictionary-like) interface to pipelines.\nIt feeds lookup data from MongoDB using a query.\nIt also has a simple cache to reduce a number of datbase hits.\n\nExample:\n\nclass ProjectLookup(bspump.mysql.MySQLLookup):\n\n\tasync def count(self, database):\n\t\treturn await database['projects'].count_documents({})\n\n\tdef find_one(self, database, key):\n\t\treturn database['projects'].find_one({'_id':key})\n\n\t'''\n\n\tConfigDefaults = {\n\t\t'table': '', # Specify a database if you want to overload the connection setting\n\t\t'key':'' # Specify key name used for search\n\t}\n\n\tdef __init__(self, app, lookup_id, mysql_connection, config=None):\n\t\tsuper().__init__(app, lookup_id=lookup_id, config=config)\n\t\tself.Connection = mysql_connection\n\n\t\tself.Table = self.Config['table']\n\t\tself.Key = self.Config['key']\n\n\t\tself.Count = -1\n\t\tself.Cache = {}\n\n\t\tconn_sync = pymysql.connect(host=mysql_connection._host,\n\t\t\t\t\t user=mysql_connection._user,\n\t\t\t\t\t passwd=mysql_connection._password,\n\t\t\t\t\t db=mysql_connection._db)\n\t\tself.CursorSync = pymysql.cursors.DictCursor(conn_sync)\n\t\tself.CursorAsync = None\n\n\t\tmetrics_service = app.get_service('asab.MetricsService')\n\t\tself.CacheCounter = metrics_service.create_counter(\"mysql.lookup\", tags={}, init_values={'hit': 0, 'miss': 0})\n\n\n\tdef _find_one(self, key):\n\t\tquery = \"SELECT * FROM {} WHERE {}='{}'\".format(self.Table, self.Key, key)\n\t\tself.CursorSync.execute(query)\n\t\tresult = self.CursorSync.fetchone()\n\t\treturn result\n\n\t\n\tasync def _count(self):\n\n\t\tquery = \"\"\"SELECT COUNT(*) as \"Number_of_Rows\" FROM {};\"\"\".format(self.Table)\n\t\tawait self.CursorAsync.execute(query)\n\t\tcount = await self.CursorAsync.fetchone()\n\t\treturn count['Number_of_Rows']\n\n\n\tasync def load(self):\n\t\tawait self.Connection.ConnectionEvent.wait()\n\t\tconn_async = await self.Connection.acquire()\n\t\tself.CursorAsync = await conn_async.cursor(aiomysql.cursors.DictCursor)\n\t\tself.Count = await self._count()\n\n\n\tdef __len__(self):\n\t\treturn self.Count\n\n\n\tdef __getitem__(self, key):\n\t\ttry:\n\t\t\tvalue = self.Cache[key]\n\t\t\tself.CacheCounter.add('hit', 1)\n\t\t\treturn value\n\t\texcept KeyError:\n\t\t\tv = self._find_one(key)\n\t\t\tself.Cache[key] = v\n\t\t\tself.CacheCounter.add('miss', 1)\n\t\t\treturn v\n\n\n\tdef __iter__(self):\n\t\tquery = query = \"SELECT * FROM {}\".format(self.Table)\n\t\tself.CursorSync.execute(query)\n\t\tresult = self.CursorSync.fetchall()\n\t\tself.Iterator = result.__iter__()\n\t\treturn self\n\n\n\tdef __next__(self):\n\t\telement = next(self.Iterator)\n\t\tkey = element.get(self.Key)\n\t\tif key is not None:\n\t\t\tself.Cache[key] = element\n\t\treturn key\n","sub_path":"bspump/mysql/lookup.py","file_name":"lookup.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"283786200","text":"class Solution:\n def LinearScan(self, nums, target):\n # 先至左掃描\n for l in range(0, len(nums)):\n if nums[l]== target:\n left_index = l\n break\n # 迴圈與 else 搭配\n else:\n return [-1, -1]\n # 再至右掃描\n for r in range(len(nums)-1, -1, -1): \n if nums[r]== target:\n right_index = r\n break\n \n return [left_index, right_index]\n \n def BinarySearch(self, nums, target):\n def search(n):\n lo = 0\n hi = len(nums)\n while lo < hi:\n mid = (lo + hi)//2\n # 若 mid >= target, hi向左移動\n # 反之 lo 向右移動 \n if nums[mid] >= n:\n hi = mid\n else:\n lo = mid + 1\n return lo\n lo = search(target)\n # target+1 為了跳過 left index , 再-1因 target 有+1\n return [lo, search(target+1)-1] if target in nums[lo:lo+1] else [-1, -1]\n \n \nif __name__ == \"__main__\":\n s = Solution()\n print(s.LinearScan(nums = [5, 7, 7, 8, 8, 10], target = 8))\n print(s.BinarySearch(nums = [5, 7, 7, 8, 8, 10], target = 8))\n ","sub_path":"034-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find-First-and-Last-Position-of-Element-in-Sorted-Array.py","file_name":"Find-First-and-Last-Position-of-Element-in-Sorted-Array.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"50981630","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef step_gradient(a_current, b_current, eta, data):\r\n a_gradient = 0\r\n b_gradient = 0\r\n n = float(len(data))\r\n for sample in data:\r\n x = sample[0]\r\n y = sample[1]\r\n a_gradient += -(2/n) * (y - ((b_current * x) + a_current))\r\n b_gradient += -(2/n) * x * (y - ((b_current * x) + a_current))\r\n new_a = a_current - (eta * a_gradient)\r\n new_b = b_current - (eta * b_gradient)\r\n return new_a, new_b\r\n\r\n\r\ndef change_coefficients(starting_a, starting_b, epochs):\r\n a = starting_a\r\n b = starting_b\r\n for _ in range(epochs):\r\n a, b = step_gradient(a, b, 0.0001, np.array(data))\r\n return a, b\r\n\r\n\r\ndef measure_error(a, b, data):\r\n error = 0\r\n for sample in data:\r\n x = sample[0]\r\n y = sample[1]\r\n error += (y - (a * x + b)) ** 2\r\n return error / float(len(data))\r\n\r\n\r\nif __name__ == '__main__':\r\n data = [[1, 2], [3, 4], [6, 7]]\r\n initial_a = 0\r\n initial_b = 0\r\n epochs = 1000\r\n print('Before running the gradient descent algorithm...\\na: ',\\\r\n initial_a, ', b: ', initial_b, ', error: ',\\\r\n measure_error(initial_a, initial_b, data))\r\n a, b = change_coefficients(initial_a, initial_b, epochs)\r\n print('After running the gradient descent algorithm...\\na: ',\\\r\n a, ', b: ', b, ', error: ', measure_error(a, b, data))\r\n","sub_path":"gradient-descent/gradient-descent.py","file_name":"gradient-descent.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"199914723","text":"from keras.models import Model\nfrom keras.layers import Activation, Dense, Dropout, Flatten, Input\nfrom keras.layers import concatenate\nfrom keras.layers import Conv1D, MaxPooling1D\nfrom time import perf_counter\nfrom loadData import *\nfrom plots import *\nfrom analysis import *\nimport sys\n\n\nclass inception(loadData, plots, analysis):\n\t\"\"\"\n\tPython class for the 1D inception model\n\t\"\"\"\n\n\tdef __init__(self, seed=7775):\n\t\tpass\n\n\n\tdef _compile(self, classes=2, act='softmax', optimizer='adadelta', loss='binary_crossentropy', metrics=['binarcy_accuracy']):\n\t\tself.model_.append(Dense(classes)(self.model_[-1]))\n\t\tself.model_.append(Activation(act, name=\"prob_output\")(self.model_[-1]))\n\t\tself.model_ = Model(inputs=self.__input, outputs=[self.model_[-1]])\n\t\tself.model_.compile(loss=loss, optimizer=optimizer, metrics=metrics)\n\n\n\tdef _convl1D(self, filters=1, kernel_size=1, input_shape=(16,16,64), padding='same'):\n\n\t\ttry:\n\t\t\tself.model_\n\t\t\tself.model_.append(Conv1D(filters=filters, kernel_size=kernel_size, input_shape=input_shape, padding=padding)(self.model_[-1]))\n\t\texcept:\n\t\t\tself.model_ = []\n\t\t\tself.__inputShape = self.trainX_.shape[1:]\n\t\t\tself.__input = Input(shape=self.__inputShape)\n\t\t\t\n\t\t\tself.model_.append(Conv1D(filters=filters, kernel_size=kernel_size, input_shape=input_shape, padding=padding)(self.__input))\n\n\tdef _dense(self, z, act='relu', drop=0.5, ntimes=1):\n\t\tfor _ in range(ntimes):\n\t\t\tself.model_.append(Dense(z)(self.model_[-1]))\n\t\t\tif act != None: self.model_.append(Activation(act)(self.model_[-1]))\n\t\t\tif drop != None: self.model_.append(Dropout(drop)(self.model_[-1]))\n\n\tdef _flatten(self):\n\t\tself.model_.append(Flatten()(self.model_[-1]))\n\n\n\tdef _inception(self, convl=[3, 5], pool=[3], act='relu'):\n\n\t\t# ===========================================\n\t\t#\tList for holding the blocks\n\t\t# ===========================================\n\t\tmodel = []\n\t\tpadding = 'same'\n\t\tpool_stride = 1\n\n\t\ttry:\n\t\t\t# ===========================================\n\t\t\t#\tIf this is not the first layer in the\n\t\t\t#\tnetwork, proceed. Otherwise, run the\n\t\t\t#\texception block\n\t\t\t# ===========================================\n\t\t\tself.model_\n\t\t\tself.__inputShape\n\n\t\t\tconvl_1x1 = Conv1D(32, kernel_size=1)(self.model_[-1])\n\t\t\tmodel.append(convl_1x1)\n\n\t\t\tfor c in convl:\n\t\t\t\tconvl_cx1 = Conv1D(64, kernel_size=c, strides=1, padding=padding, activation=act)(convl_1x1)\n\t\t\t\tmodel.append(convl_cx1)\n\n\t\t\tfor p in pool:\n\t\t\t\tpool_px1 = MaxPooling1D(pool_size=p, strides=pool_stride, padding=padding)(self.model_[-1])\n\t\t\t\tpconvl_1x1 = Conv1D(64, kernel_size=1, padding=padding, activation=act)(pool_px1)\n\t\t\t\tmodel.append(pconvl_1x1)\n\n\n\t\texcept:\n\n\t\t\tself.model_ = []\n\t\t\tself.__inputShape = self.trainX_.shape[1:]\n\t\t\tself.__input = Input(shape=self.__inputShape)\n\t\t\t\n\t\t\tconvl_1x1 = Conv1D(32, kernel_size=1, input_shape=self.__inputShape)(self.__input)\n\t\t\tmodel.append(convl_1x1)\n\n\t\t\tfor c in convl:\n\t\t\t\tconvl_cx1 = Conv1D(64, kernel_size=c, strides=1, padding=padding, activation=act)(convl_1x1)\n\t\t\t\tmodel.append(convl_cx1)\n\n\t\t\tfor p in pool:\n\t\t\t\tpool_px1 = MaxPooling1D(input_shape=self.__inputShape, pool_size=p, strides=pool_stride, padding=padding)(self.__input)\n\t\t\t\tpconvl_1x1 = Conv1D(64, kernel_size=1, padding=padding, activation=act)(pool_px1)\n\t\t\t\tmodel.append(pconvl_1x1)\n\n\n\t\tself.model_.append(concatenate(model))\n\n\n\tdef _train(self, epochs, batch_size, timeit=True, save=False, ofile=\"wtf_weights\", verbose=1):\n\n\t\tif timeit:\n\t\t\tstart = perf_counter()\n\n\t\t# =============================================\n\t\t#\tTest if there is a validation set to\n\t\t#\ttest the accuracy. If not, use the\n\t\t#\ttraining set.\n\t\t# =============================================\n\t\ttry:\n\t\t\tself.validX_\n\t\t\tself.model_.fit(self.trainX_, self.trainY_, batch_size=batch_size, epochs=epochs, verbose=verbose, validation_data=(self.validX_, self.validY_))\n\t\texcept:\n\t\t\tself.model_.fit(self.trainX_, self.trainY_, batch_size=batch_size, epochs=epochs, verbose=verbose, validation_data=(self.trainX_, self.trainY_))\n\n\t\t# =============================================\n\t\t#\tCompute the training time (minutes)\n\t\t# =============================================\n\t\tif timeit:\n\t\t\ttime2run = perf_counter() - start\n\t\t\tprint(\"It took {:.1f} minutes to run\".format(time2run/60.))\n\n\t\t# =============================================\n\t\t#\tIf save, output the weights to \"ofile\"\n\t\t# =============================================\n\t\tif save:\n\t\t\tself.model_.save_weights(ofile)\n\n\n\tdef _test(self, prob=0.5):\n\t\t\"\"\"\n\t\tFunction for computing the class probabilities.\n\n\t\tTo call:\n\t\t\t_test(prob)\n\n\t\tParameters:\n\t\t\tprob\tprobability threshold to declare a source \"complex\"\n\n\t\tPostcondition:\n\t\t\tThe test probabilities have been stored in the array \"testProb_\"\n\t\t\tThe predicted classes have been stored in the array \"testPred_\"\n\t\t\"\"\"\n\t\ttry:\n\t\t\tself.testX_\n\t\t\tself.testProb_ = self.model_.predict(self.testX_)[:,1]\n\t\t\tself.testPred_ = np.where(self.testProb_ > prob, 1, 0)\n\t\texcept:\n\t\t\tprint(\"Please load a test dataset.\")\n\t\t\tsys.exit(1)\n\n\n\nif __name__ == '__main__':\n\tcnn = inception()\n\tcnn._loadTrain(\"../data/train/X_data.npy\", \"../data/train/label.npy\")\n\tcnn._loadValid(\"../data/valid/X_data.npy\", \"../data/valid/label.npy\")\n\tcnn._loadTest(\"../data/test/X_data.npy\", \"../data/test/label.npy\")\n\n\tcnn._inception(convl=[3,5], pool=[3])\n\tcnn._convl1D()\n\tcnn._flatten()\n\tcnn._dense(512, 'relu', 0.5, 1)\n\tcnn._compile(2, 'softmax', 'adadelta', 'binary_crossentropy', ['binary_accuracy'])\n\t#cnn._plotModel(to_file='graph.png')\n\n\tcnn._train(10, 5, save=False)\n\tcnn._test(prob=0.8)\n\tprint(confusion_matrix(cnn.testLabel_, cnn.testPred_))\n","sub_path":"python/inception.py","file_name":"inception.py","file_ext":"py","file_size_in_byte":5568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"423785254","text":"import math\nimport os\nimport json\nfrom datetime import datetime\nfrom flask import Flask, render_template, request, session, redirect, flash\nfrom flask_sqlalchemy import SQLAlchemy\n# from werkzeug.utils import secure_filename\nfrom flask_mail import Mail\nimport pymysql\n\npymysql.install_as_MySQLdb()\n\nwith open('config.json', 'r') as c:\n params = json.load(c)[\"params\"]\n\nlocal_server = True\napp = Flask(__name__)\napp.secret_key = 'super-secret-key'\napp.config['UPLOAD_FOLDER'] = params['upload_location']\napp.config['BOOK_UPLOAD_FOLDER'] = params['book_upload_location']\n# app.config.update(\n# MAIL_SERVER='smtp.gmail.com',\n# MAIL_PORT=465,\n# MAIL_USE_SSL=True,\n# MAIL_USERNAME=params['gmail-user'],\n# MAIL_PASSWORD=params['gmail-password']\n# )\n\napp.config['MAIL_SERVER']='smtp.mailtrap.io'\napp.config['MAIL_PORT'] = 2525\napp.config['MAIL_USERNAME'] = '0b712f2fabdc86'\napp.config['MAIL_PASSWORD'] = '3f19c452ca373f'\napp.config['MAIL_USE_TLS'] = True\napp.config['MAIL_USE_SSL'] = False\nmail = Mail(app)\nif local_server:\n app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']\nelse:\n app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']\n\ndb = SQLAlchemy(app)\n\n\nclass Contacts(db.Model):\n sno = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n email = db.Column(db.String(20), nullable=False)\n phone_no = db.Column(db.String(12), nullable=False)\n msg = db.Column(db.String(120), nullable=False)\n date = db.Column(db.String(12), nullable=True)\n\n\nclass Posts(db.Model):\n sno = db.Column(db.Integer, primary_key=True)\n tittle = db.Column(db.Text, nullable=False)\n slug = db.Column(db.String(25), nullable=False)\n content = db.Column(db.Text, nullable=False)\n tagline = db.Column(db.Text, nullable=False)\n date = db.Column(db.String(12), nullable=True)\n img_file = db.Column(db.String(100), nullable=True)\n\n\nclass Book(db.Model):\n book_id = db.Column(db.Integer, primary_key=True)\n book_name = db.Column(db.Text, nullable=False)\n book_cat = db.Column(db.Text, nullable=False)\n book_author = db.Column(db.Text, nullable=False)\n book_publication = db.Column(db.Text, nullable=False)\n book_desc = db.Column(db.Text, nullable=False)\n price = db.Column(db.Float, nullable=False)\n book_img = db.Column(db.String(100), nullable=True)\n amazon_link = db.Column(db.Text, nullable=False)\n flipkart_link = db.Column(db.Text, nullable=False)\n thriftbooks_link = db.Column(db.Text, nullable=False)\n\n\n\n@app.route('/')\ndef home():\n posts = Posts.query.filter_by().all()\n last = math.ceil(len(posts) / int(params['no_of_posts']))\n # [0:params['no_of_posts']]\n page = request.args.get('page')\n if not str(page).isnumeric():\n page = 1\n page = int(page)\n posts = posts[(page - 1) * int(params['no_of_posts']): (page - 1) * int(params['no_of_posts']) + int(\n params['no_of_posts'])]\n # Pagination Logic :-\n # First :-\n if page == 1:\n prev = \"#\"\n next = \"/?page=\" + str(page + 1)\n elif page == last:\n prev = \"/?page=\" + str(page - 1)\n next = \"#\"\n else:\n prev = \"/?page=\" + str(page - 1)\n next = \"/?page=\" + str(page + 1)\n\n return render_template('index.html', params=params, posts=posts, prev=prev, next=next)\n\n\n@app.route(\"/post/\", methods=['GET'])\ndef post_route(post_slug):\n post = Posts.query.filter_by(slug=post_slug).first()\n return render_template('post.html', params=params, post=post)\n\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html', params=params)\n\n@app.route(\"/bookshelf\", methods=['GET'])\ndef bookshelf():\n books = Book.query.filter_by().all()\n return render_template('bookshelf.html', params=params, books=books)\n\n\n@app.route(\"/dashboard\", methods=['GET', 'POST'])\ndef dashboard():\n if 'user' in session and session['user'] == params['admin_user']:\n posts = Posts.query.all()\n return render_template('dashboard.html', params=params, posts=posts)\n\n if request.method == 'POST':\n username = request.form.get('uname')\n userpass = request.form.get('pass')\n if username == params['admin_user'] and userpass == params['admin_password']:\n # set the session variable\n session['user'] = username\n posts = Posts.query.all()\n return render_template('dashboard.html', params=params, posts=posts)\n else:\n flash('Incorrect username or password', 'danger')\n return render_template('login.html', params=params)\n\n\n@app.route(\"/bookDashboard\", methods=['GET', 'POST'])\ndef bookDashboard():\n if 'user' in session and session['user'] == params['admin_user']:\n books = Book.query.all()\n return render_template('bookDashboard.html', params=params, books=books)\n\n if request.method == 'POST':\n username = request.form.get('uname')\n userpass = request.form.get('pass')\n if username == params['admin_user'] and userpass == params['admin_password']:\n # set the session variable\n session['user'] = username\n books = Book.query.all()\n return render_template('bookDashboard.html', params=params, books=books)\n else:\n flash('Incorrect username or password', 'danger')\n return render_template('login.html', params=params)\n\n\n@app.route(\"/edit/\", methods=['GET', 'POST'])\ndef edit(sno):\n if 'user' in session and session['user'] == params['admin_user']:\n if request.method == 'POST':\n f = request.files['file1']\n if f.filename == '':\n pass\n else:\n # secure_filename\n f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))\n box_tittle = request.form.get('tittle')\n tline = request.form.get('tline')\n slug = request.form.get('slug')\n content = request.form.get('content')\n img_file = request.form.get('img_file')\n date = datetime.now()\n if sno == '0':\n if box_tittle == '' and tline == '' and slug == '' and content == '':\n flash('Below fields are mandatory to create a post!', 'danger')\n else:\n post = Posts(tittle=box_tittle, slug=slug, content=content,\n tagline=tline, img_file=img_file, date=date)\n db.session.add(post)\n db.session.commit()\n flash('Post has been added successfully', 'success')\n else:\n post = Posts.query.filter_by(sno=sno).first()\n post.tittle = box_tittle\n post.slug = slug\n post.content = content\n post.tagline = tline\n post.img_file = img_file\n post.date = date\n db.session.commit()\n flash('Post has been edited successfully', 'success')\n\n return redirect('/edit/' + sno)\n post = Posts.query.filter_by(sno=sno).first()\n return render_template('edit.html', params=params, post=post, sno=sno)\n\n\n@app.route(\"/bookEdit/\", methods=['GET', 'POST'])\ndef bookEdit(book_id):\n if 'user' in session and session['user'] == params['admin_user']:\n if request.method == 'POST':\n f = request.files['file2']\n if f.filename == '':\n pass\n else:\n # secure_filename\n f.save(os.path.join(app.config['BOOK_UPLOAD_FOLDER'], f.filename))\n booksName = request.form.get('name')\n booksCat = request.form.get('category')\n booksAuthor = request.form.get('author')\n booksPublication = request.form.get('publication')\n booksDesc = request.form.get('desc')\n booksPrice = request.form.get('bookprice')\n booksImg = request.form.get('bookImage')\n amazonLink = request.form.get('amazonLink')\n flipkartLink = request.form.get('flipkartLink')\n thriftbooksLink = request.form.get('thriftbooksLink')\n # date = datetime.now()\n if book_id == 0:\n if booksName == '' and booksCat == '' and booksAuthor == '' and booksDesc == '' and booksPrice == '':\n flash('Below fields are mandatory to add a book!', 'danger')\n else:\n book = Book(book_name=booksName, book_cat=booksCat, book_author=booksAuthor,\n book_publication=booksPublication, book_desc=booksDesc, price=booksPrice,\n book_img=booksImg, amazon_link=amazonLink, flipkart_link=flipkartLink, thriftbooks_link=thriftbooksLink)\n db.session.add(book)\n db.session.commit()\n flash('Book has been added successfully', 'success')\n else:\n book = Book.query.filter_by(book_id=book_id).first()\n book.book_name = booksName\n book.book_cat = booksCat\n book.book_author = booksAuthor\n book.book_publication = booksPublication\n book.book_desc = booksDesc\n book.price = booksPrice\n book.book_img = booksImg\n book.amazon_link = amazonLink\n book.flipkart_link = flipkartLink\n book.thriftbooks_link = thriftbooksLink\n db.session.commit()\n flash('Book has been edited successfully', 'success')\n\n return redirect('/bookEdit/' + str(book_id))\n book = Book.query.filter_by(book_id=book_id).first()\n return render_template('bookEdit.html', params=params, book=book, book_id=book_id)\n\n@app.route(\"/logout\")\ndef logout():\n session.pop('user')\n return redirect('/dashboard')\n\n\n@app.route(\"/delete/\", methods=['GET', 'POST'])\ndef delete(sno):\n if 'user' in session and session['user'] == params['admin_user']:\n post = Posts.query.filter_by(sno=sno).first()\n db.session.delete(post)\n db.session.commit()\n flash('Post has been deleted successfully', 'success')\n return redirect('/dashboard')\n\n@app.route(\"/bookDelete/\", methods=['GET', 'POST'])\ndef bookDelete(book_id):\n if 'user' in session and session['user'] == params['admin_user']:\n book = Book.query.filter_by(book_id=book_id).first()\n db.session.delete(book)\n db.session.commit()\n flash('Book has been deleted successfully', 'success')\n return redirect('/bookDashboard')\n\n\n@app.route(\"/contact\", methods=['GET', 'POST'])\ndef contact():\n if request.method == 'POST':\n '''Add entry to the database'''\n name = request.form.get('name')\n email = request.form.get('email')\n phone = request.form.get('phone')\n message = request.form.get('message')\n\n entry = Contacts(name=name, email=email, phone_no=phone,\n msg=message, date=datetime.now())\n db.session.add(entry)\n db.session.commit()\n mail.send_message('New message from ' + name,\n sender=email,\n recipients=[params['gmail-user']],\n body=message + \"\\n\" + phone\n )\n flash('Thank You for contacting us', 'success')\n return render_template('contact.html', params=params)\n\n@app.route(\"/bookshelf\", methods=['GET', 'POST'])\ndef searchBook():\n words1 = request.form.get('search')\n bookSearch1 = Book.query.filter_by().all()\n # print(f\" array {bookSearch1}\")\n searchResult = []\n for book1 in bookSearch1:\n if book1.book_name.lower() == words1.lower() or book1.book_cat.lower() == words1.lower():\n # print(f\"book- {book1}\")\n searchResult.append(book1)\n if len(searchResult) == 0:\n wordArray = words1.split(\" \")\n for book2 in bookSearch1:\n for word in wordArray:\n if book2.book_name.lower() == word.lower() or book2.book_cat.lower() == word.lower():\n searchResult.append(book2)\n return render_template('bookshelf.html', params=params, books=searchResult)\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24616751","text":"import RPi.GPIO as GPIO\n\ndef forward(Motor1P,Motor1N,Motor2P,Motor2N):\n\tGPIO.output(Motor1P,GPIO.HIGH)\n\tGPIO.output(Motor1N,GPIO.LOW)\n\tGPIO.output(Motor2P,GPIO.HIGH)\n\tGPIO.output(Motor2N,GPIO.LOW)\n\ndef reverse(Motor1P,Motor1N,Motor2P,Motor2N):\n\tGPIO.output(Motor1N,GPIO.HIGH)\n\tGPIO.output(Motor1P,GPIO.LOW)\n\tGPIO.output(Motor2N,GPIO.HIGH)\n\tGPIO.output(Motor2P,GPIO.LOW)\n\ndef right(Motor1P, Motor1N, Motor2P, Motor2N):\n GPIO.output(Motor1P,GPIO.HIGH)\n GPIO.output(Motor1N,GPIO.LOW)\n GPIO.output(Motor2P,GPIO.LOW)\n GPIO.output(Motor2N,GPIO.HIGH)\n \ndef left(Motor1P, Motor1N, Motor2P, Motor2N):\n GPIO.output(Motor2P,GPIO.HIGH)\n GPIO.output(Motor2N,GPIO.LOW)\n GPIO.output(Motor1P,GPIO.LOW)\n GPIO.output(Motor1N,GPIO.HIGH) \n\ndef activate_pins(Motor1,Motor2,Motor1P,Motor1N,Motor2P,Motor2N):\n\tGPIO.setup(Motor1,GPIO.OUT)\n\tGPIO.setup(Motor2,GPIO.OUT)\n\tGPIO.setup(Motor1P,GPIO.OUT)\t\n\tGPIO.setup(Motor2P,GPIO.OUT)\n\tGPIO.setup(Motor1N,GPIO.OUT)\n\tGPIO.setup(Motor2N,GPIO.OUT)\n\ndef start_pwm(base_speed,Motor1,Motor2):\n\tGPIO.output(Motor1,GPIO.HIGH)\n\tGPIO.output(Motor2,GPIO.HIGH)\n\tpwm1=GPIO.PWM(Motor1,100)\n\tpwm2=GPIO.PWM(Motor2,100)\n\tpwm1.start(base_speed+5)\n\tpwm2.start(base_speed-5)\n\treturn\t[pwm1,pwm2]\n\ndef set_motor_speed(pwm1,pwm2,duty_cycle1, duty_cycle2):\n pwm1.ChangeDutyCycle(duty_cycle1)\n pwm2.ChangeDutyCycle(duty_cycle2)\n\ndef stop(Motor1P,Motor1N,Motor2P,Motor2N):\n GPIO.output(Motor1P,GPIO.HIGH)\n GPIO.output(Motor1N,GPIO.HIGH)\n GPIO.output(Motor2P, GPIO.HIGH)\n GPIO.output(Motor2N, GPIO.HIGH)\n\ndef clean(pwm1,pwm2):\n pwm1.stop()\n pwm2.stop()\n GPIO.cleanup()\n","sub_path":"AUV1_rasp/motor_movement.py","file_name":"motor_movement.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16767872","text":"import trio\nimport asyncio\n\nfrom botworx.run import *\nfrom botworx.run import _I\nfrom botworx.run.policy import Policy\n\nclass Agent(Policy):\n def __init__(self):\n super().__init__()\n self.posts = []\n\n def run(self):\n trio.run(self.main)\n\n async def main(self):\n print(\"I'm an Agent\")\n\n async def process_posts(self):\n print('process')\n for post in self.posts:\n for rule in self.__class__.rules:\n print(rule)\n task = await curio.spawn(rule.action(self))\n await task.join()\n\n async def post(self, msg):\n self.posts.append(msg)\n await self.process_posts()\n\n async def call(self, msg):\n loop = self.loop\n future = loop.create_future()\n msg.future = future\n self.posts.append(msg)\n await self.process_posts()\n await future\n\n_like = term_('like')\n_Cheese = term_('Cheese')\n\nclass MyAgent(Agent):\n def __init__(self):\n super().__init__()\n print(self.__class__.rules)\n\n async def main(self):\n await self.post(assert_(Believe, _I, _like, _Cheese))\n\n @_(onAssert_(_I, _like, _Cheese))\n async def howdy(self):\n print('Howdy Folks!')\n\nagent = MyAgent()\nagent.run()\n","sub_path":"experiments/exp_agent_trio.py","file_name":"exp_agent_trio.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"345167914","text":"# -*- coding: utf-8 -*-\n# @File : Test1_3.py\n# @Author: lizhen\n# @Date : 2019/1/30\n# @Desc :\n\nimport numpy as np\nfrom keras.datasets import mnist\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense,Activation\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\n\nfrom keras.layers.core import Dropout\nimport pydot\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom keras.utils import plot_model\n\n# 设置超参数\nNB_EPOCH=20\n\nBATCH_SIZE=128\nVERBOSE=1\nNB_CLASSES =10\nOPTIMIZER=SGD() # 优化器\nN_HIDDEN=128\nVALIDATION_SPLIT=0.2 # 训练数据集合中用于验证集的数据比例\nDROPOUT=0.3 # 设置dropout 的失活率\n\n# 数据准备\n(X_train,Y_train),(X_test,Y_test) = mnist.load_data() #[NHWC]\ndata_SHAPE=28*28\ntrain_num=60000\ntest_num=10000\n# change to [N,WHC]\nX_train =X_train.reshape(train_num,data_SHAPE).astype('float32')\nX_test = X_test.reshape(test_num,data_SHAPE).astype('float32')\n# 数据归一化\nX_train /=255\nX_test /=255\n#\nprint(X_train.shape[0],'train samples') #get N\nprint(X_test.shape[0],'test sample')\n\n# change label\nY_train = np_utils.to_categorical(Y_train,NB_CLASSES)\nY_test = np_utils.to_categorical(Y_test,NB_CLASSES)\n\nmodel = Sequential()\nmodel.add(Dense(NB_CLASSES,input_shape=(data_SHAPE,)))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(DROPOUT))\nmodel.add(Dense(N_HIDDEN))\nmodel.add(Activation('relu'))\nmodel.add(Dense(NB_CLASSES))\nmodel.add(Activation('softmax')) ###\n\nmodel.summary() # 打印出模型概况\n# plot_model(model,to_file='test1_3.png',show_layer_names=True) # 绘制模型\n\nmodel.compile(loss='categorical_crossentropy',optimizer=OPTIMIZER,metrics=['accuracy'])\n\nhis = model.fit(X_train,Y_train,\n batch_size=BATCH_SIZE,\n epochs=NB_EPOCH,\n verbose=VERBOSE,\n validation_split=VALIDATION_SPLIT)\n\nscore = model.evaluate(X_test,Y_test,verbose=VERBOSE)\nprint('Test score:',score[0])\nprint('Test accuracy',score[1])\n\nprint(his.history) # val_loss, val_acc,loss,acc\n###\nresult=his.history\nval_loss = result[\"val_loss\"]\nval_acc = result[\"val_acc\"]\nloss = result[\"loss\"]\nacc = result[\"acc\"]\n\nplt.title('Result Analysis')\nplt.plot(val_loss, color='red', label='val_loss')\nplt.plot(val_acc, color='blue', label='val_acc')\nplt.plot(loss, color='green', label='loss')\nplt.plot(acc, color='black', label='acc')\n\nplt.legend()\nplt.xlabel('opechs')\nplt.ylabel('values')\n\n# plt.show()\n# fig =plt.gcf() # get current figure\n# fig.savefig('data_result.png',dpi=100)\n# or\nplt.savefig(\"data_result.png\")\nplt.show()","sub_path":"Test1_35.py","file_name":"Test1_35.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"175725181","text":"import scrapy\r\n\r\nfrom tutorial.items import TutorialItem\r\nfrom scrapy.crawler import CrawlerProcess\r\n\r\nclass DmozSpider(scrapy.Spider):\r\n name = \"googlepic\"\r\n\r\n # pass parameter\r\n def __init__(self, query=None, *args, **kwargs):\r\n super(DmozSpider, self).__init__(*args, **kwargs)\r\n self.query = query\r\n self.start_urls = [\"http://cn.bing.com/images/async?q=%s&first=0\" % query]\r\n\r\n def parse(self, response):\r\n item = TutorialItem()\r\n item['image_urls'] = response.xpath('//a[contains(@class, \"iusc\")]/@m').re(r'\"murl\":\"(.+?)\"')\r\n item['name'] = self.query\r\n yield item","sub_path":"spider/tutorial/spiders/dmoz_spider.py","file_name":"dmoz_spider.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380671487","text":"# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018-2019 Fetch.AI Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ------------------------------------------------------------------------------\n\n\"\"\"This package contains a scaffold of a handler.\"\"\"\n\nimport pprint\nimport time\nfrom typing import Dict, Optional, Tuple, cast\n\nfrom aea.configurations.base import ProtocolId, PublicId\nfrom aea.helpers.dialogue.base import DialogueLabel\nfrom aea.helpers.search.models import Query\nfrom aea.protocols.base import Message\nfrom aea.protocols.default.message import DefaultMessage\nfrom aea.protocols.signing.message import SigningMessage\nfrom aea.skills.base import Handler\n\nfrom packages.fetchai.protocols.fipa.message import FipaMessage\nfrom packages.fetchai.protocols.oef_search.message import OefSearchMessage\nfrom packages.fetchai.skills.tac_negotiation.dialogues import Dialogue, Dialogues\nfrom packages.fetchai.skills.tac_negotiation.search import Search\nfrom packages.fetchai.skills.tac_negotiation.strategy import Strategy\nfrom packages.fetchai.skills.tac_negotiation.transactions import Transactions\n\n\nclass FIPANegotiationHandler(Handler):\n \"\"\"This class implements the fipa negotiation handler.\"\"\"\n\n SUPPORTED_PROTOCOL = FipaMessage.protocol_id # type: Optional[ProtocolId]\n\n def setup(self) -> None:\n \"\"\"\n Implement the setup.\n\n :return: None\n \"\"\"\n pass\n\n def handle(self, message: Message) -> None:\n \"\"\"\n Dispatch message to relevant handler and respond.\n\n :param message: the message\n :return: None\n \"\"\"\n fipa_msg = cast(FipaMessage, message)\n\n # recover dialogue\n dialogues = cast(Dialogues, self.context.dialogues)\n fipa_dialogue = cast(Dialogue, dialogues.update(fipa_msg))\n if fipa_dialogue is None:\n self._handle_unidentified_dialogue(fipa_msg)\n return\n\n self.context.logger.debug(\n \"[{}]: Handling FipaMessage of performative={}\".format(\n self.context.agent_name, fipa_msg.performative\n )\n )\n if fipa_msg.performative == FipaMessage.Performative.CFP:\n self._on_cfp(fipa_msg, fipa_dialogue)\n elif fipa_msg.performative == FipaMessage.Performative.PROPOSE:\n self._on_propose(fipa_msg, fipa_dialogue)\n elif fipa_msg.performative == FipaMessage.Performative.DECLINE:\n self._on_decline(fipa_msg, fipa_dialogue)\n elif fipa_msg.performative == FipaMessage.Performative.ACCEPT:\n self._on_accept(fipa_msg, fipa_dialogue)\n elif fipa_msg.performative == FipaMessage.Performative.MATCH_ACCEPT_W_INFORM:\n self._on_match_accept(fipa_msg, fipa_dialogue)\n\n def teardown(self) -> None:\n \"\"\"\n Implement the handler teardown.\n\n :return: None\n \"\"\"\n pass\n\n def _handle_unidentified_dialogue(self, msg: FipaMessage) -> None:\n \"\"\"\n Handle an unidentified dialogue.\n\n Respond to the sender with a default message containing the appropriate error information.\n\n :param msg: the message\n\n :return: None\n \"\"\"\n self.context.logger.info(\n \"[{}]: unidentified dialogue.\".format(self.context.agent_name)\n )\n default_msg = DefaultMessage(\n dialogue_reference=(\"\", \"\"),\n message_id=1,\n target=0,\n performative=DefaultMessage.Performative.ERROR,\n error_code=DefaultMessage.ErrorCode.INVALID_DIALOGUE,\n error_msg=\"Invalid dialogue.\",\n error_data={\"fipa_message\": msg.encode()},\n )\n default_msg.counterparty = msg.counterparty\n self.context.outbox.put_message(message=default_msg)\n\n def _on_cfp(self, cfp: FipaMessage, dialogue: Dialogue) -> None:\n \"\"\"\n Handle a CFP.\n\n :param cfp: the fipa message containing the CFP\n :param dialogue: the dialogue\n\n :return: None\n \"\"\"\n new_msg_id = cfp.message_id + 1\n query = cast(Query, cfp.query)\n strategy = cast(Strategy, self.context.strategy)\n proposal_description = strategy.get_proposal_for_query(\n query, cast(Dialogue.Role, dialogue.role)\n )\n\n if proposal_description is None:\n self.context.logger.debug(\n \"[{}]: sending to {} a Decline{}\".format(\n self.context.agent_name,\n dialogue.dialogue_label.dialogue_opponent_addr[-5:],\n pprint.pformat(\n {\n \"msg_id\": new_msg_id,\n \"dialogue_reference\": cfp.dialogue_reference,\n \"origin\": dialogue.dialogue_label.dialogue_opponent_addr[\n -5:\n ],\n \"target\": cfp.target,\n }\n ),\n )\n )\n fipa_msg = FipaMessage(\n performative=FipaMessage.Performative.DECLINE,\n message_id=new_msg_id,\n dialogue_reference=dialogue.dialogue_label.dialogue_reference,\n target=cfp.message_id,\n )\n dialogues = cast(Dialogues, self.context.dialogues)\n dialogues.dialogue_stats.add_dialogue_endstate(\n Dialogue.EndState.DECLINED_CFP, dialogue.is_self_initiated\n )\n else:\n transactions = cast(Transactions, self.context.transactions)\n transaction_msg = transactions.generate_transaction_message(\n SigningMessage.Performative.SIGN_MESSAGE,\n proposal_description,\n dialogue.dialogue_label,\n cast(Dialogue.Role, dialogue.role),\n self.context.agent_address,\n )\n transactions.add_pending_proposal(\n dialogue.dialogue_label, new_msg_id, transaction_msg\n )\n self.context.logger.info(\n \"[{}]: sending to {} a Propose {}\".format(\n self.context.agent_name,\n dialogue.dialogue_label.dialogue_opponent_addr[-5:],\n pprint.pformat(\n {\n \"msg_id\": new_msg_id,\n \"dialogue_reference\": cfp.dialogue_reference,\n \"origin\": dialogue.dialogue_label.dialogue_opponent_addr[\n -5:\n ],\n \"target\": cfp.message_id,\n \"propose\": proposal_description.values,\n }\n ),\n )\n )\n fipa_msg = FipaMessage(\n performative=FipaMessage.Performative.PROPOSE,\n message_id=new_msg_id,\n dialogue_reference=dialogue.dialogue_label.dialogue_reference,\n target=cfp.message_id,\n proposal=proposal_description,\n )\n fipa_msg.counterparty = cfp.counterparty\n dialogue.update(fipa_msg)\n self.context.outbox.put_message(message=fipa_msg)\n\n def _on_propose(self, propose: FipaMessage, dialogue: Dialogue) -> None:\n \"\"\"\n Handle a Propose.\n\n :param propose: the message containing the Propose\n :param dialogue: the dialogue\n :return: None\n \"\"\"\n new_msg_id = propose.message_id + 1\n strategy = cast(Strategy, self.context.strategy)\n proposal_description = propose.proposal\n self.context.logger.debug(\n \"[{}]: on Propose as {}.\".format(self.context.agent_name, dialogue.role)\n )\n transactions = cast(Transactions, self.context.transactions)\n transaction_msg = transactions.generate_transaction_message(\n SigningMessage.Performative.SIGN_MESSAGE,\n proposal_description,\n dialogue.dialogue_label,\n cast(Dialogue.Role, dialogue.role),\n self.context.agent_address,\n )\n\n if strategy.is_profitable_transaction(\n transaction_msg, role=cast(Dialogue.Role, dialogue.role)\n ):\n self.context.logger.info(\n \"[{}]: Accepting propose (as {}).\".format(\n self.context.agent_name, dialogue.role\n )\n )\n transactions.add_locked_tx(\n transaction_msg, role=cast(Dialogue.Role, dialogue.role)\n )\n transactions.add_pending_initial_acceptance(\n dialogue.dialogue_label, new_msg_id, transaction_msg\n )\n fipa_msg = FipaMessage(\n performative=FipaMessage.Performative.ACCEPT,\n message_id=new_msg_id,\n dialogue_reference=dialogue.dialogue_label.dialogue_reference,\n target=propose.message_id,\n )\n else:\n self.context.logger.info(\n \"[{}]: Declining propose (as {})\".format(\n self.context.agent_name, dialogue.role\n )\n )\n fipa_msg = FipaMessage(\n performative=FipaMessage.Performative.DECLINE,\n message_id=new_msg_id,\n dialogue_reference=dialogue.dialogue_label.dialogue_reference,\n target=propose.message_id,\n )\n dialogues = cast(Dialogues, self.context.dialogues)\n dialogues.dialogue_stats.add_dialogue_endstate(\n Dialogue.EndState.DECLINED_PROPOSE, dialogue.is_self_initiated\n )\n fipa_msg.counterparty = propose.counterparty\n dialogue.update(fipa_msg)\n self.context.outbox.put_message(message=fipa_msg)\n\n def _on_decline(self, decline: FipaMessage, dialogue: Dialogue) -> None:\n \"\"\"\n Handle a Decline.\n\n :param decline: the Decline message\n :param dialogue: the dialogue\n :return: None\n \"\"\"\n self.context.logger.debug(\n \"[{}]: on_decline: msg_id={}, dialogue_reference={}, origin={}, target={}\".format(\n self.context.agent_name,\n decline.message_id,\n decline.dialogue_reference,\n dialogue.dialogue_label.dialogue_opponent_addr,\n decline.target,\n )\n )\n target = decline.target\n dialogues = cast(Dialogues, self.context.dialogues)\n\n if target == 1:\n dialogues.dialogue_stats.add_dialogue_endstate(\n Dialogue.EndState.DECLINED_CFP, dialogue.is_self_initiated\n )\n elif target == 2:\n dialogues.dialogue_stats.add_dialogue_endstate(\n Dialogue.EndState.DECLINED_PROPOSE, dialogue.is_self_initiated\n )\n transactions = cast(Transactions, self.context.transactions)\n transaction_msg = transactions.pop_pending_proposal(\n dialogue.dialogue_label, target\n )\n elif target == 3:\n dialogues.dialogue_stats.add_dialogue_endstate(\n Dialogue.EndState.DECLINED_ACCEPT, dialogue.is_self_initiated\n )\n transactions = cast(Transactions, self.context.transactions)\n transaction_msg = transactions.pop_pending_initial_acceptance(\n dialogue.dialogue_label, target\n )\n transactions.pop_locked_tx(transaction_msg)\n\n def _on_accept(self, accept: FipaMessage, dialogue: Dialogue) -> None:\n \"\"\"\n Handle an Accept.\n\n :param accept: the Accept message\n :param dialogue: the dialogue\n :return: None\n \"\"\"\n self.context.logger.debug(\n \"[{}]: on_accept: msg_id={}, dialogue_reference={}, origin={}, target={}\".format(\n self.context.agent_name,\n accept.message_id,\n accept.dialogue_reference,\n dialogue.dialogue_label.dialogue_opponent_addr,\n accept.target,\n )\n )\n new_msg_id = accept.message_id + 1\n transactions = cast(Transactions, self.context.transactions)\n transaction_msg = transactions.pop_pending_proposal(\n dialogue.dialogue_label, accept.target\n )\n strategy = cast(Strategy, self.context.strategy)\n\n if strategy.is_profitable_transaction(\n transaction_msg, role=cast(Dialogue.Role, dialogue.role)\n ):\n self.context.logger.info(\n \"[{}]: locking the current state (as {}).\".format(\n self.context.agent_name, dialogue.role\n )\n )\n transactions.add_locked_tx(\n transaction_msg, role=cast(Dialogue.Role, dialogue.role)\n )\n if strategy.is_contract_tx:\n pass\n # contract = cast(ERC1155Contract, self.context.contracts.erc1155)\n # if not contract.is_deployed:\n # ledger_api = self.context.ledger_apis.get_api(strategy.ledger_id)\n # contract_address = self.context.shared_state.get(\n # \"erc1155_contract_address\", None\n # )\n # assert (\n # contract_address is not None\n # ), \"ERC1155Contract address not set!\"\n # tx_nonce = transaction_msg.skill_callback_info.get(\"tx_nonce\", None)\n # assert tx_nonce is not None, \"tx_nonce must be provided\"\n # transaction_msg = contract.get_hash_batch_transaction_msg(\n # from_address=accept.counterparty,\n # to_address=self.context.agent_address, # must match self\n # token_ids=[\n # int(key)\n # for key in transaction_msg.terms.quantities_by_good_id.keys()\n # ]\n # + [\n # int(key)\n # for key in transaction_msg.terms.amount_by_currency_id.keys()\n # ],\n # from_supplies=[\n # quantity if quantity > 0 else 0\n # for quantity in transaction_msg.terms.quantities_by_good_id.values()\n # ]\n # + [\n # value if value > 0 else 0\n # for value in transaction_msg.terms.amount_by_currency_id.values()\n # ],\n # to_supplies=[\n # -quantity if quantity < 0 else 0\n # for quantity in transaction_msg.terms.quantities_by_good_id.values()\n # ]\n # + [\n # -value if value < 0 else 0\n # for value in transaction_msg.terms.amount_by_currency_id.values()\n # ],\n # value=0,\n # trade_nonce=int(tx_nonce),\n # ledger_api=self.context.ledger_apis.get_api(strategy.ledger_id),\n # skill_callback_id=self.context.skill_id,\n # skill_callback_info={\n # \"dialogue_label\": dialogue.dialogue_label.json\n # },\n # )\n self.context.logger.info(\n \"[{}]: sending tx_message={} to decison maker.\".format(\n self.context.agent_name, transaction_msg\n )\n )\n self.context.decision_maker_message_queue.put(transaction_msg)\n else:\n self.context.logger.debug(\n \"[{}]: decline the Accept (as {}).\".format(\n self.context.agent_name, dialogue.role\n )\n )\n fipa_msg = FipaMessage(\n performative=FipaMessage.Performative.DECLINE,\n message_id=new_msg_id,\n dialogue_reference=dialogue.dialogue_label.dialogue_reference,\n target=accept.message_id,\n )\n fipa_msg.counterparty = accept.counterparty\n dialogue.update(fipa_msg)\n dialogues = cast(Dialogues, self.context.dialogues)\n dialogues.dialogue_stats.add_dialogue_endstate(\n Dialogue.EndState.DECLINED_ACCEPT, dialogue.is_self_initiated\n )\n self.context.outbox.put_message(message=fipa_msg)\n\n def _on_match_accept(self, match_accept: FipaMessage, dialogue: Dialogue) -> None:\n \"\"\"\n Handle a matching Accept.\n\n :param match_accept: the MatchAccept message\n :param dialogue: the dialogue\n :return: None\n \"\"\"\n self.context.logger.debug(\n \"[{}]: on_match_accept: msg_id={}, dialogue_reference={}, origin={}, target={}\".format(\n self.context.agent_name,\n match_accept.message_id,\n match_accept.dialogue_reference,\n dialogue.dialogue_label.dialogue_opponent_addr,\n match_accept.target,\n )\n )\n if (match_accept.info.get(\"tx_signature\") is not None) and (\n match_accept.info.get(\"tx_id\") is not None\n ):\n transactions = cast(Transactions, self.context.transactions)\n transaction_msg = transactions.pop_pending_initial_acceptance(\n dialogue.dialogue_label, match_accept.target\n )\n strategy = cast(Strategy, self.context.strategy)\n if strategy.is_contract_tx:\n pass\n # contract = cast(ERC1155Contract, self.context.contracts.erc1155)\n # if not contract.is_deployed:\n # ledger_api = self.context.ledger_apis.get_api(strategy.ledger_id)\n # contract_address = self.context.shared_state.get(\n # \"erc1155_contract_address\", None\n # )\n # assert (\n # contract_address is not None\n # ), \"ERC1155Contract address not set!\"\n # contract.set_deployed_instance(\n # ledger_api, cast(str, contract_address),\n # )\n # strategy = cast(Strategy, self.context.strategy)\n # tx_nonce = transaction_msg.skill_callback_info.get(\"tx_nonce\", None)\n # tx_signature = match_accept.info.get(\"tx_signature\", None)\n # assert (\n # tx_nonce is not None and tx_signature is not None\n # ), \"tx_nonce or tx_signature not available\"\n # transaction_msg = contract.get_atomic_swap_batch_transaction_msg(\n # from_address=self.context.agent_address,\n # to_address=match_accept.counterparty,\n # token_ids=[\n # int(key)\n # for key in transaction_msg.terms.quantities_by_good_id.keys()\n # ]\n # + [\n # int(key)\n # for key in transaction_msg.terms.amount_by_currency_id.keys()\n # ],\n # from_supplies=[\n # -quantity if quantity < 0 else 0\n # for quantity in transaction_msg.terms.quantities_by_good_id.values()\n # ]\n # + [\n # -value if value < 0 else 0\n # for value in transaction_msg.terms.amount_by_currency_id.values()\n # ],\n # to_supplies=[\n # quantity if quantity > 0 else 0\n # for quantity in transaction_msg.terms.quantities_by_good_id.values()\n # ]\n # + [\n # value if value > 0 else 0\n # for value in transaction_msg.terms.amount_by_currency_id.values()\n # ],\n # value=0,\n # trade_nonce=int(tx_nonce),\n # ledger_api=self.context.ledger_apis.get_api(strategy.ledger_id),\n # skill_callback_id=self.context.skill_id,\n # signature=tx_signature,\n # skill_callback_info={\n # \"dialogue_label\": dialogue.dialogue_label.json\n # },\n # )\n else:\n transaction_msg.set(\n \"skill_callback_ids\",\n [PublicId.from_str(\"fetchai/tac_participation:0.4.0\")],\n )\n transaction_msg.set(\n \"skill_callback_info\",\n {\n **transaction_msg.skill_callback_info,\n **{\n \"tx_counterparty_signature\": match_accept.info.get(\n \"tx_signature\"\n ),\n \"tx_counterparty_id\": match_accept.info.get(\"tx_id\"),\n },\n },\n )\n self.context.logger.info(\n \"[{}]: sending tx_message={} to decison maker.\".format(\n self.context.agent_name, transaction_msg\n )\n )\n self.context.decision_maker_message_queue.put(transaction_msg)\n else:\n self.context.logger.warning(\n \"[{}]: match_accept did not contain tx_signature and tx_id!\".format(\n self.context.agent_name\n )\n )\n\n\nclass SigningHandler(Handler):\n \"\"\"This class implements the transaction handler.\"\"\"\n\n SUPPORTED_PROTOCOL = SigningMessage.protocol_id # type: Optional[ProtocolId]\n\n def setup(self) -> None:\n \"\"\"\n Implement the setup.\n\n :return: None\n \"\"\"\n pass\n\n def handle(self, message: Message) -> None:\n \"\"\"\n Dispatch message to relevant handler and respond.\n\n :param message: the message\n :return: None\n \"\"\"\n tx_message = cast(SigningMessage, message)\n if tx_message.performative == SigningMessage.Performative.SIGNED_MESSAGE:\n self.context.logger.info(\n \"[{}]: transaction confirmed by decision maker\".format(\n self.context.agent_name\n )\n )\n strategy = cast(Strategy, self.context.strategy)\n dialogue_label = DialogueLabel.from_json(\n cast(\n Dict[str, str], tx_message.skill_callback_info.get(\"dialogue_label\")\n )\n )\n dialogues = cast(Dialogues, self.context.dialogues)\n dialogue = dialogues.dialogues[dialogue_label]\n last_fipa_message = cast(FipaMessage, dialogue.last_incoming_message)\n if (\n last_fipa_message is not None\n and last_fipa_message.performative == FipaMessage.Performative.ACCEPT\n ):\n self.context.logger.info(\n \"[{}]: sending match accept to {}.\".format(\n self.context.agent_name,\n dialogue.dialogue_label.dialogue_opponent_addr[-5:],\n )\n )\n fipa_msg = FipaMessage(\n performative=FipaMessage.Performative.MATCH_ACCEPT_W_INFORM,\n message_id=last_fipa_message.message_id + 1,\n dialogue_reference=dialogue.dialogue_label.dialogue_reference,\n target=last_fipa_message.message_id,\n info={\n \"tx_signature\": tx_message.signed_transaction,\n \"tx_id\": tx_message.dialogue_reference[0],\n },\n )\n fipa_msg.counterparty = dialogue.dialogue_label.dialogue_opponent_addr\n dialogue.update(fipa_msg)\n self.context.outbox.put_message(message=fipa_msg)\n elif (\n last_fipa_message is not None\n and last_fipa_message.performative\n == FipaMessage.Performative.MATCH_ACCEPT_W_INFORM\n and strategy.is_contract_tx\n ):\n self.context.logger.info(\n \"[{}]: sending atomic swap tx to ledger.\".format(\n self.context.agent_name\n )\n )\n tx_signed = tx_message.signed_transaction\n tx_digest = self.context.ledger_apis.get_api(\n strategy.ledger_id\n ).send_signed_transaction(tx_signed=tx_signed)\n # TODO; handle case when no tx_digest returned and remove loop\n assert tx_digest is not None, \"Error when submitting tx.\"\n self.context.logger.info(\n \"[{}]: tx_digest={}.\".format(self.context.agent_name, tx_digest)\n )\n count = 0\n while (\n not self.context.ledger_apis.get_api(\n strategy.ledger_id\n ).is_transaction_settled(tx_digest)\n and count < 20\n ):\n self.context.logger.info(\n \"[{}]: waiting for tx to confirm. Sleeping for 3 seconds ...\".format(\n self.context.agent_name\n )\n )\n time.sleep(3.0)\n count += 1\n tx_receipt = self.context.ledger_apis.get_api(\n strategy.ledger_id\n ).get_transaction_receipt(tx_digest=tx_digest)\n if tx_receipt is None:\n self.context.logger.info(\n \"[{}]: Failed to get tx receipt for atomic swap.\".format(\n self.context.agent_name\n )\n )\n elif tx_receipt.status != 1:\n self.context.logger.info(\n \"[{}]: Failed to conduct atomic swap.\".format(\n self.context.agent_name\n )\n )\n else:\n self.context.logger.info(\n \"[{}]: Successfully conducted atomic swap. Transaction digest: {}\".format(\n self.context.agent_name, tx_digest\n )\n )\n # contract = cast(ERC1155Contract, self.context.contracts.erc1155)\n # result = contract.get_balances(\n # address=self.context.agent_address,\n # token_ids=[\n # int(key)\n # for key in tx_message.terms.quantities_by_good_id.keys()\n # ]\n # + [\n # int(key)\n # for key in tx_message.terms.amount_by_currency_id.keys()\n # ],\n # )\n result = 0\n self.context.logger.info(\n \"[{}]: Current balances: {}\".format(\n self.context.agent_name, result\n )\n )\n else:\n self.context.logger.warning(\n \"[{}]: last message should be of performative accept or match accept.\".format(\n self.context.agent_name\n )\n )\n else:\n self.context.logger.info(\n \"[{}]: transaction was not successful.\".format(self.context.agent_name)\n )\n\n def teardown(self) -> None:\n \"\"\"\n Implement the handler teardown.\n\n :return: None\n \"\"\"\n pass\n\n\nclass OEFSearchHandler(Handler):\n \"\"\"This class implements the oef search handler.\"\"\"\n\n SUPPORTED_PROTOCOL = OefSearchMessage.protocol_id # type: Optional[ProtocolId]\n\n def setup(self) -> None:\n \"\"\"\n Implement the setup.\n\n :return: None\n \"\"\"\n pass\n\n def handle(self, message: Message) -> None:\n \"\"\"\n Implement the reaction to a message.\n\n :param message: the message\n :return: None\n \"\"\"\n # convenience representations\n oef_msg = cast(OefSearchMessage, message)\n\n if oef_msg.performative is OefSearchMessage.Performative.SEARCH_RESULT:\n agents = list(oef_msg.agents)\n search_id = int(oef_msg.dialogue_reference[0])\n search = cast(Search, self.context.search)\n if self.context.agent_address in agents:\n agents.remove(self.context.agent_address)\n agents_less_self = tuple(agents)\n if search_id in search.ids_for_sellers:\n self._handle_search(\n agents_less_self, search_id, is_searching_for_sellers=True\n )\n elif search_id in search.ids_for_buyers:\n self._handle_search(\n agents_less_self, search_id, is_searching_for_sellers=False\n )\n\n def teardown(self) -> None:\n \"\"\"\n Implement the handler teardown.\n\n :return: None\n \"\"\"\n pass\n\n def _handle_search(\n self, agents: Tuple[str, ...], search_id: int, is_searching_for_sellers: bool\n ) -> None:\n \"\"\"\n Handle the search response.\n\n :param agents: the agents returned by the search\n :param is_searching_for_sellers: whether the agent is searching for sellers\n :return: None\n \"\"\"\n searched_for = \"sellers\" if is_searching_for_sellers else \"buyers\"\n if len(agents) > 0:\n self.context.logger.info(\n \"[{}]: found potential {} agents={} on search_id={}.\".format(\n self.context.agent_name,\n searched_for,\n list(map(lambda x: x[-5:], agents)),\n search_id,\n )\n )\n strategy = cast(Strategy, self.context.strategy)\n dialogues = cast(Dialogues, self.context.dialogues)\n query = strategy.get_own_services_query(\n is_searching_for_sellers, is_search_query=False\n )\n\n for opponent_addr in agents:\n self.context.logger.info(\n \"[{}]: sending CFP to agent={}\".format(\n self.context.agent_name, opponent_addr[-5:]\n )\n )\n fipa_msg = FipaMessage(\n message_id=Dialogue.STARTING_MESSAGE_ID,\n dialogue_reference=dialogues.new_self_initiated_dialogue_reference(),\n performative=FipaMessage.Performative.CFP,\n target=Dialogue.STARTING_TARGET,\n query=query,\n )\n fipa_msg.counterparty = opponent_addr\n dialogues.update(fipa_msg)\n self.context.outbox.put_message(message=fipa_msg)\n else:\n self.context.logger.info(\n \"[{}]: found no {} agents on search_id={}, continue searching.\".format(\n self.context.agent_name, searched_for, search_id\n )\n )\n","sub_path":"packages/fetchai/skills/tac_negotiation/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":32079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"175570585","text":"import os\nimport pygame\n#####################################################\n# basic initialize\npygame.init() #init\nscreen_width = 640 \nscreen_height = 480\nscreen = pygame.display.set_mode((screen_width,screen_height))\npygame.display.set_caption(\"Nado Pang\")\nclock = pygame.time.Clock()\n#############################################################\n# User Initialize \n# background\n\ncurrent_path = os.path.dirname(__file__) # return current postion\nimage_path = os.path.join(current_path,\"images\")\n\n\nbackground = pygame.image.load(os.path.join(image_path,\"background.png\"))\nstage = pygame.image.load(os.path.join(image_path,\"stage.png\"))\nstage_size = stage.get_rect().size\nstage_height = stage_size[1] # put the character on stage\n\n\n# read sprit(character)\ncharacter = pygame.image.load(os.path.join(image_path,\"character.png\"))\ncharacter_size = character.get_rect().size #get image size\ncharacter_width = character_size[0] #hor\ncharacter_height = character_size[1] #veri\ncharacter_x_pos = screen_width / 2 - (character_width / 2)\ncharacter_y_pos = screen_height - character_height - stage_height\n\n# move coord\ncharacter_to_x = 0\ncharacter_to_y = 0\ncharacter_speed = 0.3\n\n\n#weapon\nweapon = pygame.image.load(os.path.join(image_path,\"weapon.png\"))\nweapon_size = weapon.get_rect().size #get image size\nweapon_width = weapon_size[0] #hor\n\n# multi shot\nweapons = []\nweapon_speed = 10\n\n\n\n#display text\ngame_font = pygame.font.Font(None,40)\ntotal_time = 10\nstart_ticks = pygame.time.get_ticks()\n\n#event loop\nrunning = True\nwhile running:\n dt = clock.tick(30) #FPS setting\n #character to move 100\n # 10 fps : 10 * 10 100\n # 20 fps : 5 * 20 = 100\n print(\"fps : \" + str(clock.get_fps()))\n\n # event handler \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_LEFT:\n character_to_x -=character_speed\n elif event.key == pygame.K_RIGHT: \n character_to_x +=character_speed \n # elif event.key == pygame.K_UP:\n # character_to_y -=character_speed\n # elif event.key == pygame.K_DOWN:\n # character_to_y +=character_speed\n elif event.key == pygame.K_SPACE:\n weapon_x_pos = character_x_pos + (character_width/2) - (weapon_width/2)\n weapon_y_pos = character_y_pos\n weapons.append([weapon_x_pos,weapon_y_pos])\n \n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n character_to_x = 0\n if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n character_to_y = 0\n\n #3. game character position update\n character_x_pos += character_to_x * dt\n character_y_pos += character_to_y * dt\n\n if character_x_pos < 0 :\n character_x_pos = 0\n elif character_x_pos > screen_width - character_width:\n character_x_pos = screen_width - character_width\n\n if character_y_pos < 0 :\n character_y_pos = 0\n elif character_y_pos > screen_height - character_height:\n character_y_pos = screen_height - character_height\n\n#4 collision info\n character_rect = character.get_rect()\n character_rect.left = character_x_pos\n character_rect.top = character_y_pos\n\n# weapons position change 100,200 -> 100, 180,16\n weapons = [[w[0],w[1]-weapon_speed ] for w in weapons]\n\n# delect weapon on top\n weapons = [[w[0],w[1]] for w in weapons if w[1] > 0 ]\n\n\n# collision check\n\n\n\n#5 render screen\n\n screen.blit(background,(0,0))\n\n for weapon_x_pos, weapon_y_pos in weapons:\n screen.blit(weapon,(weapon_x_pos,weapon_y_pos))\n\n screen.blit(stage,(0,screen_height-stage_height))\n screen.blit(character,(character_x_pos,character_y_pos))\n\n\n\n #add timer\n elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 # sec\n timer = game_font.render(str(int(total_time - elapsed_time)), True,(255,255,255))\n screen.blit(timer,(10,10))\n\n if ( total_time - elapsed_time <= 0 ):\n print(\"time out\")\n running = False\n #screen.fill((0,0,255))\n pygame.display.update() # redraw screen\n\n\npygame.time.delay(2000)\n#pygame teminiation\npygame.quit()\n\n","sub_path":"Pygame_project/2_weapon_keyevent.py","file_name":"2_weapon_keyevent.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"314966887","text":"#============= enthought library imports =======================\nfrom enthought.envisage.ui.action.api import Action#, Group, Menu, ToolBar\nfrom enthought.envisage.ui.workbench.api import WorkbenchActionSet\n#============= standard library imports ========================\n\n#============= local library imports ==========================\nclass ScriptActionSet(WorkbenchActionSet):\n '''\n G{classtree}\n '''\n id = 'pychron.script.action_set'\n actions = [\n Action(name = 'New',\n path = 'MenuBar/File/Script',\n class_name = 'src.scripts.plugins.script_actions:NewScriptAction'),\n\n Action(name = 'Run',\n path = 'MenuBar/File/Script',\n class_name = 'src.scripts.plugins.script_actions:RunScriptAction'),\n\n Action(name = 'Power Map',\n path = 'MenuBar/File/Script/Open',\n class_name = 'src.scripts.plugins.script_actions:PowerMapAction'),\n\n ]\n#============= EOF ====================================\n","sub_path":"src/scripts/plugins/script_action_set.py","file_name":"script_action_set.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"7619282","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 28 10:16:28 2020\n\n@author: hwan\n\"\"\"\nimport os\nimport time\nfrom decimal import Decimal # for filenames\nimport pdb #Equivalent of keyboard in MATLAB, just add \"pdb.set_trace()\"\n\n###############################################################################\n# FilePaths #\n###############################################################################\nclass FilePaths():\n def __init__(self, hyperp, run_options,\n autoencoder_loss, project_name,\n data_options, dataset_directory):\n #################\n # File Name #\n #################\n #=== Data Type ===#\n if run_options.data_type_exponential == 1:\n data_type = 'exponential_'\n directory_name = 'Exponential/'\n\n data_string = data_type\n\n #=== Neural Network Architecture and Regularization ===#\n autoencoder_type = 'VAE_'\n if run_options.diagonal_posterior_covariance == 1:\n posterior_covariance_shape = 'diagpost_'\n if run_options.full_posterior_covariance == 1:\n posterior_covariance_shape = 'fullpost_'\n if run_options.diagonal_prior_covariance == 1:\n prior_string = 'prdiag'\n if run_options.full_prior_covariance == 1:\n prior_string = 'prfull'\n\n #=== File Name ===#\n self.filename = project_name +\\\n data_string + prior_string + '_' +\\\n autoencoder_type + autoencoder_loss +\\\n '_hl%d_tl%d_hn%d_%s_d%d_b%d_e%d' %(hyperp.num_hidden_layers,\n hyperp.truncation_layer, hyperp.num_hidden_nodes, hyperp.activation,\n run_options.num_data_train, hyperp.batch_size, hyperp.num_epochs)\n\n ################\n # Datasets #\n ################\n self.input_train_savefilepath =\\\n dataset_directory + directory_name + project_name +\\\n 'parameter_' + data_type + 'train_d%d_'%(run_options.num_data_train) +\\\n data_options\n self.output_train_savefilepath =\\\n dataset_directory + directory_name + project_name +\\\n 'state_' + data_type + 'train_d%d_'%(run_options.num_data_train) +\\\n data_options\n self.input_test_savefilepath =\\\n dataset_directory + directory_name + project_name +\\\n 'parameter_' + data_type + 'test_d%d_'%(run_options.num_data_test) +\\\n data_options\n self.output_test_savefilepath =\\\n dataset_directory + directory_name + project_name +\\\n 'state_' + data_type + 'test_d%d_'%(run_options.num_data_test) +\\\n data_options\n\n #############\n # Prior #\n #############\n #=== Prior File Name ===#\n if run_options.diagonal_prior_covariance == 1:\n prior_string = 'diag_'\n if run_options.full_prior_covariance == 1:\n prior_string = 'full_'\n self.prior_mean_file_name = project_name + 'prior_mean_' +\\\n data_type + 'n%d'%(run_options.parameter_dimensions)\n self.prior_mean_savefilepath = dataset_directory + directory_name +\\\n self.prior_mean_file_name\n self.prior_covariance_file_name = project_name + 'prior_covariance_' +\\\n prior_string + data_type + 'n%d'%(run_options.parameter_dimensions)\n self.prior_covariance_savefilepath = dataset_directory + directory_name +\\\n self.prior_covariance_file_name\n\n###############################################################################\n# Derived Classes #\n###############################################################################\nclass FilePathsTraining(FilePaths):\n def __init__(self, *args, **kwargs):\n super(FilePathsTraining, self).__init__(*args, **kwargs)\n #=== Saving Trained Neural Network and Tensorboard ===#\n self.NN_savefile_directory = '../../../Trained_NNs/' + self.filename\n self.NN_savefile_name = self.NN_savefile_directory + '/' + self.filename\n self.tensorboard_directory = '../../../Tensorboard/' + self.filename\n\nclass FilePathsHyperparameterOptimization(FilePaths):\n def __init__(self, *args, **kwargs):\n super(FilePathsHyperparameterOptimization, self).__init__(*args, **kwargs)\n #=== Saving Trained Neural Network and Tensorboard ===#\n self.hyperp_opt_Trained_NNs_directory = 'Hyperparameter_Optimization/Trained_NNs'\n self.hyperp_opt_Tensorboard_directory = 'Hyperparameter_Optimization/Tensorboard'\n self.NN_savefile_directory = self.hyperp_opt_Trained_NNs_directory + '/' + self.filename\n self.NN_savefile_name = self.NN_savefile_directory + '/' + self.filename\n self.tensorboard_directory = self.hyperp_opt_Tensorboard_directory + '/' + self.filename\n\n #=== Saving Hyperparameter Optimization Outputs ===#\n self.hyperp_opt_outputs_directory = 'Hyperparameter_Optimization'\n self.hyperp_opt_skopt_res_savefile_name = self.hyperp_opt_outputs_directory +\\\n '/hyperp_opt_result.pkl'\n self.hyperp_opt_optimal_parameters_savefile_name = self.hyperp_opt_outputs_directory +\\\n '/optimal_set_of_hyperparameters.txt'\n self.hyperp_opt_scenarios_trained_savefile_name = self.hyperp_opt_outputs_directory +\\\n '/scenarios_trained.txt'\n self.hyperp_opt_validation_losses_savefile_name = self.hyperp_opt_outputs_directory +\\\n '/validation_losses.csv'\n self.hyperp_opt_convergence_savefile_name = self.hyperp_opt_outputs_directory +\\\n '/convergence.png'\n\nclass FilePathsPredictionAndPlotting(FilePaths):\n def __init__(self, *args, **kwargs):\n super(FilePathsPredictionAndPlotting, self).__init__(*args, **kwargs)\n #=== File Path for Loading Trained Neural Network ===#\n self.NN_savefile_directory = '../../../Trained_NNs/' + self.filename\n self.NN_savefile_name = self.NN_savefile_directory + '/' + self.filename\n\n #=== File Path for Loading Displayable Test Data ===#\n self.savefile_name_parameter_test = self.NN_savefile_directory +\\\n '/parameter_test'\n self.savefile_name_state_test = self.NN_savefile_directory +\\\n '/state_test'\n\n #=== File Path for Loading Displayable Predictions ===#\n self.savefile_name_parameter_pred = self.NN_savefile_name + '_parameter_pred'\n self.savefile_name_state_pred = self.NN_savefile_name + '_state_pred'\n\n #=== File Path for Saving Figures ===#\n self.figures_savefile_directory = '../../../Figures/' + self.filename\n self.figures_savefile_name = self.figures_savefile_directory + '/' + self.filename\n self.figures_savefile_name_parameter_test = self.figures_savefile_directory + '/' +\\\n 'parameter_test'\n self.figures_savefile_name_state_test = self.figures_savefile_directory+ '/' +\\\n 'state_test'\n self.figures_savefile_name_parameter_pred = self.figures_savefile_name + '_parameter_pred'\n self.figures_savefile_name_state_pred = self.figures_savefile_name + '_state_pred'\n\n #=== Creating Directories ===#\n if not os.path.exists(self.figures_savefile_directory):\n os.makedirs(self.figures_savefile_directory)\n","sub_path":"Codes_TF2/projects/Simple_1D/Utilities/file_paths_VAE.py","file_name":"file_paths_VAE.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"150023505","text":"import numpy as np\r\nimport chainer\r\nfrom chainer import cuda, Function, report, training, utils, Variable\r\nfrom chainer import datasets, iterators, optimizers, serializers, reporter\r\nfrom chainer.dataset import convert\r\nfrom chainer.dataset import iterator as iterator_module\r\nfrom chainer import Link, Chain, ChainList\r\nfrom chainer import Link, Chain, ChainList\r\nimport chainer.functions as F\r\nimport chainer.links as L\r\nfrom chainer.training import extensions\r\nfrom chainer import reporter as reporter_module\r\nfrom chainer import function\r\nimport matplotlib.pyplot as plt\r\nimport os.path\r\nimport copy\r\n\r\n# Check version\r\n# Python 2.7.12 on win32 (Windows version)\r\n# numpy (1.14.0)\r\n# matplotlib (1.5.3)\r\n# chainer (1.20.0.1)\r\n\r\n# ****\r\n# This is a fault one.\r\n# eval loss of middle layer in/out, not real in/out\r\n\r\n\r\nclass CNN_Autoencoder2(Chain):\r\n\tdef __init__(self,num_filter, size_filter, stride0=1, net=None):\r\n\t\tsuper(CNN_Autoencoder2, self).__init__(\r\n\t\t\tconv1 = L.Convolution2D(1, num_filter, size_filter, stride=stride0,\r\n\t\t\t initialW=net.conv1_W if net else None ,initial_bias=net.conv1_b if net else None),\r\n\t\t\tconv2 = L.Convolution2D(num_filter, num_filter * 2, size_filter, stride=stride0),\r\n\t\t\tdcnv2 = L.Deconvolution2D(num_filter * 2, num_filter, size_filter, stride=stride0),\r\n\t\t\tdcnv1 = L.Deconvolution2D(num_filter, 1, size_filter, stride=stride0,\r\n\t\t\t initialW=net.dconv1_W if net else None ,initial_bias=net.dconv1_b if net else None),\r\n\t\t)\r\n\t\tself.train = True\r\n\r\n\tdef __call__(self, x):\r\n\t\th3, h1 = self.sub(x)\r\n\t\th4 = F.relu(self.dcnv1(h3))\r\n\t\treturn h4\r\n\r\n\tdef sub(self, x):\r\n\t\th1 = F.relu(self.conv1(x))\r\n\t\th2 = F.relu(self.conv2(h1))\r\n\t\th3 = F.relu(self.dcnv2(h2))\r\n\t\treturn h3,h1\r\n\r\nclass DelGradient(object):\r\n\tname = 'DelGradient'\r\n\tdef __init__(self, delTgt):\r\n\t\tself.delTgt = delTgt\r\n\r\n\tdef __call__(self, opt):\r\n\t\tfor name,param in opt.target.namedparams():\r\n\t\t\tfor d in self.delTgt:\r\n\t\t\t\tif d in name:\r\n\t\t\t\t\t#print ('avoid ', d)\r\n\t\t\t\t\tgrad = param.grad\r\n\t\t\t\t\twith cuda.get_device(grad):\r\n\t\t\t\t\t\tgrad*=0\r\n\r\n\r\nclass Custom_Updater(training.StandardUpdater):\r\n\tdef __init__(self, iterator, generator, optimizers, converter=convert.concat_examples, device=None,):\r\n\t\tif isinstance(iterator, iterator_module.Iterator):\r\n\t\t\titerator = {'main': iterator}\r\n\t\tself._iterators = iterator\r\n\t\tself.gen = generator\r\n\t\tself._optimizers = optimizers\r\n\t\tself.converter = converter\r\n\t\tself.device = device\r\n\t\tself.iteration = 0\r\n\r\n\tdef update_core(self):\r\n\t\tbatch = self._iterators['main'].next()\r\n\t\tin_arrays = self.converter(batch, self.device)\r\n\t\tx_data = in_arrays\r\n\t\t\r\n\t\tbatchsize = x_data.shape[0]\r\n\t\tz= x_data\r\n\r\n\t\ty_gen,x_gen = self.gen.sub(z)\r\n\r\n\t\tloss_gen = F.mean_squared_error(x_gen, y_gen)\r\n\t\tloss = loss_gen / batchsize\r\n\r\n\t\tfor optimizer in self._optimizers.values():\r\n\t\t\toptimizer.target.cleargrads()\r\n\r\n\t\t# compute gradients all at once\r\n\t\tloss.backward()\r\n\r\n\t\tfor optimizer in self._optimizers.values():\r\n\t\t\toptimizer.update()\r\n\r\n\t\t# loss will be summaried and compute_mean() per epoch\r\n\t\treporter.report(\r\n\t\t\t{'loss': loss})\r\n\r\n\r\nclass Custom_Evaluator(extensions.Evaluator):\r\n\tdef evaluate(self):\r\n\t\titerator = self._iterators['main']\r\n\t\ttarget = self._targets['main']\r\n\t\teval_func = target\r\n\t\tit = copy.copy(iterator)\r\n\r\n\t\tsummary = reporter_module.DictSummary()\r\n\r\n\t\tfor batch in it:\r\n\t\t\tobservation = {}\r\n\t\t\twith reporter_module.report_scope(observation):\r\n\t\t\t\tin_arrays = self.converter(batch, self.device)\r\n\t\t\t\twith function.no_backprop_mode():\r\n\t\t\t\t\t\ty_z,x_z=eval_func.sub(in_arrays)\r\n\t\t\t\t\t\tloss_validation = F.mean_squared_error(y_z, x_z) / in_arrays.shape[0]\r\n\r\n\t\t\tsummary.add({'validation/loss':loss_validation })\r\n\t\t\tsummary.add(observation)\r\n\r\n\r\n\t\treturn summary.compute_mean()\r\n\r\n\r\ndef plot_figure(test, OUT_DIR='autoencoder2'):\r\n\t@training.make_extension(trigger=(1, 'epoch'))\r\n\tdef _plot_figure(trainer):\r\n\t\tnumber=5\r\n\t\tfig, axs = plt.subplots(2,number)\r\n\t\t\r\n\t\twith function.no_backprop_mode():\r\n\t\t\tfor i in range(number):\r\n\t\t\t\tx = Variable(test[i].reshape(1, 1, 64, 64) ) \r\n\t\t\t\ty = updater.gen(x)\r\n\t\t\t\tx_data = test[i]\r\n\t\t\t\ty_data = y.data[0]\r\n\t\t\t\taxs[0,i].imshow(x_data.reshape(64,64), cmap='gray')\r\n\t\t\t\taxs[1,i].imshow(y_data.reshape(64,64), cmap='gray')\r\n\r\n\t\tplt.savefig( os.path.join(OUT_DIR,( 'epoch' + str(updater.epoch) + '.png')))\r\n\t\t\r\n\treturn _plot_figure\r\n\r\n\r\ndef get_dataset(IN_DIR='DataSet', train_ratio=9):\r\n\t# load data set and convert to tuple in this.py\r\n\ttrain_data = np.load(os.path.join(IN_DIR,'train_data.npy'))\r\n\t#train_label = np.load(os.path.join(IN_DIR,'train_label.npy'))\r\n\t#print ( train_data.shape[0])\r\n\t# dvide train and test per the ratio\r\n\tthreshold = np.int32(train_data.shape[0]/10*train_ratio)\r\n\ttrain = train_data[0:threshold]\r\n\ttest = train_data[threshold:]\r\n\treturn train, test\r\n\r\n\r\ndef save_auto_wb(model, OUT_DIR='autoencoder2'):\r\n\tif not os.path.exists(OUT_DIR):\r\n\t\tos.mkdir(OUT_DIR)\r\n\tconv2_W = model.conv2.W.data\r\n\tconv2_b = model.conv2.b.data\r\n\tdconv2_W = model.dcnv2.W.data\r\n\tdconv2_b = model.dcnv2.b.data\r\n\tnp.save(os.path.join(OUT_DIR,'conv2_W.npy'), conv2_W)\r\n\tnp.save(os.path.join(OUT_DIR,'conv2_b.npy'), conv2_b)\r\n\tnp.save(os.path.join(OUT_DIR,'dconv2_W.npy'), dconv2_W)\r\n\tnp.save(os.path.join(OUT_DIR,'dconv2_b.npy'), dconv2_b)\r\n\tprint ('saved conv W and b')\r\n\r\n\r\nclass Class_net(object):\r\n\tdef __init__(self, default_Wb):\r\n\t\tself.Wb = default_Wb\r\n\t@property\r\n\tdef conv1_W(self):\r\n\t\treturn self.Wb[0]\r\n\t@property\r\n\tdef conv1_b(self):\r\n\t\treturn self.Wb[1]\r\n\t@property\r\n\tdef dconv1_W(self):\r\n\t\treturn self.Wb[2]\r\n\t@property\r\n\tdef dconv1_b(self):\r\n\t\treturn self.Wb[3]\r\n\r\n\r\ndef load_init_Wb(IN_DIR='log_Autoencoder'):\r\n\tlist0=['conv1_W','conv1_b','dconv1_W','dconv1_b']\r\n\tfor i, listx in enumerate(list0):\r\n\t\tf=os.path.join(IN_DIR+ str(int(i/4)+1) ,(listx+'.npy'))\r\n\t\tif os.path.exists(f):\r\n\t\t\tlist0[i] = np.load(f)\r\n\t\t\tprint (' load of ', f)\r\n\t\telse:\r\n\t\t\tlist0[i] = None\r\n\t\t\tprint (' no file of ', f)\r\n\treturn Class_net(list0)\r\n\r\n\r\nif __name__=='__main__':\r\n\t\r\n\t# load upper layer W and b\r\n\tnet0=load_init_Wb()\r\n\r\n\tmodel = CNN_Autoencoder2(num_filter=16, size_filter=6,stride0=2, net=net0)\r\n\r\n\ttrain, test = get_dataset()\r\n\r\n\toptimizer = {'gen': chainer.optimizers.Adam()}\r\n\toptimizer['gen'].setup(model)\r\n\t\r\n\t# To avoid weight update of specified layer\r\n\toptimizer['gen'].add_hook(DelGradient([\"conv1\",\"dcnv1\"]))\r\n\t\r\n\t\r\n\ttrain_iter = chainer.iterators.SerialIterator(train, batch_size=30)\r\n\ttest_iter = chainer.iterators.SerialIterator(test, batch_size=30, repeat=False, shuffle=False)\r\n\r\n\tupdater = Custom_Updater(train_iter, model, optimizer, device=-1)\r\n\t\r\n\t### output dir \"logs\"\r\n\tOUT_DIR='log_Autoencoder2'\r\n\tif not os.path.exists(OUT_DIR):\r\n\t\tos.mkdir(OUT_DIR)\r\n\t\r\n\ttrainer = training.Trainer(updater, (30, 'epoch'), out=OUT_DIR)\r\n\ttrainer.extend(Custom_Evaluator(test_iter, model, device=-1))\r\n\t\r\n\t# If plot in/out comparison figure \r\n\ttrainer.extend(plot_figure(test,OUT_DIR))\r\n\t\r\n\ttrainer.extend(extensions.LogReport())\r\n\t\r\n\ttrainer.extend(extensions.PrintReport( ['epoch', 'loss', 'validation/loss', 'elapsed_time']))\r\n\ttrainer.extend(extensions.ProgressBar())\r\n\t\r\n\ttrainer.extend(extensions.PlotReport(['loss','validation/loss'], x_key='epoch', file_name='loss.png'))\r\n\t\r\n\t\r\n\t\r\n\ttrainer.run()\r\n\r\n\tsave_auto_wb(model, OUT_DIR)\r\n\r\n\r\n\r\n# This file uses TAB\r\n\r\n\r\n\r\n\r\n","sub_path":"cnn_autoencoder2.py","file_name":"cnn_autoencoder2.py","file_ext":"py","file_size_in_byte":7334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"313189539","text":"# Copyright @ 2020 Thought Machine Group Limited. All rights reserved.\nimport os\nimport uuid\nimport json\nfrom common.test_utils.endtoend.helper import send_request\nimport logging\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(\n level=os.environ.get(\"LOGLEVEL\", \"INFO\"),\n format=\"%(asctime)s.%(msecs)03d - %(levelname)s: %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\n\n\ndef create_payee(\n created_by_customer_id,\n account_id,\n payee_label,\n default_payment_reference,\n beneficiary_name,\n account_number,\n sort_code,\n):\n\n post_body = {\n \"request_id\": uuid.uuid4().hex,\n \"payee\": {\n \"created_by_customer_id\": created_by_customer_id,\n \"account_id\": account_id,\n \"payee_label\": payee_label,\n \"default_payment_reference\": default_payment_reference,\n \"uk_bank_identifier\": {\n \"beneficiary_name\": beneficiary_name,\n \"account_number\": account_number,\n \"sort_code\": sort_code,\n },\n },\n }\n\n post_body = json.dumps(post_body)\n\n res = send_request(\"post\", \"/v1/payees\", data=post_body)\n\n return res\n\n\ndef list_payees(customer_id, account_ids=None, include_deleted=None):\n get_body = {\n \"customer_id\": customer_id,\n \"account_ids\": account_ids,\n \"include_deleted\": include_deleted,\n \"page_size\": \"100\",\n }\n\n resp = send_request(\"get\", \"/v1/payees\", params=get_body)\n\n return resp[\"payees\"]\n\n\ndef get_payee(payee_id):\n get_body = {\"ids\": [payee_id]}\n resp = send_request(\"get\", \"/v1/payees:batchGet\", params=get_body)\n\n return next(iter(resp[\"payees\"].values()))\n","sub_path":"common/test_utils/endtoend/xpl_helper.py","file_name":"xpl_helper.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"99159420","text":"# coding=utf-8\nfrom util import db_util\nimport json\nimport datetime\nimport re\nimport os\n\ndb_util.db_url = 'mysql://app_user:app@LVVHW6@db:3306/test?charset=utf8'\nquery = db_util.get_query()\n\nlive_data_list = []\nlive_task_list = {}\ndemand_data_list = []\ndemand_works_list = {}\npraise_data_list = []\ncomment_data_list = []\nlive_web_data_list = []\nlive_web_list = {}\nuid_set = set([])\nip_set = set([])\n\n\n# 昨天日期前缀\nyesterday_str = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')\nlog_root_path = r'/data/logs/ks_stat/'\n\n\n# 获取日志内容中传递json格式参数\ndef get_param(log_str):\n if log_str:\n post_data_str = log_str[log_str.find('param:') + 6:]\n return json.loads(post_data_str)\n return None\n\n\n# 获取访问接口(执行该操作)的时间\ndef get_time(log_str):\n if log_str:\n time_str = log_str[:log_str.find(',')]\n return datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')\n return None\n\n\n# 分析日志文件获取直播,点播,点赞,评论等数据\ndef analysis_log(path):\n if not(os.path.exists(path)):\n path = log_root_path + 'live.log'\n with open(path, 'r') as f:\n line = f.readline()\n regex = re.compile('[\\n|\\t|\\r|\\v]+')\n line = re.sub(regex, '', line)\n while line:\n if line.find('/ks_web/api/live/live_room') != -1:\n live_data = {}\n param = get_param(line)\n\n live_data['uid'] = param['uid']\n live_data['roomer_uid'] = param['roomer_uid']\n live_data['room_id'] = param['room_id']\n live_data['live_id'] = param['live_id']\n live_data['time'] = get_time(line)\n\n live_data_list.append(live_data)\n elif line.find('/ks_web/api/live/praise') != -1:\n praise_data = {}\n param = get_param(line)\n\n praise_data['uid'] = param['uid']\n praise_data['live_id'] = param['live_id']\n praise_data['room_id'] = param['room_id']\n praise_data['time'] = get_time(line)\n\n praise_data_list.append(praise_data)\n elif line.find('/ks_web/api/live/live_comment/put') != -1:\n comment_data = {}\n param = get_param(line)\n\n comment_data['uid'] = param['uid']\n comment_data['live_id'] = param['live_id']\n comment_data['time'] = get_time(line)\n\n comment_data_list.append(comment_data)\n elif line.find('/ks_web/api/live/offline_live_show') != -1:\n demand_data = {}\n param = get_param(line)\n\n demand_data['uid'] = param['uid']\n demand_data['live_id'] = param['live_id']\n demand_data['room_id'] = param['room_id']\n demand_data['roomer_uid'] = param['roomer_uid']\n demand_data['time'] = get_time(line)\n\n demand_data_list.append(demand_data)\n elif line.find('/ks_web/api/live/live_for_web'):\n data = {}\n # 把\"ip\":12.23.23.43转换成\"ip\":\"12.23.23.43\"否则json转换报错\n index = line.find('\"ip\":')\n if index != -1 and line.find('\"ip\":\"') == -1:\n regex_str = '\"ip\":(.+?)}'\n ip = re.findall(regex_str, line)\n line = line.replace(ip[0], '\"' + ip[0] + '\"')\n param = get_param(line)\n if param.get('ip'):\n data['uid'] = param['uid']\n data['roomer_uid'] = param['roomer_uid']\n data['room_id'] = param['room_id']\n data['live_id'] = param['live_id']\n data['is_live'] = param['is_live']\n data['ip'] = param['ip']\n data['time'] = get_time(line)\n\n # 网页收听直点播数据\n live_web_data_list.append(data)\n line = f.readline()\n\n\ndef get_live_task():\n room_uid_set = set([])\n for live_data in live_data_list:\n room_uid_set.add(live_data['roomer_uid'])\n room_uid_list_str = str(room_uid_set)\n room_uid_list_str = room_uid_list_str[room_uid_list_str.find('[') + 1:room_uid_list_str.find(']')]\n live_task_list.clear()\n if len(room_uid_list_str) > 0:\n sql_str = \"select * from ks_live.live_task where uid in ({0}) and date_format(start_time, '%%Y-%%m-%%d') ='{1}' and date_format(end_time,'%%Y-%%m-%%d') = '{1}' \".format(\n room_uid_list_str, yesterday_str)\n query.Query(sql_str)\n for row in query.record:\n live_task = dict(live_id=row['id'], room_uid=row['uid'], room_id=row['room_id'],\n live_status=row['live_status'],\n start_time=row['start_time'], end_time=row['end_time'])\n live_task_list[row['id']] = live_task\n\n\ndef get_demand_works():\n get_live_data(demand_data_list, demand_works_list)\n\n\n# 获取指定的预告或作品信息\ndef get_live_data(data_list, result_dict):\n id_list = []\n for data in data_list:\n id_list.append(data['live_id'])\n\n return select_live_task(id_list, result_dict)\n\n\n# 按id list查询live_task\ndef select_live_task(id_list, result_dict):\n id_set = set(id_list)\n id_list_str = str(id_set)\n id_list_str = id_list_str[id_list_str.find('[') + 1:id_list_str.find(']')]\n if len(id_list) > 0:\n query.Query(\"select * from ks_live.live_task where id in (%s) \" % (id_list_str))\n for row in query.record:\n live = dict(live_id=row['id'], room_uid=row['uid'], room_id=row['room_id'],\n live_status=row['live_status'],\n start_time=row['start_time'], end_time=row['end_time'])\n result_dict[row['id']] = live\n return result_dict\n\n\n# 统计直播开始前一个小时到直播结束时间段内进入(按live_id和uid统计)\ndef count_live_user():\n live_user_dict = {}\n for live_data in live_data_list:\n live_task = live_task_list.get(live_data['live_id'])\n if live_task:\n start_time = live_task['start_time'] - datetime.timedelta(hours=1)\n # 判断进入直播大厅的时间是否在播开始前一个小时到直播结束时间之中\n if live_data['time'] >= start_time and live_data['time'] <= live_task['end_time']:\n live_user_id_set = live_user_dict.get(live_task['live_id'])\n # 判断是否是用户再次进入该直播间,如果是则不需再次重复统计该用户\n if live_user_id_set is not None and live_data['uid'] in live_user_id_set:\n continue\n else:\n live_user_count = live_task.get('live_user_count')\n if live_user_count is None:\n live_user_count = dict()\n live_user_count[live_data['uid']] = 1\n live_task['live_user_count'] = live_user_count\n\n # 保存进入过该直播间的用户\n if live_user_id_set is None:\n live_user_id_set = set([])\n live_user_id_set.add(live_data['uid'])\n live_user_dict[live_task['live_id']] = live_user_id_set\n else:\n live_user_id_set.add(live_data['uid'])\n # 保存有过直点播赞聊天评论操作的用户\n uid_set.add(live_data['uid'])\n\n\n# 统计直播期间点过赞的用户(按live_id和uid统计)\ndef count_live_praise_user():\n live_praise_user_dict = {}\n for praise_data in praise_data_list:\n live_task = live_task_list.get(praise_data['live_id'])\n if live_task:\n start_time = live_task['start_time'] - datetime.timedelta(hours=1) # 判断点赞时间是否在播开始前一个小时到直播结束时间之中如果是则是直播期间点赞\n if live_task is not None and praise_data['time'] >= start_time and praise_data['time'] <= live_task['end_time'] and praise_data['live_id'] == live_task['live_id']:\n live_praise_user_set = live_praise_user_dict.get(live_task['live_id'])\n # 判断是否是用户再次在该直播间点赞,如果是则不需再次重复统计该用户\n if live_praise_user_set is not None and praise_data['uid'] in live_praise_user_set:\n continue\n else:\n live_praise_user_count = live_task.get('live_praise_user_count')\n if live_praise_user_count is None:\n live_praise_user_count = dict()\n live_praise_user_count[praise_data['uid']] = 1\n live_task['live_praise_user_count'] = live_praise_user_count\n\n # 保存在该直播间点过赞的用户\n if live_praise_user_set is None:\n live_praise_user_set = set([])\n live_praise_user_set.add(praise_data['uid'])\n live_praise_user_dict[live_task['live_id']] = live_praise_user_set\n else:\n live_praise_user_set.add(praise_data['uid'])\n # 保存有过直点播赞聊天评论操作的用户\n uid_set.add(praise_data['uid'])\n\n\n# 统计直播期间聊天的用户(按live_id和uid统计)\ndef count_live_chat_user():\n for live_task in live_task_list.values():\n if live_task:\n if live_task.get('room_id') is None:\n live_task['room_id'] = 0\n query.Query(\n \"select uid from ks_live.live_chat_record where uid != 0 and room_id = {0} and create_time >= str_to_date('{1}','%%Y-%%m-%%d %%H:%%i:%%s') and create_time <= str_to_date('{2}','%%Y-%%m-%%d %%H:%%i:%%s') group by uid\".format(\n live_task['room_id'], live_task['start_time'].strftime('%Y-%m-%d %H:%M:%S'),\n live_task['end_time'].strftime('%Y-%m-%d %H:%M:%S')))\n live_task_chat_user_count = dict()\n for row in query.record:\n live_task_chat_user_count[row['uid']] = 1\n # 保存有过直点播赞聊天评论操作的用户\n uid_set.add(row['uid'])\n live_task['live_chat_user_count'] = live_task_chat_user_count\n\n\n# 统计点播过相应作品的用户(按live_id和uid统计)\ndef count_demand_works_user():\n works_demand_user_dict = {}\n for demand_data in demand_data_list:\n works = demand_works_list.get(demand_data['live_id'])\n # 判断用户是否点播过在作品\n if works:\n works_demand_user_set = works_demand_user_dict.get(works['live_id'])\n # 用户重复点播的某一作品,不能重复统计\n if works_demand_user_set is not None and demand_data['uid'] in works_demand_user_set:\n continue\n else:\n demand_user_count = works.get('demand_user_count')\n if demand_user_count is None:\n demand_user_count = dict()\n demand_user_count[demand_data['uid']] = 1\n works['demand_user_count'] = demand_user_count\n\n # 保存点播过该作品的用户\n if works_demand_user_set is None:\n works_demand_user_set = set([])\n works_demand_user_set.add(demand_data['uid'])\n works_demand_user_dict[works['live_id']] = works_demand_user_set\n else:\n works_demand_user_set.add(demand_data['uid'])\n # 保存有过直点播赞聊天评论操作的用户\n uid_set.add(demand_data['uid'])\n\n\n# 统计对点播作品点过赞的用户数(按live_id和uid统计)\ndef count_demand_works_praise_user():\n works_demand_praise_user_dict = {}\n for praise_data in praise_data_list:\n works = demand_works_list.get(praise_data['live_id'])\n if works:\n # 如果点赞时间大于直播结束时间则该点赞是相对于点播作品是的点赞\n if praise_data['time'] > works['end_time']:\n works_demand_praise_user_set = works_demand_praise_user_dict.get(works['live_id'])\n # 用户重复对点播的某一作品点赞,不能重复统计\n if works_demand_praise_user_set is not None and praise_data['uid'] in works_demand_praise_user_set:\n continue\n else:\n demand_praise_user_count = works.get('demand_praise_user_count')\n if demand_praise_user_count is None:\n demand_praise_user_count = dict()\n demand_praise_user_count[praise_data['uid']] = 1\n works['demand_praise_user_count'] = demand_praise_user_count\n\n # 保存对该作品点赞过的用户\n if works_demand_praise_user_set is None:\n works_demand_praise_user_set = set([])\n works_demand_praise_user_set.add(praise_data['uid'])\n works_demand_praise_user_dict[works['live_id']] = works_demand_praise_user_set\n else:\n works_demand_praise_user_set.add(praise_data['uid'])\n # 保存有过直点播赞聊天评论操作的用户\n uid_set.add(praise_data['uid'])\n\n\n# 统计对点播的作品进行评论的用户数量(按live_id和uid统计)\ndef count_demand_works_comment_user():\n works_demand_comment_user_dict = {}\n for comment_data in comment_data_list:\n works = demand_works_list.get(comment_data['live_id'])\n if works:\n works_demand_comment_user_set = works_demand_comment_user_dict.get(works['live_id'])\n # 用户重复对某一点播作品进行评论,不能重复统计\n if works_demand_comment_user_set is not None and comment_data['uid'] in works_demand_comment_user_set:\n continue\n else:\n demand_comment_user_count = works.get('demand_comment_user_count')\n if demand_comment_user_count is None:\n demand_comment_user_count = dict()\n demand_comment_user_count[comment_data['uid']] = 1\n works['demand_comment_user_count'] = demand_comment_user_count\n\n # 保存对该点播作品进行过评论的用户\n if works_demand_comment_user_set is None:\n works_demand_comment_user_set = set([])\n works_demand_comment_user_set.add(comment_data['uid'])\n works_demand_comment_user_dict[works['live_id']] = works_demand_comment_user_set\n else:\n works_demand_comment_user_set.add(comment_data['uid'])\n # 保存有过直点播赞聊天评论操作的用户\n uid_set.add(comment_data['uid'])\n\n\n# 合并点播和直播的相关数据\ndef merge_live_and_demand_data():\n live_data_dict = dict()\n demand_data_dict = dict()\n live_task_id_set = set([])\n # 将直播的数据按live_task_id为key存储到字典\n for live_task in live_task_list.values():\n live_data_dict[live_task['live_id']] = live_task\n live_task_id_set.add(live_task['live_id'])\n # 将点播的数据按live_task_id为key存储到字典\n for works in demand_works_list.values():\n demand_data_dict[works['live_id']] = works\n live_task_id_set.add(works['live_id'])\n\n for live_task_id in live_task_id_set:\n live_data = live_data_dict.get(live_task_id)\n demand_data = demand_data_dict.get(live_task_id)\n live_user_count = dict()\n live_praise_user_count = dict()\n live_chat_user_count = dict()\n demand_user_count = dict()\n demand_praise_user_count = dict()\n demand_comment_user_count = dict()\n roomer_uid = None\n room_id = None\n if live_data:\n if live_data.get('live_user_count'):\n live_user_count = live_data.get('live_user_count')\n if live_data.get('live_praise_user_count'):\n live_praise_user_count = live_data.get('live_praise_user_count')\n if live_data.get('live_chat_user_count'):\n live_chat_user_count = live_data.get('live_chat_user_count')\n roomer_uid = live_data.get('room_uid')\n room_id = live_data.get('room_id')\n if demand_data:\n if demand_data.get('demand_user_count'):\n demand_user_count = demand_data.get('demand_user_count')\n if demand_data.get('demand_praise_user_count'):\n demand_praise_user_count = demand_data.get('demand_praise_user_count')\n if demand_data.get('demand_comment_user_count'):\n demand_comment_user_count = demand_data.get('demand_comment_user_count')\n if roomer_uid is None:\n roomer_uid = demand_data.get('room_uid')\n if room_id is None:\n room_id = demand_data.get('room_id')\n if roomer_uid is None:\n roomer_uid = 0\n if room_id is None:\n room_id = 0\n for uid in uid_set:\n live_task_report = dict()\n\n live_task_report['live_task_id'] = live_task_id\n live_task_report['uid'] = uid\n live_task_report['roomer_uid'] = roomer_uid\n live_task_report['room_id'] = room_id\n is_empty_data = True\n\n if live_user_count.get(uid):\n live_task_report['live_user_count'] = live_user_count.get(uid)\n is_empty_data = False\n else:\n live_task_report['live_user_count'] = 0\n if live_praise_user_count.get(uid):\n live_task_report['live_praise_user_count'] = live_praise_user_count.get(uid)\n is_empty_data = False\n else:\n live_task_report['live_praise_user_count'] = 0\n if live_chat_user_count.get(uid):\n live_task_report['live_chat_user_count'] = live_chat_user_count.get(uid)\n is_empty_data = False\n else:\n live_task_report['live_chat_user_count'] = 0\n if demand_user_count.get(uid):\n live_task_report['demand_user_count'] = demand_user_count.get(uid)\n is_empty_data = False\n else:\n live_task_report['demand_user_count'] = 0\n if demand_praise_user_count.get(uid):\n live_task_report['demand_praise_user_count'] = demand_praise_user_count.get(uid)\n is_empty_data = False\n else:\n live_task_report['demand_praise_user_count'] = 0\n if demand_comment_user_count.get(uid):\n live_task_report['demand_comment_user_count'] = demand_comment_user_count.get(uid)\n is_empty_data = False\n else:\n live_task_report['demand_comment_user_count'] = 0\n\n if not is_empty_data:\n insert_live_task_report(live_task_report)\n\n\n# 插入数据到live_task_report表中\ndef insert_live_task_report(live_task_report):\n\n query.Query(\n \"insert into ks_data_statistics.live_task_report(live_task_id,uid,roomer_uid,room_id,cycle_time,live_user_count,live_praise_user_count,\"\n \"live_chat_user_count,demand_user_count,demand_praise_user_count,demand_comment_user_count,create_time) \"\n \"VALUES ({0},{1},{2},{3},str_to_date('{4}','%%Y-%%m-%%d'),{5},{6},{7},{8},{9},{10},str_to_date('{11}','%%Y-%%m-%%d %%H:%%i:%%s'))\".format(\n live_task_report.get('live_task_id'), live_task_report.get('uid'), live_task_report.get('roomer_uid'),\n live_task_report.get('room_id'), yesterday_str, live_task_report.get('live_user_count'),\n live_task_report.get('live_praise_user_count'), live_task_report.get('live_chat_user_count'),\n live_task_report.get('demand_user_count'),\n live_task_report.get('demand_praise_user_count'), live_task_report.get('demand_comment_user_count'),\n datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))\n\n\n#统计网页直点播数据(按live_id和ip统计)\ndef count_live_for_web_data():\n live_web_dict = dict()\n demand_web_dict = dict()\n get_live_data(live_web_data_list, live_web_list)\n for live_web_data in live_web_data_list:\n live_task = live_web_list.get(live_web_data['live_id'])\n if live_task is None:\n continue\n web_dict = demand_web_dict\n count_type = 'demand_count'\n if live_web_data['is_live'] == 1:\n web_dict = live_web_dict\n count_type = 'live_count'\n count_web_data(live_web_data, live_task, web_dict, count_type)\n\n\n# 统计一条网页web点直播数据记录,如果已经统计了该ip则不需要统计\ndef count_web_data(web_data, live_task, web_dict, count_type):\n web_ip_set = web_dict.get(web_data['live_id'])\n if web_ip_set is not None and web_data['ip'] in web_ip_set:\n return\n live_ip_count_dict = live_task.get(count_type)\n if live_ip_count_dict is None:\n live_ip_count_dict = dict()\n live_ip_count_dict[web_data['ip']] = 1\n live_task[count_type] = live_ip_count_dict\n if web_ip_set is None:\n web_ip_set = set([])\n web_ip_set.add(web_data['ip'])\n web_dict[web_data['live_id']] = web_ip_set\n\n ip_set.add(web_data['ip'])\n\n\n# 保存web网页直点播统计数据\ndef save_live_task_web_report():\n live_id_set = set(live_web_list.keys())\n for live_id in live_id_set:\n live_web = live_web_list[live_id]\n live_count = dict()\n demand_count = dict()\n if live_web.get('live_count'):\n live_count = live_web.get('live_count')\n if live_web.get('demand_count'):\n demand_count = live_web.get('demand_count')\n for ip in ip_set:\n live_task_web_report = dict()\n live_task_web_report['live_task_id'] = live_id\n live_task_web_report['room_id'] = live_web.get('room_id')\n live_task_web_report['roomer_uid'] = live_web.get('room_uid')\n live_task_web_report['ip'] = ip\n\n is_empty_data = True\n if live_count.get(ip):\n live_task_web_report['live_count'] = live_count.get(ip)\n is_empty_data = False\n else:\n live_task_web_report['live_count'] = 0\n if demand_count.get(ip):\n live_task_web_report['demand_count'] = demand_count.get(ip)\n is_empty_data = False\n else:\n live_task_web_report['demand_count'] = 0\n if not is_empty_data:\n insert_live_task_web_report(live_task_web_report)\n\n\n# 插入数据到live_task_web_report\ndef insert_live_task_web_report(report):\n query.Query(\n \"insert into ks_data_statistics.live_task_web_report(live_task_id,roomer_uid,room_id,cycle_time,ip,live_count,demand_count,create_time) \"\n \"VALUES ({0},{1},{2},str_to_date('{3}','%%Y-%%m-%%d'),'{4}',{5},{6},str_to_date('{7}','%%Y-%%m-%%d %%H:%%i:%%s'))\".format(\n report.get('live_task_id'), report.get('roomer_uid'),\n 0 if report.get('room_id') is None else report.get('room_id'), yesterday_str, report.get('ip'), report.get('live_count'),\n report.get('demand_count'), datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))\n\n\ndef main():\n analysis_log(log_root_path + 'live.log.' + yesterday_str)\n get_live_task()\n get_demand_works()\n count_live_user()\n count_live_praise_user()\n count_live_chat_user()\n count_demand_works_user()\n count_demand_works_praise_user()\n count_demand_works_comment_user()\n merge_live_and_demand_data()\n count_live_for_web_data()\n save_live_task_web_report()\n\nif __name__ == '__main__':\n log_root_path = r'D:/data/logs/ks_stat/'\n main()\n","sub_path":"statistics/live_report.py","file_name":"live_report.py","file_ext":"py","file_size_in_byte":24057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"238764206","text":"import math\nimport numpy as np\nimport os\nimport pandas as pd\nimport sys\n\nfrom glumpy import app, gloo, gl, glm\n\nvert_shader = \"\"\"\n// LIDAR Data 3d vectors\nattribute vec3 color;\nattribute vec3 pos;\n\n// Output position of center and radius from eye \nvarying vec3 eyespacePos;\nvarying float eyespaceRadius;\nvarying float dist_from_origin;\nvarying vec3 clr;\n\nuniform mat4 modelview;\nuniform mat4 projection;\nuniform float radius;\n\nvoid main() {\n dist_from_origin = length(pos);\n\n vec4 test_point = vec4(pos.xyz, 1.0f) + vec4(0, radius, 0, 0); \n test_point = modelview * test_point;\n vec4 eyespacePos4 = modelview * vec4(pos.xyz, 1.0f);\n\n eyespacePos = eyespacePos4.xyz;\n eyespaceRadius = length(test_point - eyespacePos4);\n\n vec4 clipspacePos = projection * eyespacePos4;\n gl_Position = clipspacePos;\n \n test_point = eyespacePos4 + vec4(0, eyespaceRadius, 0, 0); \n test_point = projection * test_point;\n test_point = test_point / test_point.w;\n clipspacePos = clipspacePos / clipspacePos.w;\n \n gl_PointSize = 3.0f; \n\n clr = color;\n}\n\"\"\"\n\nfrag_shader = \"\"\"\n// Parameters from the vertex shader\nvarying vec3 eyespacePos;\nvarying float eyespaceRadius;\nvarying float dist_from_origin;\nvarying vec3 clr;\n\n// Uniforms\nuniform mat4 modelview;\nuniform mat4 projection;\n\n// Heat map values\nuniform vec4 red = vec4(1.0f, 0, 0, 1.0f);\nuniform vec4 yellow = vec4(1.0f, 1.0f, 0, 1.0f);\nuniform vec4 green = vec4(0.5f, 1.0f, 0.0f, 1.0f);\nuniform vec4 blue = vec4(0.0f, 0.5f, 1.0f, 1.0f);\n\nvec4 heat_map_color(float dist) {\n // dist should be normalized between 0 and 1\n float close = float(dist < 0.34f);\n float medium = float(dist >= 0.34f && dist < 0.67f);\n float far = float(dist >= 0.67f);\n\n vec4 close_value = ((0.34f - dist) * red + dist * yellow) / .34f;\n vec4 medium_value = ((0.34f - dist / 2.0f) * yellow + dist / 2.0f * green) / .34f;\n vec4 far_value = ((0.34f - (min(dist, 1.0f) / 3.0f)) * green + min(dist, 1.0f) / 3.0 * blue) / .34f;\n\n return close * close_value + medium * medium_value + far * far_value;\n}\n\nvoid main() {\n vec3 normal;\n // See where we are inside the point sprite\n normal.xy = (gl_PointCoord * 2.0f) - vec2(1.0);\n float dist = dot(normal.xy, normal.xy);\n\n // Discard if outside circle\n //if(dist > 1.0f) {\n // discard;\n //}\n\n //gl_FragColor = heat_map_color (dist_from_origin / 40.0f) ;\n gl_FragColor = vec4(clr, 1.0);\n \n // Calculate fragment position in eye space, project to find depth\n vec4 fragPos = vec4(eyespacePos + normal * eyespaceRadius, 1.0);\n vec4 clipspacePos = projection * fragPos;\n\n // Set up output\n float far = gl_DepthRange.far;\n float near = gl_DepthRange.near;\n float deviceDepth = clipspacePos.z / clipspacePos.w;\n float fragDepth = (((far - near) * deviceDepth) + near +far) / 2.0;\n gl_FragDepth = fragDepth;\n}\n\n\"\"\" \n\nfrag_shader_line = \"\"\"\n// Parameters from the vertex shader\nvarying vec3 eyespacePos;\nvarying float eyespaceRadius;\nvarying float dist_from_origin;\nvarying vec3 clr;\n\n// Uniforms\nuniform mat4 modelview;\nuniform mat4 projection;\n\nvoid main() {\n vec3 normal;\n // See where we are inside the point sprite\n normal.xy = (gl_PointCoord * 2.0f) - vec2(1.0);\n float dist = dot(normal.xy, normal.xy);\n\n gl_FragColor = vec4(clr, 1.0);\n \n // Calculate fragment position in eye space, project to find depth\n vec4 fragPos = vec4(eyespacePos + normal * eyespaceRadius, 1.0);\n vec4 clipspacePos = projection * fragPos;\n\n // Set up output\n float far = gl_DepthRange.far;\n float near = gl_DepthRange.near;\n float deviceDepth = clipspacePos.z / clipspacePos.w;\n float fragDepth = (((far - near) * deviceDepth) + near +far) / 2.0;\n gl_FragDepth = fragDepth;\n}\n\n\"\"\" \ndef magnitude(v):\n return math.sqrt(np.sum(v ** 2))\n\ndef normalize(v):\n m = magnitude(v)\n if m == 0:\n return v\n return v / m\n\ndef translate(xyz):\n x, y, z = xyz\n return np.matrix([[1,0,0,x],\n [0,1,0,y],\n [0,0,1,z],\n [0,0,0,1]])\n\ndef lookat(eye, target, up):\n f = normalize(target - eye)\n s = normalize(np.cross(f, up))\n u = np.cross(s, f)\n \n res = np.eye(4, dtype=np.float32)\n res[:3, 0] = s\n res[:3, 1] = u\n res[:3, 2] = -f\n res[3, 0] =-np.dot(s, eye);\n res[3, 1] =-np.dot(u, eye);\n res[3, 2] = np.dot(f, eye);\n\n return res;\n\ndef perspective(field_of_view_y, aspect, z_near, z_far):\n\n fov_radians = math.radians(float(field_of_view_y))\n f = math.tan(fov_radians/2.0)\n\n perspective_matrix = np.zeros((4, 4))\n\n perspective_matrix[0][0] = 1.0 / (f*aspect)\n perspective_matrix[1][1] = 1.0 / f\n perspective_matrix[2][2] = -(z_near + z_far)/(z_far - z_near)\n perspective_matrix[2][3] = -1.0;\n perspective_matrix[3][2] = -2*z_near*z_far/(z_far - z_near)\n\n return perspective_matrix\n\n# Create program\npc_program = gloo.Program(vert_shader, frag_shader)\nline_program = gloo.Program(vert_shader, frag_shader_line)\n\n# Load uniforms\npc_program['modelview'] = lookat(np.array([0.05, 0, 0.3]), np.array([6, 0, 0]), np.array([0, 0, 1])) \npc_program['radius'] = .03\n\nline_program['modelview'] = lookat(np.array([0.05, 0, 0.3]), np.array([6, 0, 0]), np.array([0, 0, 1])) \nline_program['radius'] = .03\n\ndef load_point_cloud(filename):\n # Load point cloud\n with open(filename, \"r\") as f:\n lidar = []\n lidar_color = []\n for line in f.readlines():\n values = [float(x) for x in line.split(',')]\n lidar.append(values[:3])\n lidar_color.append(values[3:])\n lidar = np.array(lidar)\n lidar_color = np.array(lidar_color)\n\n pc_program._attributes['pos']._data = None \n pc_program._attributes['color']._data = None \n pc_program._attributes['pos'].set_data(lidar) \n pc_program._attributes['color'].set_data(lidar_color) \n\n# Load line data\ndef load_line_data(filename):\n with open(filename, \"r\") as f:\n line_coords = []\n line_colors = []\n for line in f.readlines():\n values = [float(x) for x in line.split(',')]\n line_coords.append((values[0], values[1], values[2]))\n line_coords.append((values[3], values[4], values[5]))\n line_colors.append((values[6], values[7], values[8]))\n line_colors.append((values[6], values[7], values[8]))\n \n line_program._attributes['pos']._data = None \n line_program._attributes['color']._data = None \n line_program._attributes['pos'].set_data(line_coords)\n line_program._attributes['color'].set_data(line_colors) \n\nwindow = app.Window(width=1280, height=720)\n\ndirectory = 'detection/'\nboard_directory = directory + 'boards/'\npoints_directory = directory + 'points/'\n\nboard_filenames = sorted(os.listdir(board_directory))\npoints_filenames = sorted(os.listdir(points_directory))\n\nboard_filenames.sort(key=len)\npoints_filenames.sort(key=len)\n\nfile_ind = 0\n\n#load_point_cloud(points_directory + points_filenames[file_ind])\n#load_line_data(board_directory + board_filenames[file_ind])\n#file_ind += 1\npc_program['pos'] = np.zeros((133632, 3)) \npc_program['color'] = np.zeros((133632, 3))\n\nline_program['pos'] = np.zeros((133632, 3)) \nline_program['color'] = np.zeros((133632, 3))\n\n@window.timer(0.05)\ndef timer(dt):\n global file_ind\n load_point_cloud(points_directory + points_filenames[file_ind])\n load_line_data(board_directory + board_filenames[file_ind])\n if file_ind < len(board_filenames) - 1:\n file_ind += 1\n\n@window.event\ndef on_resize(width, height):\n ratio = width / float(height)\n\n # Load projection matrix\n pc_program['projection'] = perspective(45.0, ratio, 0.1, 100.0)\n line_program['projection'] = perspective(45.0, ratio, 0.1, 100.0)\n\n@window.event\ndef on_draw(dt):\n window.clear()\n gl.glEnable(gl.GL_DEPTH_TEST)\n gl.glEnable(gl.GL_PROGRAM_POINT_SIZE)\n gl.glLineWidth(30.0)\n pc_program.draw(mode=gl.GL_POINTS)\n line_program.draw(mode=gl.GL_LINES)\n\n@window.event\ndef on_mouse_drag(x, y, dx, dy, buttons):\n # Rotate about z axis\n a = dx * 0.01\n rot = np.zeros((4, 4))\n rot[0][0] = math.cos(a)\n rot[0][1] = math.sin(a) \n rot[1][0] = -math.sin(a)\n rot[1][1] = math.cos(a)\n rot[2][2] = math.cos(a) + (1.0 - math.cos(a)) \n \n rot[3][3] = 1\n pc_program['modelview'] = np.dot(rot, pc_program['modelview'].reshape((4, 4))) \n line_program['modelview'] = np.dot(rot, pc_program['modelview'].reshape((4, 4)))\n\n# Run the app\napp.run()\n\n","sub_path":"detection_play.py","file_name":"detection_play.py","file_ext":"py","file_size_in_byte":8362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"60965073","text":"import numpy as np\nimport DNN\nimport matplotlib.pyplot as plt\n\ndef split_data (data, train_ratio):\n if train_ratio < 0 or train_ratio > 1:\n raise Exception()\n end_range = round(train_ratio * len(data))\n return data[0:end_range], data[end_range:-1]\n\ndef train_model (network, X, Y, batch_size, possible_categories, suppress_output = True):\n if len(X) != len(Y):\n raise Exception()\n deltas_weights = []\n deltas_bias = []\n for layer in network.layers:\n deltas_weights.append(np.zeros(np.shape(layer.weight_matrix.cells)))\n deltas_bias.append(np.zeros(np.shape(layer.bias_vector.cells)))\n starting_observation_index = 0\n batch_number = 0\n while starting_observation_index < len(X):\n observations_for_training = batch_size\n if len(X) - starting_observation_index < batch_size:\n observations_for_training = len(X) - starting_observation_index\n\n total_loss = 0\n num_correct = 0\n for observation, label in zip(X[starting_observation_index:starting_observation_index + observations_for_training],\\\n Y[starting_observation_index:starting_observation_index + observations_for_training]): \n observation_flattened = np.reshape(observation, (-1,1))\n observation_flattened = observation_flattened/255\n pre_activations, post_activations = network.forward_propagation (observation_flattened)\n predicted_probs = post_activations[-1]\n if np.argmax(predicted_probs) == label:\n num_correct += 1\n total_loss += network.get_loss(possible_categories, label, predicted_probs)\n weight_changes, bias_changes = network.backward_propagate_and_update(label, possible_categories, predicted_probs, observation_flattened)\n layer = 0\n for weight_change, bias_change in zip(weight_changes, bias_changes):\n deltas_weights[layer] += weight_changes[layer]\n deltas_bias[layer] += bias_changes[layer]\n layer += 1\n if not suppress_output:\n print(\"Batch number: {}, Batch size: {}, Accuracy: {}%, Average Loss {}\".format(batch_number, observations_for_training, num_correct/observations_for_training*100, total_loss/observations_for_training))\n #CONTINUE WORK BY AGGREGATING AND UPDATING DELTAS IN BATCHES\n #now just need to add the aggregated deltas to the layers\n network.update_with_deltas(deltas_weights, deltas_bias)\n starting_observation_index += observations_for_training\n batch_number += 1\n network.display_weights()\n\ndef test_model(network, X, Y, possible_categories): #forward propagate without updates\n num_correct = 0\n total_loss = 0\n for features, label in zip(X,Y):\n features_flattened = np.reshape(features, (-1,1))\n pre_activations, post_activations = network.forward_propagation (features_flattened)\n predicted_probs = post_activations[-1]\n if np.argmax(predicted_probs) == label:\n num_correct += 1\n \"\"\"else: #uncomment to show wrong classifications\n plt.imshow(features, cmap='gray')\n plt.title(\"predicted: {}, actual: {}\".format(np.argmax(predicted_probs), label))\n plt.show()\"\"\"\n total_loss += network.get_loss(possible_categories, label, predicted_probs)\n accuracy = num_correct/len(X)\n average_loss = total_loss/len(X)\n return accuracy, average_loss\n\n\n\n\nif __name__ == \"__main__\":\n dnn = DNN.DNN(\"multiclass_cross_entropy\", 0.01)\n input_template = np.array([1,2,3,4,5,6,7,8])\n input1 = input_template * 2\n input2 = input_template * np.random.random(8)\n features_matrix = np.array(np.random.randn(6,8))\n labels_matrix = np.random.randint(1,4,(6,1))\n possible_categories = np.array([1,2,3])\n dnn.add_layer(8,\"relu\",8)\n dnn.add_layer(3, \"sigmoid\")\n\n pre_train_weights = []\n for layer in dnn.layers:\n pre_train_weights.append(layer.weight_matrix.cells)\n train_model(dnn, features_matrix[0:4], labels_matrix[0:4], 2, possible_categories, suppress_output = False)\n accuracy, average_loss = test_model(dnn, features_matrix[4:], labels_matrix[4:], possible_categories)\n print(\"accuracy: {}, average loss: {}\".format(accuracy, average_loss))\n\n\n post_train_weights = []\n for layer in dnn.layers:\n post_train_weights.append(layer.weight_matrix.cells)\n\n\n\n","sub_path":"train_and_test_DNN.py","file_name":"train_and_test_DNN.py","file_ext":"py","file_size_in_byte":4453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"410900109","text":"'''\nThis script writes SLURM job files.\n'''\nimport os\nimport sys\nimport argparse\nsys.path.append(os.getenv('S2STOOL'))\nfrom s2s_modules.shared import utils\n\nPARSER = argparse.ArgumentParser()\nPARSER.add_argument('-f', '--JOBFILE', required=False, help='job file name')\nPARSER.add_argument('-t', '--NTASKS', required=False, help='NTASKS')\nPARSER.add_argument('-c', '--CONFIGFILE', required=False, help='config file name')\nPARSER.add_argument('-H', '--HOURS', required=False, help='time HOURS')\nPARSER.add_argument('-j', '--JOBNAME', required=False, help='job-name')\nPARSER.add_argument('-w', '--CWD', required=False, help='current working directory')\nPARSER.add_argument('-m', '--MYID', required=False, help='my job id')\nPARSER.add_argument('-a', '--AFTERID', required=False, help='after id')\nPARSER.add_argument('-s', '--SCHEDULE_FILE', required=False, help='schedule file')\nPARSER.add_argument('-r', '--REPORT', required=False, help='print report')\nPARSER.add_argument('-d', '--YYYYMMDIR', required=False, help='yyyymm directory')\n\nARGS = PARSER.parse_args()\nREPORT = ARGS.REPORT\nif REPORT is not None:\n CWD = ARGS.CWD\n YYYYMMDIR = ARGS.YYYYMMDIR\n utils.print_status_report (CWD, YYYYMMDIR)\n sys.exit()\n\nNTASKS = ARGS.NTASKS\nJOBFILE = ARGS.JOBFILE\n\nif NTASKS is None:\n SCHEDULE_FILE = ARGS.SCHEDULE_FILE\n MYID = ARGS.MYID\n AFTERID = ARGS.AFTERID\n utils.update_job_schedule(SCHEDULE_FILE, MYID, JOBFILE, AFTERID)\nelse:\n CONFIGFILE = ARGS.CONFIGFILE\n HOURS = ARGS.HOURS\n JOBNAME = ARGS.JOBNAME\n CWD = ARGS.CWD\n utils.job_script(CONFIGFILE, JOBFILE, JOBNAME, NTASKS, str(HOURS), CWD)\n","sub_path":"lis/utils/usaf/s2s/s2s_app/write_to_file.py","file_name":"write_to_file.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"59706140","text":"\"\"\"\nDefaults module.\nThis module is automatically loaded with variables defined in\nconf/ocsci/default_config.yaml in its DEFAULTS section.\nIf the variable can be used in some config file sections from ocsci/config.py\nmodule, plese put your defaults rather to mentioned default_config.yaml file!\nSee the documentation in conf/README.md file to understand this config file.\nPYTEST_DONT_REWRITE - avoid pytest to rewrite, keep this msg here please!\n\"\"\"\nimport os\n\nfrom ocs import constants\nfrom utility.templating import load_yaml_to_dict\n\nSTORAGE_API_VERSION = 'storage.k8s.io/v1'\nROOK_API_VERSION = 'ceph.rook.io/v1'\nOCP_API_VERSION = 'project.openshift.io/v1'\nOPENSHIFT_REST_CLIENT_API_VERSION = 'v1'\n\n# Those variables below are duplicate at the moment from default_config.yaml\n# and once we drop support for old runner we will remove those variables from\n# here and will have them defined only on one place.\n\n# Be aware that variables defined above and below are not used anywhere in the\n# config files and their sections when we rendering config!\n\nINSTALLER_VERSION = '4.1.2'\nCLIENT_VERSION = INSTALLER_VERSION\nAWS_REGION = 'us-east-2'\nROOK_CLUSTER_NAMESPACE = 'openshift-storage'\nKUBECONFIG_LOCATION = 'auth/kubeconfig' # relative from cluster_dir\nCLUSTER_NAME = \"ocs-ci\"\nAPI_VERSION = \"v1\"\nCEPH_IMAGE = \"ceph/ceph:v14\"\nROOK_IMAGE = \"rook/ceph:master\"\nDEPLOYMENT_PLATFORM = 'AWS'\n\n# This section is suppose to be available just from ocsci/config.py module from\n# ENV_DATA dictionary. Once we drop support of old runner we will delete this\n# data from here as well.\nENV_DATA = {\n 'platform': DEPLOYMENT_PLATFORM,\n 'cluster_name': CLUSTER_NAME,\n 'cluster_namespace': ROOK_CLUSTER_NAMESPACE,\n 'region': AWS_REGION,\n 'ceph_image': CEPH_IMAGE,\n 'rook_image': ROOK_IMAGE,\n}\n\nDEPLOYMENT = {\n 'installer_version': INSTALLER_VERSION,\n}\n\nREPORTING = {\n 'email': {\n 'address': 'ocs-ci@redhat.com',\n },\n 'polarion': {\n 'project_id': 'OpenShiftContainerStorage',\n }\n}\n\nRUN = {\n 'log_dir': '/tmp',\n 'run_id': None,\n 'kubeconfig_location': 'auth/kubeconfig',\n 'cli_params': {},\n 'client_version': DEPLOYMENT['installer_version'],\n 'bin_dir': './bin',\n}\n\nTEMP_YAML = os.path.join(constants.TEMPLATE_DIR, \"temp.yaml\")\n\nTOOL_POD_DICT = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_DEPLOYMENT_DIR, \"toolbox_pod.yaml\"\n )\n)\nCEPHFILESYSTEM_DICT = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_FS_DIR, \"CephFileSystem.yaml\"\n )\n)\nCEPHBLOCKPOOL_DICT = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_DEPLOYMENT_DIR, \"cephblockpool.yaml\"\n )\n)\nCSI_RBD_STORAGECLASS_DICT = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_RBD_DIR, \"storageclass.yaml\"\n )\n)\nCSI_CEPHFS_STORAGECLASS_DICT = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_FS_DIR, \"storageclass.yaml\"\n )\n)\nCSI_PVC_DICT = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_PV_PVC_DIR, \"PersistentVolumeClaim.yaml\"\n )\n)\nCSI_RBD_POD_DICT = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_RBD_DIR, \"pod.yaml\"\n )\n)\nCSI_RBD_SECRET = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_RBD_DIR, \"secret.yaml\"\n )\n)\nCSI_CEPHFS_SECRET = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_FS_DIR, \"secret.yaml\"\n )\n)\n\nCSI_CEPHFS_STORAGECLASS_DICT = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_FS_DIR, \"storageclass.yaml\"\n )\n)\n\nCSI_CEPHFS_PVC = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_FS_DIR, \"pvc.yaml\"\n )\n)\n\nCSI_RBD_PVC = load_yaml_to_dict(\n os.path.join(\n constants.TEMPLATE_CSI_RBD_DIR, \"pvc.yaml\"\n )\n)\n","sub_path":"ocs/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"369068178","text":"\"\"\"\nMini-application: Buttons on a Tkinter GUI tell the robot to:\n - Go forward at the speed given in an entry box.\n\nThis module runs on your LAPTOP.\nIt uses MQTT to SEND information to a program running on the ROBOT.\n\nAuthors: David Mutchler, his colleagues, and Myon McGee.\n\"\"\"\n# ------------------------------------------------------------------------------\n# done: 1. PUT YOUR NAME IN THE ABOVE LINE.\n# ------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------\n\nimport tkinter\nfrom tkinter import ttk\nimport mqtt_remote_method_calls as com\n\n\ndef main():\n \"\"\" Constructs and runs a GUI for this program. \"\"\"\n root = tkinter.Tk()\n mqtt_client = com.MqttClient()\n mqtt_client.connect_to_ev3()\n\n setup_gui(root, mqtt_client)\n\n root.mainloop()\n\ndef setup_gui(root_window, user):\n\n \"\"\" Constructs and sets up widgets on the given window. \"\"\"\n frame = ttk.Frame(root_window, padding=100)\n frame.grid()\n\n speed_entry_box = ttk.Entry(frame)\n backward_entry_box = ttk.Entry(frame)\n left_entry_box = ttk.Entry(frame)\n right_entry_box = ttk.Entry(frame)\n speed_button = ttk.Button(frame, text=\"Forward\")\n backward_botton = ttk.Button(frame, text=\"Backward\")\n left_botton = ttk.Button(frame, text=\"Left\")\n right_botton = ttk.Button(frame, text=\"Right\")\n label = ttk.Label(frame, text=\"The Racer\")\n entry_box = ttk.Entry(frame)\n\n label.grid()\n backward_entry_box.grid()\n backward_botton.grid()\n left_entry_box.grid()\n left_botton.grid()\n right_entry_box.grid()\n right_botton.grid()\n speed_entry_box.grid()\n speed_button.grid()\n entry_box.grid()\n\n speed_button['command'] = \\\n lambda: handle_go_forward(user, speed_entry_box)\n backward_botton['command'] = \\\n lambda: backwards(user, backward_entry_box)\n left_botton['command'] = \\\n lambda: lefts(user, left_entry_box)\n right_botton['command'] = \\\n lambda: rights(user, right_entry_box)\n\n root_window.bind_all('', lambda event: handle_go_forward(user, speed_entry_box))\n root_window.bind_all('', lambda event: backwards(user, backward_entry_box))\n root_window.bind_all('', lambda event: lefts(user, left_entry_box))\n root_window.bind_all('', lambda event: rights(user, right_entry_box))\n root_window.bind_all('', lambda event: boost(user, speed_entry_box))\n root_window.bind_all('', lambda event: stop(user))\n root_window.bind_all('', lambda event: lifts(user))\n root_window.bind_all('', lambda event: drops(user))\n\n root_window.mainloop()\n\ndef stop(mqtt_client):\n\n mqtt_client.send_message('stopper')\n\ndef lifts(mqtt_client):\n\n mqtt_client.send_message('lift')\n\ndef drops(mqtt_client):\n\n mqtt_client.send_message('drop')\n\n\ndef boost(mqtt_client, speed_input):\n\n speed_string = speed_input.get()\n mqtt_client.send_message('booster', [speed_string])\n\n\ndef handle_go_forward(mqtt_client, speed_input):\n\n speed_string = speed_input.get()\n mqtt_client.send_message('forward', [speed_string])\n\n\ndef backwards(mqtt_client, speed_input):\n\n speed_string = speed_input.get()\n mqtt_client.send_message('backward', [speed_string])\n\n\ndef lefts(mqtt_client, speed_input):\n speed_string = speed_input.get()\n mqtt_client.send_message('left', [speed_string])\n\n\ndef rights(mqtt_client, speed_input):\n speed_string = speed_input.get()\n mqtt_client.send_message('right', [speed_string])\n\n\nmain()\n","sub_path":"src/capstone_3_runs_on_laptop.py","file_name":"capstone_3_runs_on_laptop.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"544934559","text":"#!/usr/bin/python\n\n\"\"\"\nUtilities to convert AFTER relations into TimeML format and compute the scoring using TimeML tools.\n\"\"\"\n\nimport logging\nimport os\nimport subprocess\nfrom xml.dom import minidom\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element, SubElement\n\nfrom config import Config\nfrom utils import TransitiveGraph\nimport utils\n\nlogger = logging.getLogger(__name__)\n\n\ndef validate(nuggets, edges_by_type):\n \"\"\"\n Validate whether the edges are valid. Currently, the validation only check whether the reverse is also included,\n which is not possible for after links.\n :param nuggets: The set of possible nuggets.\n :param edges: Edges in the system.\n :return:\n \"\"\"\n for name, edges in edges_by_type.iteritems():\n reverse_edges = set()\n\n for edge in edges:\n left, right, t = edge\n\n if left not in nuggets:\n logger.error(\"Relation contains unknown event %s.\" % left)\n if right not in nuggets:\n logger.error(\"Relation contains unknown event %s.\" % right)\n\n if edge in reverse_edges:\n logger.error(\"There is a link from %s to %s and %s to %s, this is not allowed.\"\n % (left, right, right, left))\n return False\n reverse_edges.add((right, left, t))\n\n return True\n\n\ndef make_event(parent, eid):\n event = SubElement(parent, \"EVENT\")\n event.set(\"eid\", eid)\n\n\ndef create_root():\n timeml = Element('TimML')\n timeml.set(\"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\")\n timeml.set(\"xsi:noNamespaceSchemaLocation\", \"http://timeml.org/timeMLdocs/TimeML_1.2.1.xsd\")\n\n # Add a dummy DCT (document creation time).\n dct = SubElement(timeml, \"DCT\")\n timex3 = SubElement(dct, \"TIMEX3\")\n timex3.set(\"tid\", \"t0\")\n timex3.set(\"type\", \"TIME\")\n timex3.set(\"value\", \"\")\n timex3.set(\"temporalFunction\", \"false\")\n timex3.set(\"functionInDocument\", \"CREATION_TIME\")\n\n return timeml\n\n\ndef convert_links(links_by_name):\n all_converted = {}\n for name, links in links_by_name.iteritems():\n converted = []\n for l in links:\n relation_name = convert_name(l[2])\n converted.append((l[0], l[1], relation_name))\n all_converted[name] = converted\n\n return all_converted\n\n\ndef convert_name(name):\n \"\"\"\n Convert the Event Sequencing names to an corresponding TimeML name for evaluation.\n Note that, the meaning of After in event sequencing is different from TimeML specification.\n\n In Event Sequencing task, E1 --after--> E2 represent a directed link, where the latter one happens later. In TIMEML,\n E1 --after--> E2 actually says E1 is after E2. So we use the BEFORE tag instead.\n\n This conversion is just for the sake of logically corresponding, in fact, converting to \"BEFORE\" and \"AFTER\" will\n produce the same scores.\n\n In addiction, in TIMEML, there is no definition for Subevent, but \"INCLUDES\" have a similar semantic with that.\n\n :param name:\n :return:\n \"\"\"\n if name == \"After\":\n return \"BEFORE\"\n elif name == \"Subevent\":\n return \"INCLUDES\"\n else:\n logger.warn(\"Unsupported relations name %s found.\" % name)\n\n\ndef pretty_xml(element):\n \"\"\"\n Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ElementTree.tostring(element, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\" \")\n\n\ndef find_equivalent_sets(clusters, nuggets):\n nodes = [nugget[2] for nugget in nuggets]\n\n node_2_set = {}\n set_2_nodes = {}\n non_singletons = set()\n\n set_id = 0\n\n for cluster in clusters:\n for element in cluster[2]:\n node_2_set[element] = set_id\n non_singletons.add(element)\n\n try:\n set_2_nodes[set_id].append(element)\n except KeyError:\n set_2_nodes[set_id] = [element]\n\n set_id += 1\n\n for node in nodes:\n if node not in non_singletons:\n node_2_set[node] = set_id\n try:\n set_2_nodes[set_id].append(node)\n except KeyError:\n set_2_nodes[set_id] = [node]\n\n set_id += 1\n\n return set_2_nodes, node_2_set\n\n\ndef propagate_through_equivalence(links_by_name, equivalent_links, nuggets):\n set_2_nodes, node_2_set = find_equivalent_sets(equivalent_links, nuggets)\n\n all_expanded_links = {}\n\n all_set_links = {}\n\n for name, links in links_by_name.iteritems():\n set_links = []\n\n for link in links:\n relation = link[0]\n arg1, arg2 = link[2]\n set_links.append((node_2_set[arg1], node_2_set[arg2], relation))\n\n reduced_set_links = compute_reduced_graph(set_links)\n\n expanded_links = set()\n\n for link in reduced_set_links:\n arg1, arg2, relation = link\n\n for node1 in set_2_nodes[arg1]:\n for node2 in set_2_nodes[arg2]:\n expanded_links.add((node1, node2, relation))\n\n all_expanded_links[name] = list(expanded_links)\n all_set_links[name] = list(all_set_links)\n\n return all_expanded_links, all_set_links\n\n\ndef compute_reduced_graph(set_links):\n node_indices = utils.get_nodes(set_links)\n\n graph = TransitiveGraph(len(node_indices))\n\n for arg1, arg2, relation in set_links:\n node_index1 = node_indices[arg1]\n node_index2 = node_indices[arg2]\n graph.add_edge(node_index1, node_index2)\n\n closure_matrix = graph.transitive_closure()\n\n indirect_links = set()\n\n for from_node, to_nodes in enumerate(closure_matrix):\n for to_node, reachable in enumerate(to_nodes):\n if from_node != to_node and reachable == 1:\n for indirect_node, indirect_reachable in enumerate(closure_matrix[to_node]):\n if indirect_node != to_node:\n if indirect_reachable == 1:\n indirect_links.add((from_node, indirect_node))\n\n reduced_links = []\n\n for arg1, arg2, relation in set_links:\n node_index1 = node_indices[arg1]\n node_index2 = node_indices[arg2]\n\n if (node_index1, node_index2) not in indirect_links:\n reduced_links.append((arg1, arg2, relation))\n\n return reduced_links\n\n\nclass TemporalEval:\n \"\"\"\n This class help us converting the input into TLINK format and evaluate them using the temporal evaluation tools\n developed by UzZaman. We use the variation of their method that use both the reduced graph and rewarding\n un-inferable implicit relations.\n\n Reference:\n Interpreting the Temporal Aspects of Language, Naushad UzZaman, 2012\n \"\"\"\n\n def __init__(self, doc_id, g2s_mapping, gold_nuggets, gold_links, sys_nuggets, sys_links, gold_corefs, sys_corefs):\n gold_links_by_type, gold_cluster_links = propagate_through_equivalence(gold_links, gold_corefs, gold_nuggets)\n sys_links_by_type, sys_cluster_links = propagate_through_equivalence(sys_links, sys_corefs, gold_nuggets)\n\n self.possible_types = gold_links_by_type.keys()\n\n self.normalized_system_nodes = {}\n self.normalized_gold_nodes = {}\n\n self.gold_nuggets = gold_nuggets\n self.sys_nuggets = sys_nuggets\n\n self.gold_nodes = []\n self.sys_nodes = []\n\n self.store_nodes(g2s_mapping)\n\n if not Config.no_temporal_validation:\n if not validate(set([nugget[2] for nugget in gold_nuggets]), gold_links_by_type):\n raise RuntimeError(\"The gold standard edges cannot form a valid temporal graph.\")\n\n if not validate(set([nugget[2] for nugget in sys_nuggets]), sys_links_by_type):\n raise RuntimeError(\"The system edges cannot form a valid temporal graph.\")\n\n self.gold_time_ml = self.make_all_time_ml(convert_links(gold_links_by_type), self.normalized_gold_nodes,\n self.gold_nodes)\n self.sys_time_ml = self.make_all_time_ml(convert_links(sys_links_by_type), self.normalized_system_nodes,\n self.sys_nodes)\n\n self.gold_cluster_time_ml = self.make_all_time_ml(convert_links(gold_cluster_links), self.normalized_gold_nodes,\n self.gold_nodes)\n self.sys_cluster_time_ml = self.make_all_time_ml(convert_links(sys_cluster_links), self.normalized_system_nodes,\n self.sys_nodes)\n\n self.doc_id = doc_id\n\n def write_time_ml(self):\n \"\"\"\n Write the TimeML file to disk.\n :return:\n \"\"\"\n self.write(self.gold_time_ml, Config.temporal_gold_dir)\n self.write(self.sys_time_ml, Config.temporal_sys_dir)\n\n self.write(self.gold_cluster_time_ml, Config.temporal_gold_dir + \"_cluster\")\n self.write(self.sys_cluster_time_ml, Config.temporal_sys_dir + \"_cluster\")\n\n def write(self, time_ml_data, subdir):\n \"\"\"\n Write out time ml files into sub directories.\n :param time_ml_data:\n :param time_ml_dir:\n :param subdir:\n :return:\n \"\"\"\n for name, time_ml in time_ml_data.iteritems():\n output_dir = os.path.join(Config.temporal_result_dir, name, subdir)\n\n if not os.path.isdir(output_dir):\n utils.supermakedirs(output_dir)\n\n temp_file = open(os.path.join(output_dir, \"%s.tml\" % self.doc_id), 'w')\n temp_file.write(pretty_xml(time_ml))\n temp_file.close()\n\n @staticmethod\n def eval_time_ml():\n logger.info(\"Running TimeML scorer.\")\n\n for link_type in os.listdir(Config.temporal_result_dir):\n temporal_output = os.path.join(Config.temporal_result_dir, link_type, Config.temporal_out)\n\n gold_sub_dir = os.path.join(Config.temporal_result_dir, link_type, Config.temporal_gold_dir)\n sys_sub_dir = os.path.join(Config.temporal_result_dir, link_type, Config.temporal_sys_dir)\n\n with open(temporal_output, 'wb', 0) as out_file:\n subprocess.call([\"python\", Config.temp_eval_executable, gold_sub_dir, sys_sub_dir,\n '0', \"implicit_in_recall\"], stdout=out_file)\n\n temporal_output = os.path.join(Config.temporal_result_dir, link_type, Config.temporal_out + \"_cluster\")\n\n gold_sub_dir = os.path.join(Config.temporal_result_dir, link_type, Config.temporal_gold_dir + \"_cluster\")\n sys_sub_dir = os.path.join(Config.temporal_result_dir, link_type, Config.temporal_sys_dir + \"_cluster\")\n\n with open(temporal_output, 'wb', 0) as out_file:\n subprocess.call([\"python\", Config.temp_eval_executable, gold_sub_dir, sys_sub_dir,\n '0', \"implicit_in_recall\"], stdout=out_file)\n\n @staticmethod\n def get_eval_output():\n temporal_output = os.path.join(Config.temporal_result_dir, Config.temporal_out)\n with open(temporal_output, 'r') as f:\n score_line = False\n for l in f:\n if score_line:\n prec, recall, f1 = [float(x) for x in l.strip().split(\"\\t\")]\n return prec, recall, f1\n\n if l.startswith(\"Temporal Score\"):\n score_line = True\n\n def store_nodes(self, e_mapping):\n mapped_system_mentions = set()\n\n tid = 0\n for gold_index, (system_index, _) in enumerate(e_mapping):\n node_id = \"te%d\" % tid\n tid += 1\n\n gold_temporal_instance_id = self.gold_nuggets[gold_index][2]\n self.normalized_gold_nodes[gold_temporal_instance_id] = node_id\n self.gold_nodes.append(node_id)\n\n if system_index != -1:\n system_temporal_instance_id = self.sys_nuggets[system_index][2]\n self.normalized_system_nodes[system_temporal_instance_id] = node_id\n self.sys_nodes.append(node_id)\n mapped_system_mentions.add(system_index)\n\n for system_index, system_nugget in enumerate(self.sys_nuggets):\n if system_index not in mapped_system_mentions:\n node_id = \"te%d\" % tid\n tid += 1\n\n system_temporal_instance_id = system_nugget[2]\n self.normalized_system_nodes[system_temporal_instance_id] = node_id\n self.sys_nodes.append(node_id)\n\n def make_all_time_ml(self, links_by_name, normalized_nodes, nodes):\n all_time_ml = {}\n\n all_links = []\n\n for name in self.possible_types:\n if name in links_by_name:\n links = links_by_name[name]\n all_time_ml[name] = self.make_time_ml(links, normalized_nodes, nodes)\n all_links.extend(links)\n else:\n all_time_ml[name] = self.make_time_ml([], normalized_nodes, nodes)\n\n all_time_ml[\"All\"] = self.make_time_ml(all_links, normalized_nodes, nodes)\n\n return all_time_ml\n\n def make_time_ml(self, links, normalized_nodes, nodes):\n # Create the root.\n time_ml = create_root()\n # Add TEXT.\n self.annotate_timeml_events(time_ml, nodes)\n\n # Add instances.\n self.create_instance(time_ml, nodes)\n self.create_tlinks(time_ml, links, normalized_nodes)\n\n return time_ml\n\n def create_instance(self, parent, nodes):\n for node in nodes:\n instance = SubElement(parent, \"MAKEINSTANCE\")\n instance.set(\"eiid\", \"instance_\" + node)\n instance.set(\"eid\", node)\n\n def annotate_timeml_events(self, parent, nodes):\n text = SubElement(parent, \"TEXT\")\n for tid in nodes:\n make_event(text, tid)\n\n def create_tlinks(self, time_ml, links, normalized_nodes):\n lid = 0\n\n for left, right, relation_type in links:\n if left not in normalized_nodes:\n logger.error(\"Node %s is not a event mention.\" % left)\n continue\n\n if right not in normalized_nodes:\n logger.error(\"Node %s is not a event mention.\" % right)\n continue\n\n normalized_left = normalized_nodes[left]\n normalized_right = normalized_nodes[right]\n\n link = SubElement(time_ml, \"TLINK\")\n link.set(\"lid\", \"l%d\" % lid)\n link.set(\"relType\", relation_type)\n link.set(\"eventInstanceID\", normalized_left)\n link.set(\"relatedToEventInstance\", normalized_right)\n","sub_path":"temporal.py","file_name":"temporal.py","file_ext":"py","file_size_in_byte":14616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"649982434","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 22 06:28:19 2019\r\n\r\n@author: kkosc\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport wikipedia as wp\r\n\r\n#read and scrape the table from Wikipedia\r\nhtml = wp.page(\"List of postal codes of Canada: M\").html().encode(\"UTF-8\")\r\ndf = pd.read_html(html)[0]\r\n\r\n#adjust the data in the dataframe to our specifications\r\ndf = df[df.Borough != 'Not assigned']\r\ndf = df.groupby(['Postcode','Borough'])['Neighbourhood'].apply(', '.join).reset_index()\r\ndf = df.replace(to_replace='Not assigned', value='Queen\\'s Park')\r\n\r\n#add latitude and longitude to the dataframe\r\nlatlng = pd.read_csv('Geospatial_Coordinates.csv').reset_index()\r\ndel latlng['index']\r\ndel latlng['Postal Code']\r\ndf = df.join(latlng, sort=False)\r\n\r\n#print the dataframe and its size\r\nprint(df)\r\nprint(df.shape)","sub_path":"cluster_pandas_2.py","file_name":"cluster_pandas_2.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"639640449","text":"import csv\nfrom reportes.models import Analisis,Pais\n# mx-holanda_precios.csv\n# test_file.csv\n\nclass Uploader():\n\n def show_content(file_name): # Despliega el codigo de todos los analisis\n with open(file_name, mode='r', encoding=\"utf8\") as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n char_count = 0\n nombre_count = 0\n flag = True\n for row in csv_reader: # Por cada registro en el csv\n if line_count == 0:\n line_count += 1\n for c in row[\"DESCRIPCION\"]: # Por cada caracter en el campo de descripcion\n try:\n next_char = row[\"DESCRIPCION\"][char_count+1]\n except:\n next_char = 1\n char_count += 1\n if c == '-' and flag and next_char == '-':\n nombre_count = char_count\n flag = False\n\n if not flag:\n nombre = row[\"DESCRIPCION\"][0:nombre_count-1]\n descripcion = row[\"DESCRIPCION\"][nombre_count+1:char_count]\n else:\n nombre = ' - '\n descripcion = row[\"DESCRIPCION\"]\n\n\n\n char_count = 0\n nombre_count = 0\n flag = True\n #print(f'{row[\"CODIGO\"]} \\t {nombre} \\t {descripcion} \\t {row[\"PRECIO\"]} \\t {row[\"UNIDAD_MIN\"]} \\t {row[\"DIAS\"]} \\t {row[\"NOTAS\"]} \\t {row[\"ACREDITACION\"]} \\t {row[\"PAIS\"]}')\n print(\"Code: \"+row[\"CODIGO\"]+\"\\tNombre: \"+nombre+\"\\tDescripcion: \"+descripcion)\n line_count += 1\n print(f'Registros: {line_count-1}')\n\n def upload_content(file_name): # Sube todo el contenido del csv a la base de datos\n paises = {\n 'M' : Pais.objects.get(nombre=\"México\"),\n 'H' : Pais.objects.get(nombre=\"Holanda\"),\n 'G' : Pais.objects.get(nombre=\"Alemania\"),\n 'U' : Pais.objects.get(nombre=\"Estados Unidos\"),\n 'C' : Pais.objects.get(nombre=\"Canadá\"),\n 'I' : Pais.objects.get(nombre=\"IFC\"),\n 'O' : Pais.objects.get(nombre=\"IFC\"),\n 'A' : Pais.objects.get(nombre=\"IFC\"),\n }\n with open(file_name, mode='r', encoding=\"utf8\") as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n char_count = 0\n nombre_count = 0\n flag = True\n for row in csv_reader:\n print('Subiendo: '+row[\"CODIGO\"]+' ... ', end='')\n if line_count == 0:\n line_count += 1\n line_count += 1\n for c in row[\"DESCRIPCION\"]: # Por cada caracter en el campo de descripcion\n char_count += 1\n if c == '-' and flag: # Se busca el indice del arreglo donde está el primer guión\n nombre_count = char_count\n flag = False\n nombre = row[\"DESCRIPCION\"][0:nombre_count-1] # Se divide el nombre de la descripcion\n descripcion = row[\"DESCRIPCION\"][nombre_count+2:char_count]\n\n char_count = 0\n nombre_count = 0\n flag = True\n\n p = paises[row[\"CODIGO\"][0]] # Se obtiene el país del diccionario\n\n acred = False\n if row[\"ACREDITACION\"] == 'Q': # Se valida la acreditacion\n acred = True\n\n precio = row[\"PRECIO\"] # Si no tiene precio, se colocará un -1\n if precio == '':\n precio = -1\n\n dias = row[\"DIAS\"] + \" días\" # Se depura si en la columna no está el formato (# - #)\n if len(dias) > 10:\n dias = ' - '\n if dias == '':\n dias = ' - '\n\n\n if row[\"CODIGO\"][0] != \"I\": # Se depuran todos los registros de insumos\n a = Analisis( # Se crea el registro\n nombre=nombre,\n codigo=row[\"CODIGO\"],\n descripcion=descripcion,\n precio=precio,\n unidad_min=row[\"UNIDAD_MIN\"],\n tiempo=dias,\n pais=p,\n acreditacion=acred\n )\n a.save() # Se guarda el registro\n print(f'{row[\"CODIGO\"]} registrado exitosamente')\n else:\n print('Insumo detectado... '+row[\"CODIGO\"]+' DEPURADO')\n\n\n\n\n print(\"\\n\\nFINALIZADO\\n\\n\")\n","sub_path":"voyager/UploadData.py","file_name":"UploadData.py","file_ext":"py","file_size_in_byte":4824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"261389132","text":"# -*- coding: utf-8 -*-\n\nfrom scrapy import Spider, Request\nfrom scrapy_redis.spiders import RedisSpider\nfrom crawler.spiders.base import IndexSpider\nfrom crawler.consts import (SUB_INDEX_WORKER_KEY, LOWER_INDEX_WORKER_KEY,\n MIDDLE_LEVEL_ARTICLES_WORKER_KEY)\n\nfrom crawler.models import Site, SiteRule\n\nimport re\n# pylint: disable=E0611\nfrom article.models import Article\n# pylint: enable=E0611\n\n\nclass SubIndexSpider(IndexSpider, RedisSpider):\n\n name = 'subindex_worker'\n redis_key = SUB_INDEX_WORKER_KEY\n\n def parse(self, response):\n url = response.url\n links = self.extract_urls(response)\n article_urls = []\n site_name, index_title, category_name, article_patterns = SiteRule.get_rules_by_subindex_url(url)\n unusable_site = category_name in ['Photos', 'Videos']\n for link in links:\n for pattern in article_patterns:\n if re.match(pattern, link.url):\n article_urls.append(link.url)\n if article_urls:\n articles = Article.objects(source_url__in=article_urls)\n for article in articles:\n if category_name and category_name not in article.category:\n article.category.append(category_name)\n article.usable = False\n article.save()\n exsited_article_urls = [article.source_url for article in articles]\n new_urls = set(article_urls) - set(exsited_article_urls)\n if new_urls:\n Article.objects.insert([Article(source_url=article_url, source=index_title, \\\n site_name=site_name, site_url=url, usable=False, \\\n category=[category_name] if category_name else []) \\\n for article_url in set(new_urls)])\n\nclass LowerIndexSpider(IndexSpider, RedisSpider):\n\n name = 'lowerindex_worker'\n redis_key = LOWER_INDEX_WORKER_KEY\n\n def parse(self, response):\n url = response.url\n links = self.extract_urls(response)\n subindexes, article_urls = self.split_urls(url, links)\n self.discover_lowerindex(subindexes)\n","sub_path":"crawler/spiders/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"302729340","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 2 13:15:26 2020\n\n@author: zhen chen\n\nMIT Licence.\n\nPython version: 3.7\n\n\nDescription: draw contour in python\n \n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom matplotlib.colors import ListedColormap \nimport scipy\n\n\ndf = pd.read_csv(r'D:\\Users\\chen_\\git\\Stochastic-Inventory\\H.csv', index_col=0) \ndf.drop(df.columns[-1], axis=1, inplace = True)\n\ndf.columns = df.columns.astype(float)\nR0 = df.index.values\nx0 = df.columns.values\n\nR, x = np.meshgrid(R0, x0)\nG = df.values.astype(float)\n\ncolors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') \ncolors = ('white', 'lightgreen')\ncmap = ListedColormap(colors[:len(np.unique(G))]) \n\nplt.figure(figsize=(6.5,5), dpi = 50) # 设置清晰度\n#cp = plt.contourf(x, R, GA, 0, cmap = cmap) # cmap = cmap\nax = plt.contour(R, x, G.T, 0, colors='black', linewidths=1, linestyles='solid')\n\n#contour_line_values = np.stack(ax.allsegs[0])\n#x_values = contour_line_values[0][:, 0]\n#y_values = contour_line_values[0][:, 1]\n#d = y_values\n#plt.fill_between(x_values, y_values, interpolate=True, color='lightgreen')\n#plt.fill_between(np.arange(0, 50), np.ones(50), 30, interpolate=True, color='lightblue')\narr_x1 = ax.allsegs[1][0][0:8, 0]\narr_x2 = ax.allsegs[1][0][7:23, 0]\narr_y1 = ax.allsegs[1][0][0:8, 1]\narr_y2 = ax.allsegs[1][0][7:23, 1]\narr_y2_1 = 16.8 * np.ones((len(arr_x1)))\narr_y2_2 = 30 * np.ones((len(arr_x2)))\n#plt.fill_between([0, 3], [30, 30], [16.8, 16.8], hatch=\"X\", alpha=.99, facecolor=\"none\", linewidth = 1)\n#plt.fill_between(arr_x1, arr_y1, arr_y2_1, hatch=\"///\", alpha=.99, facecolor=\"none\", linewidth = 1)\n#plt.fill_between(arr_x2, arr_y2, arr_y2_2, hatch=\"///\", alpha=.99, facecolor=\"none\", linewidth = 1)\n\narr = ax.allsegs[1][0]\n\n#plt.text(-1.5, 7.5, '$s$', fontsize=8)\n#plt.text(2.7, -1.5, '$x_0$', color = 'red')\n#plt.plot([3, 3], [0, 16.8], 'r:')\n#plt.plot(0, 16.8, 'ro', markersize = 3)\n#plt.text(-0.7, 16.5, '$R_0$', color = 'red')\n##plt.colorbar(cp)\n#\nplt.xlabel('R')\n#plt.xticks([0, 5, 10, 15, 20])\nplt.ylabel('x')\nplt.savefig('J2.eps', format='eps')\n","sub_path":"draw-pictures/deaw_contour.py","file_name":"deaw_contour.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567877106","text":"import ioFunctions\nimport numpy as np\nfrom scipy import interpolate\nimport dipy\nimport s2cnn\nfrom scipy.interpolate import griddata\nfrom scipy.interpolate import NearestNDInterpolator\nfrom scipy.interpolate import LinearNDInterpolator\nfrom scipy.interpolate import SmoothSphereBivariateSpline\nfrom scipy.interpolate import LSQSphereBivariateSpline\nimport torch\nimport s2conv\nimport somemath\nimport matplotlib.pyplot as plt\n\nclass diff2d():\n def __init__(self):\n self.vox=[]\n self.signal=[]\n\n def loadData(self,dvol=None):\n if dvol is None:\n raise ValueError(\"please call with a diffVolume object\")\n img=dvol.vol.getData()\n shape=img.shape\n img=img.reshape((shape[0]*shape[1]*shape[2],shape[3]),order='F')\n\nclass dti():\n def __init__(self):\n self.FA=[]\n self.L1=[]\n self.L2=[]\n self.L3=[]\n self.V1=[]\n self.V2=[]\n self.V3=[]\n self.MD = []\n self.MO = []\n self.S0 = []\n self.mask= []\n\n def load(self,pathprefix):\n if pathprefix is None:\n raise ValueError(\"Please provide path including prefix for dti data, prefix=...\")\n self.FA = ioFunctions.loadgetVol(pathprefix+\"_FA.nii.gz\")\n self.L1 = ioFunctions.loadgetVol(pathprefix + \"_L1.nii.gz\")\n self.L2 = ioFunctions.loadgetVol(pathprefix + \"_L2.nii.gz\")\n self.L3 = ioFunctions.loadgetVol(pathprefix + \"_L3.nii.gz\")\n self.V1 = ioFunctions.loadgetVol(pathprefix + \"_V1.nii.gz\")\n self.V2 = ioFunctions.loadgetVol(pathprefix + \"_V2.nii.gz\")\n self.V3 = ioFunctions.loadgetVol(pathprefix + \"_V3.nii.gz\")\n\n #def y(self,p):\n # v=[]\n\n\n\nclass diffVolume():\n def __init__(self):\n \"\"\"\n Class for storing gridded volume data\n \"\"\"\n self.vol = []\n self.interpExists = 0\n self.interpolator = []\n self.bvals = []\n self.bvecs = []\n self.bvecs_hemi_cart=[]\n self.bvecs_hemi_sphere=[]\n self.inds= []\n self.gtab = []\n self.img=[]\n self.sgrad_x=[]\n self.sgrad_y = []\n self.sgrad_z = []\n self.current_signal=[]\n self.mask=[]\n\n\n def getVolume(self, folder=None):\n \"\"\"\n Gets volume data\n :param filename: Path of volume file\n :return:\n \"\"\"\n self.vol, self.gtab =ioFunctions.loadDiffVol(folder=folder)\n self.img = self.vol.get_data()\n self.mask = ioFunctions.loadVol(filename=folder+\"\\\\nodif_brain_mask.nii.gz\")\n\n def makeInterpolator(self):\n \"\"\"\n Makes a linear interpolator\n :return: Fills out self. interpolator and sets self.interpExists = 1 after interpolator is calculated\n \"\"\"\n shape = self.vol.shape\n print(shape)\n img = self.vol.get_data()\n #TODO other shapes like scalars most impot\n if len(shape) > 3:\n if shape[3] == 3:\n i = np.linspace(0, shape[0] - 1, num=shape[0])\n j = np.linspace(0, shape[1] - 1, num=shape[1])\n k = np.linspace(0, shape[2] - 1, num=shape[2])\n self.interpolator = [interpolate.RegularGridInterpolator((i, j, k), img[:, :, :, f]) for f in range(shape[3])]\n self.interpExists=1\n if shape[3]==1:\n i = np.linspace(0, shape[0] - 1, num=shape[0])\n j = np.linspace(0, shape[1] - 1, num=shape[1])\n k = np.linspace(0, shape[2] - 1, num=shape[2])\n self.interpolator = interpolate.RegularGridInterpolator((i, j, k), img[:, :, :,0])\n self.interpExists = 1\n else:\n i = np.linspace(0, shape[0] - 1, num=shape[0])\n j = np.linspace(0, shape[1] - 1, num=shape[1])\n k = np.linspace(0, shape[2] - 1, num=shape[2])\n self.interpolator = interpolate.RegularGridInterpolator((i, j, k), img[:, :, :])\n self.interpExists = 1\n\n def shells(self):\n tempbvals=[]\n tempbvals=np.round(self.gtab.bvals,-2)\n inds_sort=np.argsort(tempbvals)\n bvals_sorted=self.gtab.bvals[inds_sort]\n bvecs_sorted=self.gtab.bvecs[inds_sort]\n tempbvals=np.sort(tempbvals)\n gradbvals=np.gradient(tempbvals)\n inds_shell_cuts=np.where(gradbvals!=0)\n shell_cuts=[]\n for i in range(int(len(inds_shell_cuts[0]) / 2)):\n shell_cuts.append(inds_shell_cuts[0][i * 2])\n shell_cuts.insert(0,-1)\n shell_cuts.append(len(bvals_sorted))\n print(shell_cuts)\n print(bvals_sorted.shape)\n temp_bvals=[]\n temp_bvecs=[]\n temp_inds=[]\n for t in range(int(len(shell_cuts)-1)):\n print(shell_cuts[t]+1,shell_cuts[t + 1])\n temp_bvals.append(bvals_sorted[shell_cuts[t]+1:1+shell_cuts[t+1]])\n temp_bvecs.append(bvecs_sorted[shell_cuts[t]+1:1+shell_cuts[t+1]])\n temp_inds.append(inds_sort[shell_cuts[t]+1:1+shell_cuts[t+1]])\n self.bvals=temp_bvals\n self.bvecs=temp_bvecs\n self.inds=temp_inds\n self.inds=np.asarray(self.inds)\n\n\n pi=3.14159265\n for bvecs in self.bvecs: #this is shells\n temp_bvec = []\n temp_vec = []\n for bvec in bvecs: #this is each vector in shell\n r, theta, phi=dipy.core.sphere.cart2sphere(bvec[0],bvec[1],bvec[2])\n #if theta > pi/2: #this is the anitpodal port becareful whether this is on or off\n # theta= pi- theta\n # phi=phi+3.14159265\n phi=(phi)%(2*pi)\n x,y,z=dipy.core.sphere.sphere2cart(1,theta,phi)\n temp_vec.append([x,y,z])\n temp_bvec.append([r,theta,phi])\n self.bvecs_hemi_sphere.append(temp_bvec)\n self.bvecs_hemi_cart.append(temp_vec)\n self.bvecs_hemi_cart=np.asarray(self.bvecs_hemi_cart)\n self.bvecs_hemi_sphere=np.asarray(self.bvecs_hemi_sphere)\n\n def makeFlatHemisphere(self,p1,shell):\n s0 = []\n s1 = []\n th = []\n ph = []\n x=[]\n y=[]\n z=[]\n i = 0\n for ind in self.inds[shell]:\n x.append(self.bvecs_hemi_cart[shell][i][0])\n y.append(self.bvecs_hemi_cart[shell][i][1])\n z.append(self.bvecs_hemi_cart[shell][i][2])\n s1.append(self.img[p1[0], p1[1], p1[2], ind])\n th.append(self.bvecs_hemi_sphere[shell][i][1])\n ph.append(self.bvecs_hemi_sphere[shell][i][2])\n i = i + 1\n th = np.asarray(th)\n ph = np.asarray(ph)\n s1 = np.asarray(s1)\n x = np.asarray(x)\n y = np.asarray(y)\n z = np.asarray(z)\n\n\n for ind in self.inds[0]:\n s0.append(self.img[p1[0], p1[1], p1[2], ind])\n norm=sum(s0)/len(s0)\n\n\n thph=np.column_stack((th,ph))\n xyz = np.column_stack((x, y, z))\n #interpolator=LinearNDInterpolator(thph,1/s1)\n #interpolator = NearestNDInterpolator(thph, 1 / s1)\n interpolator = NearestNDInterpolator(xyz, s1/norm)\n #interpolator = LinearNDInterpolator(xyz, s1/norm)\n\n\n iso=somemath.isomesh()\n iso.get_icomesh()\n iso.makeFlat(interpolator)\n #print(interpolator(th,ph))\n return iso.s_flat\n\n def plotSignal(self,p1,shell):\n N=64\n sphere_sig=somemath.sphereSig()\n theta = np.linspace(0, np.pi, N)\n phi = np.linspace(0, 2 * np.pi, N)\n theta, phi = np.meshgrid(theta,phi)\n s1 = []\n th = []\n ph = []\n i=0\n for ind in self.inds[shell]:\n s1.append(self.img[p1[0], p1[1], p1[2], ind])\n th.append(self.bvecs_hemi_sphere[shell][i][1])\n ph.append(self.bvecs_hemi_sphere[shell][i][2])\n i = i + 1\n th = np.asarray(th)\n ph = np.asarray(ph)\n s1 = np.asarray(s1)\n print(s1)\n ss1 = griddata((th, ph), 1/s1, (theta, phi), method='nearest') # , fill_value=-1)\n sphere_sig.grid = np.real(ss1)\n sphere_sig.N=N\n #sphere_sig.plot()\n self.current_signal=sphere_sig\n plt.imshow(sphere_sig.grid)\n\n def conv(self,p1,p2,N,shellN,tN=None):\n \"\"\"\n :param p1: voxel 1 coordinates\n :param p2: voxel 2 coordinates\n :param N: size of convolution plane\n :param shellN: number of shells including b_0\n :return: SO(3) function\n \"\"\"\n #put functions on grid\n so3=s2conv.so3()\n so3.makeSo3(N,shellN)\n\n so3.signal1 = [somemath.sphereSig() for i in range(0, shellN)]\n so3.signal2 = [somemath.sphereSig() for i in range(0, shellN)]\n #so3=np.empty([N,N,N,2,shellN])\n theta = np.linspace(0, np.pi, N)\n phi = np.linspace(0, 2 * np.pi, N)\n ep=0.0001\n if tN==None:\n tN=10\n tt = np.linspace(ep, np.pi-ep, tN)\n tp = np.linspace(ep, 2 * np.pi-ep, tN)\n\n for shell in range(0,shellN):\n s1 = []\n s2 = []\n th = []\n ph = []\n i = 0\n for ind in self.inds[shell]:\n s1.append(self.img[p1[0], p1[1], p1[2], ind])\n s2.append(self.img[p2[0], p2[1], p2[2], ind])\n th.append(self.bvecs_hemi_sphere[shell][i][1])\n ph.append(self.bvecs_hemi_sphere[shell][i][2])\n i = i + 1\n th = np.asarray(th)\n ph = np.asarray(ph)\n s1 = np.asarray(s1)\n s2 = np.asarray(s2)\n b=int(N/2)\n ss1 = griddata((th, ph), 1/s1, (theta[None,:], phi[:,None]), method='nearest')#, fill_value=-1)\n ss2= griddata((th, ph), 1/s2, (theta[None,:], phi[:,None]), method='nearest')#,fill_value=-1)\n #lut_s1 = SmoothSphereBivariateSpline(th,ph,s1/s1.max(),s=0.6,eps=1e-8)\n #lut_s2 = SmoothSphereBivariateSpline(th, ph, s2/s2.max(),s=0.6,eps=1e-8)\n #lut_s1 = LSQSphereBivariateSpline(th, ph, s1 / s1.max(), tt,tp)#, eps=1e-8)\n #lut_s2 = LSQSphereBivariateSpline(th, ph, s2 / s2.max(), tt,tp)#, eps=1e-8)\n #ss1 = lut_s1(theta,phi)\n #ss2 = lut_s2(theta, phi)\n ss1=ss1/ss1.max()\n ss2 = ss2 / ss1.max()\n #ss1=somemath.parity_symmetrize(ss1)\n #ss2 = somemath.parity_symmetrize(ss2)\n\n\n sss1 = np.empty([N, N, 2])\n sss1[:, :, 0] = np.real(ss1)\n sss1[:, :, 1] = np.imag(ss1)\n\n sss2 = np.empty([N, N, 2])\n sss2[:, :, 0] = np.real(ss2)\n sss2[:, :, 1] = np.imag(ss2)\n\n\n so3.signal1[shell].grid = np.real(ss1)\n so3.signal2[shell].grid = np.real(ss2)\n so3.signal1[shell].N = N\n so3.signal2[shell].N = N\n\n g1 = torch.tensor(sss1, dtype=torch.float)\n g1ft = s2cnn.soft.s2_fft.s2_fft(g1, b_out=b)\n g1ftn = g1ft.numpy()\n\n g2 = torch.tensor(sss2, dtype=torch.float)\n g2ft = s2cnn.soft.s2_fft.s2_fft(g2, b_out=b)\n g2ftn = g2ft.numpy()\n\n # lets try to do a convoluion\n xn1 = np.empty([b * b, 1, 1, 2])\n xn1[:, 0, 0, 0] = g1ftn[:, 0]\n xn1[:, 0, 0, 1] = g1ftn[:, 1]\n x1 = torch.tensor(xn1, dtype=torch.float)\n\n # lets try to do a convoluion\n xn2 = np.empty([b * b, 1, 1, 2])\n xn2[:, 0, 0, 0] = g2ftn[:, 0]\n xn2[:, 0, 0, 1] = g2ftn[:, 1]\n x2 = torch.tensor(xn2, dtype=torch.float)\n\n xx = s2cnn.s2_mm(x1, x2)\n xxift = s2cnn.so3_fft.so3_ifft(xx)\n # xxift=s2cnn.so3_fft.SO3_ifft_real.apply(xx)\n xxiftn = xxift.numpy()\n xxiftnsmall = np.empty([N, N, N,2])\n xxiftnsmall = xxiftn[0, 0, :, :, :, :]\n xxiftnsmall = xxiftnsmall / xxiftnsmall.max()\n so3.so3[:,:,:,:,shell]=xxiftnsmall #[beta, alpha, gamma, complex] beta=[0, pi], alpha=[0,2pi] gamma=[0,2pi]\n return so3\n\n # def so3_grad(self):\n # size=\n","sub_path":"diffusion.py","file_name":"diffusion.py","file_ext":"py","file_size_in_byte":12037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"128662899","text":"import sys # Used to add the BeautifulSoup folder the import path\nimport urllib2 # Used to read the html document\nimport web\n\nurls = (\n '/', 'index'\n)\n\nclass index:\n def GET(self):\n web.header('Access-Control-Allow-Origin', '*')\n web.header('Access-Control-Allow-Credentials', 'true')\n sys.path.append(\"./BeautifulSoup\")\n from BeautifulSoup import BeautifulSoup\n\n ### Create opener with Google-friendly user agent\n opener = urllib2.build_opener()\n opener.addheaders = [('User-agent', 'Mozilla/5.0')]\n\n ### Open page & generate soup\n ### the \"start\" variable will be used to iterate through 10 pages.\n params = web.input()\n list = []\n for start in range(0,int(params.iterations)):\n url = \"https://www.google.com/search?q=\" + params.search + \"&start=\" + str(start*10)\n page = opener.open(url)\n soup = BeautifulSoup(page)\n\n ### Parse and find\n ### Looks like google contains URLs in tags.\n ### So for each cite tag on each page (10), print its contents (url)\n for elements in soup.findAll('h3'):\n list += [\"/url?q=\" + elements.find('a').text]\n list += [elements.find('a').get('href')]\n return list\nif __name__ == \"__main__\":\n app = web.application(urls, globals())\n app.run()\n","sub_path":"backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105192369","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n #path('', views.index, name='index'),\n path('', views.viewlist, name='view_list'),\n path('detail/', views.detailView, name='detail'),\n path('chitiet/', views.chitiet, name='chitiet'),\n\n #path('search/', views.search, name='search'),\n]\n","sub_path":"file/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"171022348","text":"#!/usr/bin/env python3\n\nimport urwid\n\ndef main():\n\n color_map = [\n # label foreground background\n ('header', '', '', '', 'g78', 'g11'),\n ('footer', '', '', '', 'g78', 'g11'),\n ('body', '', '', '', 'g11', 'g27')\n ]\n\n\n def handle_key(key):\n if key in ('q', 'Q', 'esc'):\n raise urwid.ExitMainLoop()\n\n lb = urwid.SimpleListWalker([])\n lb.extend([\n urwid.AttrMap(urwid.Text(\"To Do Craft\", align='center'), 'header'),\n urwid.AttrMap(urwid.Divider(\"-\",10,10), 'body'),\n urwid.AttrMap(urwid.Text(\"STATUS: \", align='left'), 'footer')\n ])\n loop = urwid.MainLoop(\n urwid.ListBox(lb),\n unhandled_input=handle_key,\n palette=color_map\n )\n loop.screen.set_terminal_properties(colors=256)\n loop.run()\n\nif __name__ == '__main__':\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"198934385","text":"#Faça um programa que leia três números e mostre qual é maior e qual é o menor.\r\n\r\nfrom time import sleep\r\nprint('Você irá informar 3 números a seguir...')\r\nsleep(2)\r\na = int(input('Digite o primeiro número: '))\r\nb = int(input('Digite o segundo número: '))\r\nc = int(input('Digite o terceiro número: '))\r\nprint('Analisando o menor...')\r\nsleep(3)\r\n#Verificar quem é o menor número\r\nmenor = a\r\nif ba and b>c:\r\n maior = b\r\nif c>a and c>b:\r\n maior = c\r\nprint('O maior valor digitado foi {}.'.format(maior))\r\n\r\n","sub_path":"ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491304713","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 30 10:20:38 2018\n\nProvide methods to localize Wind data sets.\n\nRequire local access to Wind Terminal, and key words of data.\n\n@author: szlsd\n\"\"\"\n\n\nfrom WindPy import *\nimport pandas as pd\nimport datetime\n\n\ndef WriteWFactorData(fac_list, start_date = \"2015-01-01\", end_date = \"2018-09-30\", stock_list_date = \"2018-10-30\",\n unit = 1, rptType = 1, currencyType = \"\", Period = \"Q\", PriceAdj = \"B\"):\n \n # The function downloads Chinese A stock factor data given \n \n if len(pd.unique(fac_list)) != len(fac_list):\n raise ValueError(\"Duplicate elements in fac_list!\")\n \n w.start()\n #test\n #fac_list = ['close','ev']\n factors = \",\".join(fac_list)\n O_arguments = \"unit=%s;rptType=%s;currencyType=%s;Period=%s;PriceAdj=%s\" % (unit, rptType,currencyType,Period,PriceAdj)\n \n A_Stock_Tickers_Data = w.wset(\"sectorconstituent\",\"date=%s;sectorid=a001010100000000\" % stock_list_date) # Get the tickers of all Chinese A-Stocks\n A_S_Ticker_t = pd.DataFrame(A_Stock_Tickers_Data.Data, columns = A_Stock_Tickers_Data.Data[1], index = ['DateTime', 'Ticker', 'Name'])\n \n # Test\n \n P_Ticker_L = list(A_S_Ticker_t.loc['Ticker'])\n \n Maj_Table = pd.DataFrame()\n \n for i in range(0,len(P_Ticker_L)):\n \n temp_data = w.wsd(P_Ticker_L[i], factors, start_date, end_date, O_arguments)\n temp_data.Data.append(temp_data.Codes * len(temp_data.Data[0]))\n temp_data.Data.append(temp_data.Times)\n temp_table = pd.DataFrame(data = temp_data.Data).transpose()\n temp_table.columns = temp_data.Fields + [\"Ticker\"] + [\"Date\"]\n temp_table = temp_table[['Date'] + ['Ticker'] + temp_data.Fields]\n \n Maj_Table = pd.concat([Maj_Table, temp_table], axis = 0)\n \n print(\"Stock %s collected\" % temp_data.Codes[0])\n \n del temp_data\n \n \n Maj_Table.reset_index(drop = True)\n \n return Maj_Table\n \ndef GetCSData(fac_list, trade_date = \"20100101\", rpt_date = \"20100630\", stock_list_date = \"2018-10-30\",\n unit = 1, rptType = 1, currencyType = \"\"):\n \n # The function downloads Chinese A stock factor data given \n \n # Still need a module to control variable format\n \n try:\n if len(pd.unique(fac_list)) != len(fac_list):\n raise ValueError(\"Duplicate elements in fac_list!\")\n \n \n w.start()\n #test\n #fac_list = ['wgsd_net_inc','wgsd_assets','stm_issuingdate']\n factors = \",\".join(fac_list)\n O_arguments = \"unit=%s;tradeDate=%s;rptDate=%s;rptType=%s;currencyType=%s\" % (unit, trade_date,rpt_date,rptType,currencyType)\n \n A_Stock_Tickers_Data = w.wset(\"sectorconstituent\",\"date=%s;sectorid=a001010100000000\" % stock_list_date) # Get the tickers of all Chinese A-Stocks\n A_S_Ticker_t = pd.DataFrame(A_Stock_Tickers_Data.Data, columns = A_Stock_Tickers_Data.Data[1], index = ['DateTime', 'Ticker', 'Name'])\n \n P_Ticker_L = list(A_S_Ticker_t.loc['Ticker'])\n \n out_data = w.wss(\",\".join(P_Ticker_L),factors,O_arguments)\n out_data.Data.append(out_data.Codes)\n out_table = pd.DataFrame(data = out_data.Data).T\n out_table.columns = out_data.Fields + [\"Ticker\"]\n out_table = out_table[['Ticker'] + out_data.Fields]\n except Exception as e:\n return e\n \n return out_table\n\ndef GetTradeDates(StartDate = \"2018-09-30\", EndDate = \"2018-10-30\", DateType = \"\"):\n \n try:\n w.start()\n return w.tdays(StartDate, EndDate, \"Period=%s\" % DateType).Data \n except Exception as e:\n return e\n \ndef GetRptDates(year, quarter = 1):\n \n if quarter in [1,2,3,4]:\n try:\n rptdates = {1:\"0331\", 2:\"0630\", 3:\"0930\", 4:\"1231\"}\n Rptdate = str(year) + rptdates[quarter]\n return Rptdate\n except Exception as e:\n return e\n else:\n raise ValueError(\"qurter should be either 1,2,3 or 4\")\n \ndef GetWFactorCS(start_date, end_date):\n #test\n #Current problem of such function is that data cannot automatically adjust Wind report date to actual \n #report date, for example rpt date at 12.30, the actual release date is around 1.30 next year.\n # This is an unfinished function.\n \n \n start_date = \"2013-12-12\"\n end_date = \"2017-12-10\"\n \n start_date_dt = datetime.datetime.strptime(start_date, \"%Y-%m-%d\")\n end_date_dt = datetime.datetime.strptime(end_date, \"%Y-%m-%d\")\n \n start_date_qt = ((start_date_dt.month - 1)//3) + 1\n end_date_qt = ((start_date_dt.month - 1)//3) + 1\n s_ele_dates = [GetRptDates(i,j) for i in range(start_date_dt.year, start_date_dt.year + 1) for j in list(range(1,start_date_qt))]\n rpt_dates = [GetRptDates(i,j) for i in range(start_date_dt.year - 1, end_date_dt.year + 1) for j in [1,2,3,4]] # Have to maintain a longer calendar so as to subset proper data\n \n \n \n\nWdata = WriteWFactorData(fac_list, start_date = \"2017-01-01\")\n","sub_path":"sliquantkit/DataImport/LocalizeWind.py","file_name":"LocalizeWind.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"590974039","text":"import key\nfrom binance.client import Client\n\nclass get_client :\n\n def get_client(self, mode):\n print('----- GET CLIENT -----')\n\n if mode == 'real' :\n api_key = key.api_key_real\n api_secret = key.api_secret_real\n elif mode == 'test' :\n api_key = key.api_key_test\n api_secret = key.api_secret_test\n else :\n raise Exception('CHECK MODE : ', mode)\n\n self.client = Client(api_key, api_secret)\n\n ## Set test URL\n if mode == 'test' :\n self.client.API_URL = 'https://testnet.binance.vision/api'\n print('----- RUNNING IN TEST MODE -----')\n \n return self.client","sub_path":"GetClient.py","file_name":"GetClient.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"38214390","text":"infile=open('hippoin.txt','r').readlines()\r\nn,h,f=map(int,infile[0].strip().split())\r\nplace=[0]+[int(i) for i in infile[1:]]+[n]\r\nlength=[]\r\nfor i in range(1,h+1):\r\n length.append(place[i]-place[i-1]-1)\r\nlength.append(place[-1]-place[-2])\r\nanswer=0 \r\nmodi=length[1:-1]\r\nmodi.sort()\r\n \r\nchance=f//2\r\nif chance>0:answer=sum(modi[-chance:])\r\n\r\nchance=(f-1)//2\r\ncurrent=0\r\nif length[0]>length[-1]:current+=length[0]\r\nelse:current+=length[-1]\r\nif chance>0:current+=sum(modi[-chance:])\r\nanswer=max(current,answer)\r\n\r\nchance=(f-2)//2\r\ncurrent=length[0]+length[-1]\r\nif chance>0:current+=sum(modi[-chance:])\r\nanswer=max(current,answer)\r\n\r\nopen('hippoout.txt','w').write(str(max(0,answer)))\r\n","sub_path":"AIO/giant hippos/pigs.py","file_name":"pigs.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"281661547","text":"import re\nfrom googletrans import Translator # 需要翻墙使用\n# 用于解析网页表格数据\n# 生成指定格式文件的脚本\n\n# 将分割的字符串数组拼接成小驼峰\ndef get_format_data(data_source):\n for i in range(len(data_source)):\n if i == 0:\n data_source[i] = data_source[i].lower()\n else:\n data_source[i] = data_source[i].capitalize()\n return ''.join(data_source)\n\n# 解析网页表格信息\ndef table_info_resolve(data_path = \"data.txt\"):\n # 表名模式串\n table_pattern = r'.*'.format(parsed_url.netloc)\n formatted_url += ''.format(parsed_url.path)\n if parsed_url.fragment:\n formatted_url += ''.format(parsed_url.fragment)\n if parsed_url.query:\n formatted_url += ''\n formatted_q = parse_qs(parsed_url.query)\n for key, values in formatted_q.items():\n for val in values:\n if val.startswith(('https://', 'http://')):\n template = ''\n formatted_url += template.format(key, val)\n else:\n formatted_url += ''.format(key, val)\n template = '
Netloc{}
Path{}
fragment{}
Query
{0}{1}
{}{}
{}
'\n formatted_url = template.format(formatted_url)\n return Markup(\n \"[link]
{}\".format(input_url, formatted_url)\n ) if input_url and input_url != '#' else Markup(\"\")\n\n\ndef json_formatter(_, __, model, name):\n \"\"\"URL formatter.\"\"\"\n json_input = getattr(model, name)\n result = ''\n for key, val in sorted(json_input.items()):\n val_str = str(val)\n if val_str.startswith('/search?'):\n str_templ = '{}{}'\n result += str_templ.format(\n str(key), val_str, val_str)\n elif val_str.startswith(('https://', 'http://')):\n result += '{}{}'.format(\n str(key), val_str, val_str)\n else:\n result += '{}{}'.format(str(key), val_str)\n result = '{}
'.format(result)\n return Markup(result)\n\n\ndef date_formatter(_, __, model, name):\n date_data = getattr(model, name)\n humanized_date_data = humanize.naturaltime(date_data)\n return Markup(\n '{}'.format(\n date_data, humanized_date_data\n )\n )\n\n\ndef filesize_formatter(_, __, model, name):\n data = getattr(model, name)\n if data:\n return Markup(humanize.naturalsize(data))\n return Markup('')\n\n\nclass HomeView(AdminIndexView):\n @expose('/')\n def index(self):\n form = forms.IndexForm(request.args)\n page = request.args.get(get_page_parameter(), type=int, default=1)\n query = form.query.data\n disable_cache = form.disable_cache.data\n template_kwargs = {'entry': None, 'query': query, 'form': form, }\n pagination_kwargs = {'page': page, 'show_single_page': False, 'bs_version': 3, }\n if query:\n pagination_kwargs['per_page'] = 1\n model, created = api.get_or_create_search_query(\n query, page, disable_cache=disable_cache)\n if created or disable_cache:\n models.db.session.add(model)\n models.db.session.commit()\n pagination_kwargs['total'] = \\\n models.SearchQuery.query.filter(models.SearchQuery.search_query == query).count()\n template_kwargs['entry'] = model\n template_kwargs['pagination'] = Pagination(**pagination_kwargs)\n return self.render('google_images_download/index.html', **template_kwargs)\n\n\nclass SearchQueryView(ModelView):\n \"\"\"Custom view for SearchQuery model.\"\"\"\n can_view_details = True\n column_formatters = {'created_at': date_formatter, }\n column_searchable_list = ('page', 'search_query')\n column_filters = ('page', 'search_query')\n\n\nclass MatchResultView(ModelView):\n \"\"\"Custom view for MatchResult model.\"\"\"\n\n def _image_formatter(view, context, model, name):\n desc_table = 'Title{}'.format(model.picture_title)\n if model.picture_subtitle:\n desc_table += 'Subtitle{}'.format(model.picture_subtitle)\n desc_table += 'Site{0}'.format(\n model.site)\n desc_table += 'Site title{}'.format(model.site_title)\n desc_table = '{}
'.format(\n desc_table)\n template = '
{2}'\n return Markup(template.format(model.thumb_url, model.img_url, desc_table))\n\n def _thumbnail_formatter(view, context, model, name):\n templ = ''\n if model.img_url:\n return Markup(templ.format(model.thumbnail_url.url, model.img_url.url))\n return Markup(templ.format(model.thumbnail_url.url, model.thumbnail_url.url))\n\n column_formatters = {'created_at': date_formatter, 'thumbnail_url': _thumbnail_formatter, }\n column_exclude_list = ('imgres_url', 'img_url',)\n can_view_details = True\n page_size = 100\n\n\nclass JSONDataView(ModelView):\n \"\"\"Custom view for json data model\"\"\"\n def _value_formatter(view, context, model, name):\n res = ''\n for key, value in model.value.items():\n res += '{0}{1}'.format(key, value)\n res = '{}
'.format(res)\n return Markup(res)\n can_view_details = True\n column_formatters = {'created_at': date_formatter, 'value': _value_formatter, }\n\n\nclass ImageURLView(ModelView):\n \"\"\"Custom view for ImageURL model.\"\"\"\n\n def _url_formatter(view, context, model, name):\n match_results = model.match_results\n templ = \"\"\"\n
\n \n
{2}
\n
\"\"\"\n img_view_url = url_for('u.index', u=model.url)\n if match_results:\n first_match_result = next(iter(match_results or []), None)\n shorted_url = '
'.join(textwrap.wrap(model.url))\n return Markup(\n templ.format(\n model.url,\n first_match_result.thumbnail_url.url,\n shorted_url,\n img_view_url\n )\n )\n shorted_url = '
'.join(textwrap.wrap(model.url))\n return Markup(templ.format(model.url, model.url, shorted_url, img_view_url))\n\n can_view_details = True\n column_searchable_list = ('url', 'width', 'height')\n column_filters = ('width', 'height')\n column_formatters = {'created_at': date_formatter, 'url': _url_formatter, }\n page_size = 100\n column_default_sort = ('created_at', True)\n\n\nclass TagView(ModelView):\n \"\"\"Custom view for Tag model.\"\"\"\n\n column_searchable_list = ('namespace', 'name')\n column_filters = ('namespace', 'name')\n column_formatters = {'created_at': date_formatter, }\n column_default_sort = ('created_at', True)\n page_size = 100\n\n\nclass ImageFileView(ModelView):\n \"\"\"Custom view for ImageFile model.\"\"\"\n\n def _thumbnail_formatter(view, context, model, name):\n if not model.thumbnail:\n return\n return Markup(''.format(url_for(\n 'thumbnail', filename=model.thumbnail.checksum + '.jpg')))\n\n column_formatters = {\n 'created_at': date_formatter,\n 'size': filesize_formatter,\n 'thumbnail': _thumbnail_formatter,\n }\n can_view_details = True\n page_size = 100\n\n\nclass SearchImageView(ModelView):\n \"\"\"Custom view for SearchImage model.\"\"\"\n\n def _result_formatter(view, context, model, name):\n res = '
main'.format(model.search_url)\n if model.size_search_url:\n res += ', size'.format(model.size_search_url)\n if model.similar_search_url:\n res += ', similar'.format(model.similar_search_url)\n return Markup(res)\n\n @staticmethod\n def _format_searched_img_url(url):\n url_text = url\n if not url:\n return\n if url.startswith('https://'):\n url_text = url.replace('https://', '', 1)\n elif url.startswith('http://'):\n url_text = url.replace('http://', '', 1)\n return '{}'.format(url, url_text)\n\n def _input_search_formatter(view, context, model, name):\n res = ''\n if model.img_file:\n res += '

Image File

'\n if model.img_file.thumbnail:\n res += '
{}
'.format(\n url_for('thumbnail', filename=model.img_file.thumbnail.checksum + '.jpg'),\n Markup.escape(model.img_file)\n )\n else:\n res += '

{}

'.format(model.img_file)\n if model.searched_img_url:\n res += '

Searched Url

'\n res += SearchImageView._format_searched_img_url(model.searched_img_url)\n return Markup(res)\n\n column_formatters = {\n 'created_at': date_formatter,\n 'Result': _result_formatter,\n 'Input': _input_search_formatter,\n 'searched_img_url': lambda v, c, m, p: Markup(\n SearchImageView._format_searched_img_url(m.searched_img_url)\n if m.searched_img_url else ''\n ),\n }\n column_exclude_list = (\n 'search_url', 'similar_search_url', 'size_search_url', 'searched_img_url', 'img_file', )\n can_view_details = True\n column_searchable_list = ('searched_img_url', )\n column_list = ('img_file', 'created_at', 'searched_img_url', 'img_guess', 'Result', 'Input')\n\n\nclass SearchImagePageView(ModelView):\n \"\"\"Custom view for SearchImagePage model.\"\"\"\n\n column_formatters = dict(\n created_at=date_formatter,\n search_type=lambda v, c, m, p: m.search_type.value\n )\n column_exclude_list = ('search_url', 'similar_search_url', 'size_search_url', )\n can_view_details = True\n\n\nclass TextMatchView(ModelView):\n \"\"\"Custom view for TextMatch model.\"\"\"\n\n can_view_details = True\n column_formatters = {\n 'created_at': date_formatter,\n 'content': lambda v, c, m, p: Markup(\n '

{0}

{1}

{4}

{3}

'.format(\n m.title,\n '
'.join(textwrap.wrap(m.text)),\n m.url,\n m.url_text,\n '
'.join(textwrap.wrap(m.url)),\n )\n ),\n }\n column_searchable_list = ('url', 'url_text', 'text', 'title')\n column_filters = ('url_text', 'text', 'title')\n column_exclude_list = ('imgres_url', 'imgref_url', )\n column_list = (\n 'search_image_model',\n 'img_url',\n 'thumbnail_url',\n 'created_at',\n 'content',\n )\n page_size = 50\n column_default_sort = ('created_at', True)\n\n\nclass MainSimilarResultView(ModelView):\n \"\"\"Custom view for SearchImagePage model.\"\"\"\n\n column_formatters = dict(\n created_at=date_formatter,\n img_title=lambda v, c, m, p: Markup('{0}'.format(m.img_title))\n )\n column_exclude_list = ('search_url', 'img_src', )\n can_view_details = True\n column_searchable_list = ('img_title', 'img_width', 'img_height')\n column_filters = ('img_title', 'img_width', 'img_height')\n","sub_path":"google_images_download/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":12096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"523440676","text":"import inspect\nimport os\nimport pkgutil\nimport shutil\nimport sys\nimport warnings\nfrom pathlib import Path\nfrom types import SimpleNamespace\n\nimport ophyd\nimport pytest\nfrom epics import PV\nfrom ophyd.signal import LimitError\nfrom ophyd.sim import FakeEpicsSignal, make_fake_device\n\nfrom pcdsdevices.attenuator import MAX_FILTERS, Attenuator, _att_classes\nfrom pcdsdevices.mv_interface import setup_preset_paths\n\nMODULE_PATH = Path(__file__).parent\n\n\n# Signal.put warning is a testing artifact.\n# FakeEpicsSignal needs an update, but I don't have time today\n# Needs to not pass tons of kwargs up to Signal.put\nwarnings.filterwarnings('ignore',\n message='Signal.put no longer takes keyword arguments')\n\n\n# Other temporary patches to FakeEpicsSignal\ndef check_value(self, value):\n if value is None:\n raise ValueError('Cannot write None to epics PVs')\n if not self._use_limits:\n return\n\n low_limit, high_limit = self.limits\n if low_limit >= high_limit:\n return\n\n if not (low_limit <= value <= high_limit):\n raise LimitError('Value {} outside of range: [{}, {}]'\n .format(value, low_limit, high_limit))\n\n\n# Check value is busted, ignores (0, 0) no limits case\nFakeEpicsSignal.check_value = check_value\n# Metadata changed is missing\nFakeEpicsSignal._metadata_changed = lambda *args, **kwargs: None\n# pvname is missing\nFakeEpicsSignal.pvname = ''\n# lots of things are missing\nFakeEpicsSignal._read_pv = SimpleNamespace(get_ctrlvars=lambda: None)\n# Stupid patch that somehow makes the test cleanup bug go away\nPV.count = property(lambda self: 1)\n\nfor name, cls in _att_classes.items():\n _att_classes[name] = make_fake_device(cls)\n\n\n# Used in multiple test files\n@pytest.fixture(scope='function')\ndef fake_att():\n att = Attenuator('TST:ATT', MAX_FILTERS-1, name='test_att')\n att.readback.sim_put(1)\n att.done.sim_put(0)\n att.calcpend.sim_put(0)\n for i, filt in enumerate(att.filters):\n filt.state.put('OUT')\n filt.thickness.put(2*i)\n return att\n\n\n@pytest.fixture(scope='function')\ndef presets():\n folder_obj = Path(__file__).parent / 'test_presets'\n folder = str(folder_obj)\n if folder_obj.exists():\n shutil.rmtree(folder)\n hutch = folder + '/hutch'\n user = folder + '/user'\n os.makedirs(hutch)\n os.makedirs(user)\n setup_preset_paths(hutch=hutch, user=user)\n yield\n setup_preset_paths()\n shutil.rmtree(folder)\n\n\ndef find_all_device_classes() -> list:\n exclude_list = {'_version', }\n pkgname = 'pcdsdevices'\n modules = [\n mod.name for mod in pkgutil.iter_modules(\n path=[MODULE_PATH.parent / pkgname])\n if mod not in exclude_list\n ]\n\n for module in modules:\n __import__(f'{pkgname}.{module}')\n\n devices = set()\n for mod_name, mod in sys.modules.items():\n if pkgname not in mod_name:\n continue\n\n for mod_attr in dir(mod):\n obj = getattr(mod, mod_attr)\n if inspect.isclass(obj) and issubclass(obj, ophyd.Device):\n if not obj.__module__.startswith('ophyd'):\n devices.add(obj)\n\n return list(devices)\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"246741102","text":"import io\nimport os\nimport re\nimport shutil\nimport tarfile\n\nfrom . import checksums\nfrom . import convert\n\n\nclass ArchiveError(Exception):\n pass\n\n\nclass ExtractError(Exception):\n pass\n\n\nclass PackageError(Exception):\n pass\n\n\nclass PackageValidationError(Exception):\n pass\n\n\nclass PackageFileChecksumError(PackageValidationError):\n def __init__(self, filename):\n self.filename = filename\n super().__init__(\"Checksum mismatch for {}\".format(filename))\n\n\nclass DescriptorPackage(object):\n \"\"\" This class provides an base class for a descriptor package representing\n\n A descriptor package is a package which contains a single descriptor and any\n associated files (logos, charms, scripts, etc). This package representation\n attempts to be agnostic as to where the package files are being stored\n (in memory, on disk, etc).\n\n The package provides a simple interface to interact with the files within the\n package and access the contained descriptor.\n \"\"\"\n DESCRIPTOR_REGEX = r\"{prefix}({descriptor_type}/[^/]*|[^/]*{descriptor_type})\\.(xml|yml|yaml|json)$\"\n\n def __init__(self, log, open_fn):\n self._log = log\n self._open_fn = open_fn\n\n self._package_file_mode_map = {}\n self._package_dirs = set()\n\n @property\n def prefix(self):\n \"\"\" Return the leading parent directories shared by all files in the package\n\n In order to remain flexible as to where tar was invoked to create the package,\n the prefix represents the common parent directory path which all files in the\n package have in common.\n \"\"\"\n entries = list(self._package_file_mode_map) + list(self._package_dirs)\n\n if len(entries) > 1:\n prefix = os.path.commonprefix(entries)\n if prefix and not prefix.endswith(\"/\"):\n prefix += \"/\"\n elif len(entries) == 1:\n entry = entries[0]\n if \"/\" in entry:\n prefix = os.path.dirname(entry) + \"/\"\n else:\n prefix = \"\"\n else:\n prefix = \"\"\n\n return prefix\n\n @property\n def files(self):\n \"\"\" Return all files (with the prefix) in the package \"\"\"\n return list(self._package_file_mode_map)\n\n @property\n def dirs(self):\n \"\"\" Return all directories in the package \"\"\"\n return list(self._package_dirs)\n\n @property\n def descriptor_type(self):\n \"\"\" A shorthand name for the type of descriptor (e.g. nsd)\"\"\"\n raise NotImplementedError(\"Subclass must implement this property\")\n\n @property\n def serializer(self):\n \"\"\" An instance of convert.ProtoMessageSerializer \"\"\"\n raise NotImplementedError(\"Subclass must implement this property\")\n\n @property\n def descriptor_file(self):\n \"\"\" The descriptor file name (with prefix) \"\"\"\n regex = self.__class__.DESCRIPTOR_REGEX.format(\n descriptor_type=self.descriptor_type,\n prefix=self.prefix,\n )\n desc_file = None\n for filename in self.files:\n if re.match(regex, filename):\n if desc_file is not None:\n raise PackageError(\"Package contains more than one descriptor\")\n desc_file = filename\n\n if desc_file is None:\n raise PackageError(\"Could not find descriptor file in package\")\n\n return desc_file\n\n @property\n def descriptor_msg(self):\n \"\"\" The proto-GI descriptor message \"\"\"\n filename = self.descriptor_file\n with self.open(filename) as hdl:\n _, ext = os.path.splitext(filename)\n nsd = self.serializer.from_file_hdl(hdl, ext)\n return nsd\n\n @property\n def json_descriptor(self):\n \"\"\" The JSON serialized descriptor message\"\"\"\n nsd = self.descriptor_msg\n return self.serializer.to_json_string(nsd)\n\n @property\n def descriptor_id(self):\n \"\"\" The descriptor id which uniquely identifies this descriptor in the system \"\"\"\n if not self.descriptor_msg.has_field(\"id\"):\n msg = \"Descriptor must have an id field\"\n self._log.error(msg)\n raise PackageError(msg)\n\n return self.descriptor_msg.id\n\n @classmethod\n def get_descriptor_patterns(cls):\n \"\"\" Returns a tuple of descriptor regex and Package Types \"\"\"\n package_types = (VnfdPackage, NsdPackage)\n patterns = []\n\n for pkg_cls in package_types:\n regex = cls.DESCRIPTOR_REGEX.format(\n descriptor_type=pkg_cls.DESCRIPTOR_TYPE,\n prefix=\".*\"\n )\n\n patterns.append((regex, pkg_cls))\n\n return patterns\n\n @classmethod\n def from_package_files(cls, log, open_fn, files):\n \"\"\" Creates a new DescriptorPackage subclass instance from a list of files\n\n This classmethod detects the Package type from the package contents\n and returns a new Package instance.\n\n This will NOT subsequently add the files to the package so that must\n be done by the client\n\n Arguments:\n log - A logger\n open_fn - A function which can take a file name and mode and return\n a file handle.\n files - A list of files which would be added to the package after\n intantiation\n\n Returns:\n A new DescriptorPackage subclass of the correct type for the descriptor\n\n Raises:\n PackageError - Package type could not be determined from the list of files.\n \"\"\"\n patterns = cls.get_descriptor_patterns()\n pkg_cls = None\n regexes = set()\n for name in files:\n for regex, cls in patterns:\n regexes.add(regex)\n if re.match(regex, name) is not None:\n pkg_cls = cls\n break\n\n if pkg_cls is None:\n log.error(\"No file in archive matched known descriptor formats: %s\", regexes)\n raise PackageError(\"Could not determine package type from contents\")\n\n package = pkg_cls(log, open_fn)\n return package\n\n @classmethod\n def from_descriptor_file_hdl(cls, log, file_hdl):\n \"\"\" Creates a new DescriptorPackage from a descriptor file handle\n\n The descriptor file is added to the package before returning.\n\n Arguments:\n log - A logger\n file_hdl - A file handle whose name attribute can be recognized as\n particular descriptor type.\n\n Returns:\n A new DescriptorPackage subclass of the correct type for the descriptor\n\n Raises:\n PackageError - Package type could not be determined from the list of files.\n ValueError - file_hdl did not have a name attribute provided\n \"\"\"\n\n package_types = (VnfdPackage, NsdPackage)\n filename_patterns = []\n for package_cls in package_types:\n filename_patterns.append(\n (r\".*{}.*\".format(package_cls.DESCRIPTOR_TYPE), package_cls)\n )\n\n if not hasattr(file_hdl, 'name'):\n raise ValueError(\"File descriptor must have a name attribute to create a descriptor package\")\n\n # Iterate through the recognized patterns and assign files accordingly\n package_cls = None\n for pattern, cls in filename_patterns:\n if re.match(pattern, file_hdl.name):\n package_cls = cls\n break\n\n if not package_cls:\n raise PackageError(\"Could not determine package type from file name: %s\" % file_hdl.name)\n\n _, ext = os.path.splitext(file_hdl.name)\n try:\n package_cls.SERIALIZER.from_file_hdl(file_hdl, ext)\n except convert.SerializationError as e:\n raise PackageError(\"Could not deserialize descriptor %s\" % file_hdl.name) from e\n\n # Create a new file handle for each open call to prevent independent clients\n # from affecting each other\n file_hdl.seek(0)\n new_hdl = io.BytesIO(file_hdl.read())\n\n def do_open(file_path):\n assert file_path == file_hdl.name\n hdl = io.BytesIO(new_hdl.getvalue())\n return hdl\n\n desc_pkg = package_cls(log, do_open)\n desc_pkg.add_file(file_hdl.name)\n\n return desc_pkg\n\n def get_file_mode(self, pkg_file):\n \"\"\" Returns the file mode for the package file\n\n Arguments:\n pkg_file - A file name in the package\n\n Returns:\n The permission mode\n\n Raises:\n PackageError - The file does not exist in the package\n \"\"\"\n try:\n return self._package_file_mode_map[pkg_file]\n except KeyError as e:\n msg = \"Could not find package_file: %s\" % pkg_file\n self._log.error(msg)\n raise PackageError(msg) from e\n\n def extract_dir(self, src_dir, dest_root_dir):\n \"\"\" Extract a specific directory contents to dest_root_dir\n\n Arguments:\n src_dir - A directory within the package (None means all files/directories)\n dest_root_dir - A directory to extract directory contents to\n\n Raises:\n ExtractError - Directory contents could not be extracted\n \"\"\"\n if src_dir is not None and src_dir not in self._package_dirs:\n raise ExtractError(\"Could not find source dir: %s\" % src_dir)\n\n for filename in self.files:\n if src_dir is not None and not filename.startswith(src_dir):\n continue\n\n # Copy the contents of the file to the correct path\n dest_file_path = os.path.join(dest_root_dir, filename)\n dest_dir_path = os.path.dirname(dest_file_path)\n if not os.path.exists(dest_dir_path):\n os.makedirs(dest_dir_path)\n\n with open(dest_file_path, 'wb') as dst_hdl:\n with self.open(filename) as src_hdl:\n shutil.copyfileobj(src_hdl, dst_hdl, 10 * 1024 * 1024)\n\n # Set the file mode to original\n os.chmod(dest_file_path, self._package_file_mode_map[filename])\n\n def extract_file(self, src_file, dest_file):\n \"\"\" Extract a specific package file to dest_file\n\n The destination directory will be created if it does not exist.\n\n Arguments:\n src_file - A file within the package\n dest_file - A file path to extract file contents to\n\n Raises:\n ExtractError - Directory contents could not be extracted\n \"\"\"\n if src_file not in self._package_file_mode_map:\n msg = \"Could not find source file %s\" % src_file\n self._log.error(msg)\n raise ExtractError(msg)\n\n # Copy the contents of the file to the correct path\n dest_dir_path = os.path.dirname(dest_file)\n if not os.path.isdir(dest_dir_path):\n os.makedirs(dest_dir_path)\n\n with open(dest_file, 'wb') as dst_hdl:\n with self.open(src_file) as src_hdl:\n shutil.copyfileobj(src_hdl, dst_hdl, 10 * 1024 * 1024)\n\n # Set the file mode to original\n os.chmod(dest_file, self._package_file_mode_map[src_file])\n\n def extract(self, dest_root_dir):\n \"\"\" Extract all package contents to a destination directory\n\n Arguments:\n dest_root_dir - The directory to extract package contents to\n\n Raises:\n NotADirectoryError - dest_root_dir is not a directory\n \"\"\"\n if not os.path.isdir(dest_root_dir):\n raise NotADirectoryError(dest_root_dir)\n\n self.extract_dir(None, dest_root_dir)\n\n def open(self, rel_path):\n \"\"\" Open a file contained in the package in read-only, binary mode.\n\n Arguments:\n rel_path - The file path within the package\n\n Returns:\n A file-like object opened in read-only mode.\n\n Raises:\n PackageError - The file could not be opened\n \"\"\"\n try:\n return self._open_fn(rel_path)\n except Exception as e:\n msg = \"Could not open file from package: %s\" % rel_path\n self._log.warning(msg)\n raise PackageError(msg) from e\n\n def add_file(self, rel_path, mode=0o777):\n \"\"\" Add a file to the package.\n\n The file should be specified as a relative path to the package\n root. The open_fn provided in the constructor must be able to\n take the relative path and open the actual source file from\n wherever the file actually is stored.\n\n If the file's parent directories do not yet exist, add them to\n the package.\n\n Arguments:\n rel_path - The file path relative to the top of the package.\n mode - The permission mode the file should be stored with so\n it can be extracted with the correct permissions.\n\n Raises:\n PackageError - The file could not be added to the package\n \"\"\"\n if not rel_path:\n raise PackageError(\"Empty file name added\")\n\n if rel_path in self._package_file_mode_map:\n raise PackageError(\"File %s already exists in package\" % rel_path)\n\n # If the file's directory is not in the package add it.\n rel_dir = os.path.dirname(rel_path)\n while rel_dir:\n self._package_dirs.add(rel_dir)\n rel_dir = os.path.dirname(rel_dir)\n\n self._package_file_mode_map[rel_path] = mode\n\n def add_dir(self, rel_path):\n \"\"\" Add a directory to the package\n\n Arguments:\n rel_path - The directories relative path.\n\n Raises:\n PackageError - A file already exists in the package with the same name.\n \"\"\"\n if rel_path in self._package_file_mode_map:\n raise PackageError(\"File already exists with the same name: %s\", rel_path)\n\n if rel_path in self._package_dirs:\n self._log.warning(\"%s directory already exists\", rel_path)\n return\n\n self._package_dirs.add(rel_path)\n\n\nclass NsdPackage(DescriptorPackage):\n DESCRIPTOR_TYPE = \"nsd\"\n SERIALIZER = convert.RwNsdSerializer()\n\n @property\n def descriptor_type(self):\n return \"nsd\"\n\n @property\n def serializer(self):\n return NsdPackage.SERIALIZER\n\n\nclass VnfdPackage(DescriptorPackage):\n DESCRIPTOR_TYPE = \"vnfd\"\n SERIALIZER = convert.RwVnfdSerializer()\n\n @property\n def descriptor_type(self):\n return \"vnfd\"\n\n @property\n def serializer(self):\n return VnfdPackage.SERIALIZER\n\n\nclass PackageChecksumValidator(object):\n \"\"\" This class uses the checksums.txt file in the package\n and validates that all files in the package match the checksum that exists within\n the file.\n \"\"\"\n CHECKSUM_FILE = \"{prefix}checksums.txt\"\n\n def __init__(self, log):\n self._log = log\n\n @classmethod\n def get_package_checksum_file(cls, package):\n checksum_file = cls.CHECKSUM_FILE.format(prefix=package.prefix)\n if checksum_file not in package.files:\n raise FileNotFoundError(\"%s does not exist in archive\" % checksum_file)\n\n return checksum_file\n\n def validate(self, package):\n \"\"\" Validate file checksums match that in the checksums.txt\n\n Arguments:\n package - The Descriptor Package which possiblity contains checksums.txt\n\n Returns: A list of files that were validated by the checksums.txt\n\n Raises:\n PackageValidationError - The package validation failed for some\n generic reason.\n PackageFileChecksumError - A file within the package did not match the\n checksum within checksums.txt\n \"\"\"\n validated_files = []\n\n try:\n checksum_file = PackageChecksumValidator.get_package_checksum_file(package)\n with package.open(checksum_file) as checksum_hdl:\n archive_checksums = checksums.ArchiveChecksums.from_file_desc(checksum_hdl)\n except (FileNotFoundError, PackageError) as e:\n self._log.warning(\"Could not open package checksum file. Not validating checksums.\")\n return validated_files\n\n for pkg_file in package.files:\n if pkg_file == checksum_file:\n continue\n\n pkg_file_no_prefix = pkg_file.replace(package.prefix, \"\", 1)\n if pkg_file_no_prefix not in archive_checksums:\n self._log.warning(\"File %s not found in checksum file %s\",\n pkg_file, checksum_file)\n continue\n\n try:\n with package.open(pkg_file) as pkg_file_hdl:\n file_checksum = checksums.checksum(pkg_file_hdl)\n except PackageError as e:\n msg = \"Could not read package file {} for checksum validation: {}\".format(\n pkg_file, str(e))\n self._log.error(msg)\n raise PackageValidationError(msg) from e\n\n if archive_checksums[pkg_file_no_prefix] != file_checksum:\n msg = \"{} checksum ({}) did match expected checksum ({})\".format(\n pkg_file, file_checksum, archive_checksums[pkg_file_no_prefix]\n )\n self._log.error(msg)\n raise PackageFileChecksumError(pkg_file)\n\n validated_files.append(pkg_file)\n\n return validated_files\n\n\nclass TarPackageArchive(object):\n \"\"\" This class represents a package stored within a tar.gz archive file \"\"\"\n def __init__(self, log, tar_file_hdl, mode=\"r\"):\n self._log = log\n self._tar_filepath = tar_file_hdl\n self._tar_infos = {}\n\n self._tarfile = tarfile.open(fileobj=tar_file_hdl, mode=mode)\n\n self._load_archive()\n\n def __repr__(self):\n return \"TarPackageArchive(%s)\" % self._tar_filepath\n\n def _get_members(self):\n return [info for info in self._tarfile.getmembers()]\n\n def _load_archive(self):\n self._tar_infos = {info.name: info for info in self._get_members() if info.name}\n\n def __del__(self):\n self.close()\n\n def close(self):\n \"\"\" Close the opened tarfile\"\"\"\n if self._tarfile is not None:\n self._tarfile.close()\n self._tarfile = None\n\n @property\n def filenames(self):\n \"\"\" The list of file members within the tar file \"\"\"\n return [name for name in self._tar_infos if tarfile.TarInfo.isfile(self._tar_infos[name])]\n\n def open_file(self, rel_file_path):\n \"\"\" Opens a file within the archive as read-only, byte mode.\n\n Arguments:\n rel_file_path - The file path within the archive to open\n\n Returns:\n A file like object (see tarfile.extractfile())\n\n Raises:\n ArchiveError - The file could not be opened for some generic reason.\n \"\"\"\n if rel_file_path not in self._tar_infos:\n raise ArchiveError(\"Could not find %s in tar file\", rel_file_path)\n\n try:\n return self._tarfile.extractfile(rel_file_path)\n except tarfile.TarError as e:\n msg = \"Failed to read file {} from tarfile {}: {}\".format(\n rel_file_path, self._tar_filepath, str(e)\n )\n self._log.error(msg)\n raise ArchiveError(msg) from e\n\n def create_package(self):\n \"\"\" Creates a Descriptor package from the archive contents \"\"\"\n package = DescriptorPackage.from_package_files(self._log, self.open_file, self.filenames)\n for pkg_file in self.filenames:\n package.add_file(pkg_file, self._tar_infos[pkg_file].mode)\n\n return package\n\n\nclass TemporaryPackage(object):\n \"\"\" This class is a container for a temporary file-backed package\n\n This class contains a DescriptorPackage and can be used in place of one.\n Provides a useful context manager which will close and destroy the file\n that is backing the DescriptorPackage on exit.\n \"\"\"\n def __init__(self, log, package, file_hdl):\n self._log = log\n self._package = package\n self._file_hdl = file_hdl\n\n if not hasattr(self._file_hdl, \"name\"):\n raise ValueError(\"File handle must have a name attribute\")\n\n def __getattr__(self, attr):\n return getattr(self._package, attr)\n\n def __enter__(self):\n return self._package\n\n def __exit__(self, type, value, tb):\n self.close()\n\n def filename(self):\n \"\"\" Returns the filepath with is backing the Package \"\"\"\n return self._file_hdl.name\n\n def package(self):\n \"\"\" The contained DescriptorPackage instance \"\"\"\n return self._package\n\n def close(self):\n \"\"\" Close and remove the backed file \"\"\"\n filename = self._file_hdl.name\n\n try:\n self._file_hdl.close()\n except OSError as e:\n self._log.warning(\"Failed to close package file: %s\", str(e))\n\n try:\n os.remove(filename)\n except OSError as e:\n self._log.warning(\"Failed to remove package file: %s\", str(e))\n","sub_path":"modules/core/mano/rwlaunchpad/plugins/rwlaunchpadtasklet/rift/package/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":21251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"309225418","text":"from json import dump\nfrom pandas import DataFrame\nfrom inspect import currentframe\n\n\n# a function used to collect the warnings to store in database\n# in other words, if a user submitted flagged data we want to store that information somewhere in the database to make it easier to hunt down flagged data\ndef collect_error_messages(errs):\n \"\"\"\n errs is the list of errors or warnings that were collected during the checking process\n offset is the number of rows the excel files are offsetted, based on how the people set up their data submission templates\n \"\"\"\n\n\n assert isinstance(errs, list), \"function - collect_warnings - errs object is not a list\"\n if errs == []:\n return []\n assert all([isinstance(x, dict) for x in errs]), \"function - collect_warnings - errs list contains non-dictionary objects\"\n \n errs = [e for e in errs if len(e) > 0]\n for k in ('columns','rows','table','error_message'):\n assert all([k in x.keys() for x in errs]), f\"function - collect_warnings - '{k}' not found in keys of a dictionary in the errs list\"\n \n\n output = [\n {\n # This will be written to a json and stored in the submission directory\n # to be read in later during the final submission routine, \n # or in the routine which marks up their excel file\n \"columns\" : e['columns'],\n \"table\" : e['table'],\n \"row_number\" : r,\n \"message\" : f\"{e['columns']} - {e['error_message']}\"\n }\n for e in errs\n for r in e['rows']\n ]\n\n output = DataFrame(output).groupby(['row_number', 'table']) \\\n .apply(\n # .tolist() doesnt work. \n lambda x: '; '.join( list(x['message']) ) \n ).to_dict() \n\n \n return [{'row_number': k[0], 'table': k[1], 'message': v} for k, v in output.items()]\n\n\n\ndef correct_row_offset(lst, offset):\n # By default the error and warnings collection methods assume that no rows were skipped in reading in of excel file.\n # It adds 1 to the row number when getting the error/warning, since excel is 1 based but the python dataframe indexing is zero based.\n # Therefore the row number in the errors and warnings will only match with their excel file's row if the column headers are actually in \n # the first row of the excel file.\n # These next few lines of code should correct that\n\n [\n e.update(\n { \"rows\" : [ r + offset + 1 + 1 for r in e['rows']] }\n )\n for e in lst\n \n ]\n\n return lst\n\n\n\ndef save_errors(errs, filepath):\n errors_file = open(filepath, 'w')\n dump(\n collect_error_messages(errs),\n errors_file\n )\n errors_file.close()\n\n\n","sub_path":"proj/utils/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"209078428","text":"import random\nimport pygame\n\n\nclass Platforms:\n def __init__(self, posx, posy):\n self.image = pygame.image.load('leaf1.png')\n self.rectangle = pygame.Rect(posx, posy, 60, 20)\n self.pos = (posx, posy)\n def display(self, surface):\n #surface.blit(self.image, (self.rectangle.left, self.rectangle.top))\n pygame.draw.rect(surface, (0, 255, 255), self.rectangle)\n\n\nclass Character():\n\n def __init__(self,w,h,iw,ih,image):\n self.rectangle = pygame.Rect(w/2,(h-70),iw,ih)\n self.img = pygame.image.load(image).convert()\n self.vx = 10\n self.vy = 25\n self.jump = 20\n self.gravity = 0\n self.shift = 0\n\n\n def display(self, surface):\n #surface.blit(self.img, (self.rectangle.left, self.rectangle.top))\n pygame.draw.rect(surface, (255,255,255), self.rectangle)\n\n\n def motion(self,keys,s_w,s_h,half):\n if keys[pygame.K_LEFT]:\n if self.rectangle.left > 0:\n self.rectangle.move_ip(-self.vx, 0)\n else:\n self.rectangle.x = s_w - self.rectangle.width\n\n if keys[pygame.K_RIGHT]:\n if self.rectangle.right < s_w:\n self.rectangle.move_ip(self.vx, 0)\n else:\n self.rectangle.x = 0\n\n if not self.jump:\n self.rectangle.y += self.gravity\n self.gravity += 1\n\n elif self.jump:\n if self.rectangle.y >= half:\n self.rectangle.y -= self.jump\n else:\n self.shift += self.jump\n self.jump -= 1\n\n if self.rectangle.bottom > s_h:\n self.jump = 20\n self.gravity = 0\n\n#--------------------\n\npygame.init()\nclock = pygame.time.Clock()\n\n# Variables\n\nscore = 0\ns_w = 500\ns_h = 750\ni_w = 50\ni_h = 50\nhalf = s_h/2\nshift = 0\nspawn = True\nmoving = False\n\n# Screen/background details\n\nscreen = pygame.display.set_mode((s_w, s_h))\npygame.display.set_caption(\"Doodle Jump\")\n\nbackground = pygame.image.load(\"images/tree.png\")\n\ngame = True\n\n\nplayer = Character(s_w,s_h,i_w,i_h,\"leaf1.png\")\nplatforms = []\n\n# Create initial platforms\n\nfor y in range(-1400, 700, 50):\n x = random.randint(0, s_w - 60)\n p = Platforms(x, y)\n platforms.append(p)\n\nwhile game:\n clock.tick(60)\n screen.fill((0,0,0))\n\n\n # Basic event calling\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game = False\n\n\n keys = pygame.key.get_pressed()\n player.motion(keys,s_w,s_h,half)\n\n # Testing collision between player and platforms\n\n for p in platforms:\n check = False\n p.display(screen)\n\n # Testing collision between player and platforms\n\n if player.rectangle.colliderect(p.rectangle):\n future_loc = p.rectangle.y - player.jump\n if player.rectangle.bottom >= future_loc and player.gravity:\n player.jump = 20\n player.gravity = 0\n\n # Shifting the platform\n\n if player.shift > 0:\n for p in platforms:\n p.rectangle.move_ip(0, player.shift)\n player.shift = 0\n\n\n # Displaying on screen\n player.display(screen)\n pygame.display.flip()\n\n\npygame.quit()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88382649","text":"import requests\nfrom bs4 import BeautifulSoup\n# 模拟浏览器访问网站服务器\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36\"\n}\n# 分页查询访问服务器\nfor start_num in range(0, 250, 25):\n response = requests.get(\"https://movie.douban.com/top250?start=\"+str(start_num)+\"&filter=\", headers=headers)\n # print(response.status_code)\n # print(response.text)\n\n # 获取返回页面内容\n html = response.text\n # 网页html格式\n soup = BeautifulSoup(html, \"html.parser\")\n # 查询span标签class类型为title的内容\n all_titles = soup.findAll(\"span\", attrs={\"class\", \"title\"})\n # 遍历数组,找到题目的内容,并且不包含“/”\n for title in all_titles:\n title_str = title.string\n if \"/\" not in title_str:\n print(title_str)\n\n\n\n","sub_path":"crawer/scrape_douban.py","file_name":"scrape_douban.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"58344127","text":"# encoding=utf-8\n# Date: 2018-09-11\n# Author: MJUZY\n\n\nimport json\nimport cmath\nimport eventlet\nimport numpy as np\nimport os\nimport re\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium.common.exceptions import TimeoutException\nimport time\nfrom TransferTypes import Transfer2TimeType, Transfer2FloatType\nimport datetime\nimport urllib.request\nfrom urllib import parse\n\n\ndef catchFromScripts_Steps(m_script):\n weibo_content1 = '' # Initialize the variable weibo_page_title\n weibo_created_time = '' # Initialize the variable weibo_created_time\n weibo_uid = ''\n weibo_pic_url = []\n weibo_gender = ''\n\n for script in m_script:\n res_content1 = r'\"content1\": \"(.*?)\"'\n\n weibo_content1 = re.findall(res_content1, script)\n print(\"weibo_content1 : \", weibo_content1)\n if len(weibo_content1) != 0:\n weibo_content1 = weibo_content1[0]\n else:\n weibo_content1 = ''\n\n for script in m_script:\n # 注意:created_at 是一个类似json 的key\n res_created_time = r'\"created_at\": \"(.*?)\"'\n\n weibo_created_time = re.findall(res_created_time, script)\n print(\"weibo_created_time : \", weibo_created_time)\n if len(weibo_created_time) == 0:\n return weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_content1\n weibo_created_time = weibo_created_time[0]\n\n for script in m_script:\n res_uid = r'\"id\": (.*?),'\n\n weibo_uid = re.findall(res_uid, script)\n print(\"weibo-uid : \", weibo_uid)\n weibo_uid = weibo_uid[1]\n\n for script in m_script:\n res_url = r'\"url\": \"(.*?)\"'\n\n weibo_pic_url = re.findall(res_url, script)\n print(\"weibo_pic_url : \", weibo_pic_url)\n\n for script in m_script:\n res_gender = r'\"gender\": \"(.*?)\"'\n\n weibo_gender = re.findall(res_gender, script)\n print(\"weibo_gender : \", weibo_gender)\n weibo_gender = weibo_gender[0]\n\n return weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_content1\n\n\ndef catchFromScipt(html_script, HTML_data):\n weibo_uid = ''\n weibo_created_time = ''\n weibo_pic_url = []\n weibo_gender = ''\n weibo_page_title = []\n weibo_content1 = ''\n\n m_script = re.findall(html_script, HTML_data, re.S | re.M)\n\n weibo_page_title = [] # Initialize the variable weibo_page_title\n for script in m_script:\n res_page_title = r'\"page_title\": \"(.*?)\"'\n\n weibo_page_title = re.findall(res_page_title, script)\n\n \"\"\"\n : maybe you can use the sign : \"·\" to create a new filter\n \"\"\"\n\n if (weibo_page_title != []):\n if weibo_page_title[0] != '':\n if not (\"#\" in weibo_page_title[0]):\n if not (\"视频\" in weibo_page_title[0]):\n if (\"·\" in weibo_page_title[0]):\n weibo_page_title = weibo_page_title[0]\n\n weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_content1 = catchFromScripts_Steps(\n m_script)\n else:\n weibo_page_title = ''\n\n weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_content1 = catchFromScripts_Steps(\n m_script)\n else:\n weibo_page_title = ''\n\n weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_content1 = catchFromScripts_Steps(\n m_script)\n else:\n weibo_page_title = ''\n\n weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_content1 = catchFromScripts_Steps(m_script)\n\n return weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_page_title, weibo_content1\n\n\ndef extractINFO(HTML_data):\n html_script = r''\n\n weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_page_title, weibo_content1 = catchFromScipt(\n html_script, HTML_data)\n\n return weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_page_title, weibo_content1\n\n\ndef myRequest(req, timeout_mark):\n data = urllib.request.urlopen(req, timeout=5)\n print(\"---sleep---0.5---second---\")\n time.sleep(0.5)\n\n read_data = data.read().decode('utf-8', 'ignore')\n\n timeout_mark = False\n return read_data, timeout_mark\n\n\ndef catchWeibo_HTML(scheme):\n req = urllib.request.Request(\n scheme) # : url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=1259110474'\n req.add_header(\"User-Agent\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0\")\n\n timeout_mark = True\n while timeout_mark:\n try:\n read_data, timeout_mark = myRequest(req, timeout_mark)\n except:\n print(\"---Time Out ! And Sleep 2 Seconds !---\")\n time.sleep(2)\n timeout_mark = True\n\n return read_data\n\n\ndef getYear(weibo_created_time):\n year = weibo_created_time.split(' ')\n year = year[5]\n\n return year\n\n\ndef composeURL(loc, key):\n \"\"\"\n url call reference:\n https://restapi.amap.com/v3/geocode/geo?address=北京市朝阳区阜通东大街6号&output=XML&key=<用户的key>\n\n \"\"\"\n add = parse.quote(loc)\n\n pre = \"http://restapi.amap.com/v3/geocode/geo?address=\"\n url = pre + add + \"&key=\" + key\n\n req = urllib.request.urlopen(url)\n\n res = req.read().decode(\"utf-8\")\n\n return res\n\n\ndef getLngLat(key, weibo_page_title):\n loc = weibo_page_title\n\n for i in range(len(loc)):\n if loc[i] == \"·\":\n loc = loc.replace(loc[0:i + 1], '')\n break\n\n res = composeURL(loc, key)\n\n res = json.loads(res)\n\n formatted_address = res[\"geocodes\"][0][\"formatted_address\"]\n\n location_str = res[\"geocodes\"][0][\"location\"]\n\n lng = location_str.split(',')[0]\n lat = location_str.split(',')[1]\n\n return lng, lat, formatted_address\n\n\ndef tryGetData(i, weibo_url, proxy_addr, recordedINFO, process_mark, lng, lat):\n print(\"---Process : tryGetData---\")\n\n data = use_proxy(weibo_url, proxy_addr)\n\n content = json.loads(data).get('data')\n\n cards = content.get('cards')\n\n card_tot_id = 0\n\n if (len(cards) > 0):\n for j in range(len(cards)):\n\n print(\"-----正在爬取第\" + str(i) + \"页,第\" + str(j) + \"条微博------\")\n\n card_type = cards[j].get('card_type')\n\n if (card_type == 9):\n\n mblog = cards[j].get('mblog')\n text = mblog.get('text')\n\n if len(text) > 0:\n if (\"·\" in text):\n\n print()\n print()\n print()\n\n \"\"\"Initialize data dict\"\"\"\n data_dict = {}\n\n idstr = mblog.get('idstr') # 微博的idstr,储存起来,为后续爬虫再用\n # : idstr = 4281561774373070\n # (Sample): tested_url of weibo: https://m.weibo.cn/status/4281561774373070\n\n scheme = cards[j].get(\n 'scheme') # : scheme = 'https://m.weibo.cn/status/GydNfilDo?mblogid=GydNfilDo&luicode=10000011&lfid=1076031995216231'\n\n HTML_data = catchWeibo_HTML(scheme)\n print(\"lng : \", lng, \"lat : \", lat)\n\n weibo_uid, weibo_created_time, weibo_pic_url, weibo_gender, weibo_page_title, weibo_content1 = extractINFO(\n HTML_data)\n\n if weibo_uid != '':\n\n data_dict[\"uid\"] = weibo_uid\n data_dict[\"idstr\"] = idstr\n data_dict[\"gender\"] = weibo_gender\n data_dict[\"title\"] = weibo_page_title\n print(\"---\" + weibo_page_title + \"---\")\n\n lng, lat, formatted_address = getLngLat(key, weibo_page_title)\n data_dict[\"lng\"] = lng\n data_dict[\"lat\"] = lat\n data_dict[\"formatted_address\"] = formatted_address\n\n data_dict[\"content1\"] = weibo_content1\n\n data_dict[\"created_at\"] = weibo_created_time\n print(\"created_at : \", weibo_created_time)\n\n data_dict[\"text\"] = text\n data_dict[\"pic_urls\"] = weibo_pic_url\n\n year = getYear(weibo_created_time)\n if int(year) <= 2016: process_mark = False # : 发出年份小于2016的将不再爬取\n\n recordedINFO.append(data_dict)\n\n card_tot_id += 1\n else:\n process_mark = False\n\n return recordedINFO, process_mark\n\n\ndef open_Json_File_To_Write(path_to_write):\n judgeExisting = os.path.exists(path_to_write)\n if not judgeExisting:\n f1 = open(path_to_write, mode='w')\n else:\n f1 = open(path_to_write, mode='a')\n\n return f1\n\n\n# 定义页面打开函数\ndef use_proxy(url, proxy_addr): # proxy_addr = '122.241.72.191:808'\n\n req = urllib.request.Request(\n url) # : url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=1259110474'\n\n # req.add_header(\"User-Agent\", \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0\")\n req.add_header(\"User-Agent\",\n \"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1\")\n\n proxy = urllib.request.ProxyHandler({'http': proxy_addr})\n opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)\n urllib.request.install_opener(opener)\n\n request_mark = True\n while request_mark:\n try:\n data = urllib.request.urlopen(req, timeout=5)\n data_read = data.read().decode('utf-8', 'ignore')\n\n request_mark = False # 退出循环\n except:\n print(\"---Proxy Time Out !---\")\n request_mark = True\n\n return data_read\n\n\n# 获取微博主���的containerid,爬取微博内容时需要此id\ndef get_containerid(url):\n data = use_proxy(url, proxy_addr)\n data_json = json.loads(data)\n\n containerid = ''\n\n content = data_json.get('data')\n\n try:\n for data in content.get('tabsInfo').get('tabs'):\n if (data.get('tab_type') == 'weibo'):\n containerid = data.get('containerid')\n print(\"containerid : \", containerid)\n except:\n return containerid\n\n return containerid\n\n\ndef writeData(file, recordedINFO):\n fh = open_Json_File_To_Write(file)\n for data in recordedINFO:\n a = json.dumps(data)\n b = str(a) + \"\\n\"\n\n fh.write(b)\n\n fh.close()\n\n\ndef getWeibo(id, file, lng, lat):\n print(\"---Process : get_weibo---\")\n\n \"\"\"\n 注意:现在进入到了提取有POI的微博的数据的环节\n \"\"\"\n\n i = 1\n\n process_mark = True\n\n POIWeibo_Count = 0\n\n while process_mark:\n\n \"\"\": url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=1259110474'\"\"\"\n url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=' + id\n\n containerid = get_containerid(url)\n if containerid != '':\n\n \"\"\": url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=1259110474&containerid=1076031259110474&page=1'\"\"\"\n weibo_url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=' + id + \\\n '&containerid=' + containerid + '&page=' + str(i)\n\n recordedINFO = [] # 该博主的每条微博信息为一个元素\n \"\"\"try:\"\"\"\n recordedINFO, process_mark = tryGetData(i, weibo_url, proxy_addr, recordedINFO, process_mark, lng, lat)\n \"\"\"\n except Exception as e:\n\n print(e)\n\n print(\"---Now sleep for 3 second to Stop this process---\")\n time.sleep(3)\n \"\"\"\n\n if recordedINFO != []:\n writeData(file, recordedINFO)\n\n POIWeibo_Count += len(recordedINFO)\n print(\"POIWeibo_Count : \", POIWeibo_Count)\n\n print(\"content of one page: \")\n for record_sample in recordedINFO:\n print(record_sample)\n else:\n process_mark = False\n\n i += 1\n\n if i == 21:\n if POIWeibo_Count == 0:\n process_mark = False # 从而退出循环\n\n if i == 50:\n if POIWeibo_Count < 3:\n process_mark = False\n\n if i == 70:\n if POIWeibo_Count < 4:\n process_mark = False\n\n\ndef GoThrough_Current_Page(obj, vip_panel_list, panel_id_record, length_panel_list, recordedINFO):\n print(\"---Go Through Current Page !---\")\n\n while panel_id_record < length_panel_list:\n\n vip_panel_sample = vip_panel_list[panel_id_record]\n\n vip_panel_text = vip_panel_sample.text\n if \"·\" in vip_panel_text:\n recordedINFO.append(vip_panel_text)\n print(\"---panel_id_record---\", panel_id_record)\n\n panel_id_record += 1\n\n return vip_panel_list, panel_id_record, recordedINFO, obj\n\n\ndef get_Weibo_host(obj, host_url, file):\n panel_id_record = 0\n\n length_panel_change = True\n\n \"\"\"\n 注意:现在开始进入到微博主页\n \"\"\"\n obj.get(host_url)\n\n print(\"---sleep 1.5 after get host page !---\")\n time.sleep(1.5)\n\n vip_panel_list = obj.find_elements_by_class_name(\"weibo-text\")\n length_panel_list = len(vip_panel_list)\n print(\"---length_panel_list---\", length_panel_list)\n if length_panel_list > 0:\n\n recorded_POIPanel_Texts = [] # 初始化panel Text记录器\n\n while length_panel_change:\n \"\"\"\n recordedINFO改成记录有POI的微博的标号\n \"\"\"\n vip_panel_list, panel_id_record, recorded_POIPanel_Texts, obj = GoThrough_Current_Page(obj, vip_panel_list,\n panel_id_record,\n length_panel_list,\n recorded_POIPanel_Texts)\n print(\"---One Loop Finished !---\")\n\n # 执行js代码(让滚动条向下偏移n个像素(作用:动态加载了更多信息))\n js = 'var q=document.body.scrollTop=10000'\n obj.execute_script(js) # 该函数可以执行一组字符串形式的js代码\n\n print(\"---滚动条下拉---\")\n print(\"---Sleep 2 Seconds for the more INFO Loaded !---\")\n time.sleep(2)\n\n vip_panel_list = obj.find_elements_by_class_name(\"weibo-text\")\n newlength_panel_list = len(vip_panel_list)\n print(\"---newlength_panel_list---\", newlength_panel_list)\n\n if not newlength_panel_list > length_panel_list:\n length_panel_change = False\n\n return recorded_POIPanel_Texts\n else:\n length_panel_list = newlength_panel_list\n\n\ndef writeTimeLog(_dir, uid, timeLogFileName):\n json_path = _dir + uid + \"/\" + timeLogFileName\n\n log_data = {}\n\n nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 现在的时间\n construct1 = nowTime.split('-')\n\n year = construct1[0]\n month = construct1[1]\n day = ((construct1[2]).split(' '))[0]\n\n log_data[\"year\"] = year\n log_data[\"month\"] = month\n log_data[\"day\"] = day\n\n fh = open(json_path, mode='w') # 必须重写\n\n a = json.dumps(log_data)\n b = str(a) + \"\\n\"\n\n fh.write(b)\n fh.close()\n\n return\n\n\ndef getUSRID(obj):\n current_url = obj.current_url # : current_url = 'https://m.weibo.cn/u/2145605952?uid=2145605952&luicode=10000011&lfid=2304410021114.305248_30.60786_'\n construct1 = current_url.split('/')\n current_url = construct1[4]\n construct1 = current_url.split('?')\n uid = construct1[0]\n\n return uid\n\n\ndef constructURL(random, rightBoundage, downBoundage, ori_lng, ori_lat):\n lng = random.uniform(ori_lng, rightBoundage) # 随机数范围\n lat = random.uniform(downBoundage, ori_lat) # 随机数范围\n\n BEGIN_URL = 'https://m.weibo.cn/p/index?containerid=2304410021' + str(lng) + '_' + str(\n lat) + '_&needlocation=1&uid=&count=10&page=1&luicode=&lfid=&featurecode='\n\n print(\"---New lng : \", lng, \" lat : \", lat, \"---\")\n\n return BEGIN_URL, lng, lat\n\n\ndef configDriver():\n dcap = dict(DesiredCapabilities.PHANTOMJS) # 设置userAgent\n dcap[\"phantomjs.page.settings.userAgent\"] = (\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0\")\n\n obj = webdriver.PhantomJS(executable_path='./phantomjs-2.1.1-windows/bin/phantomjs.exe',\n desired_capabilities=dcap) # 加载驱动\n\n return obj\n\n\ndef mkDocument(_dir, uid):\n docPath = _dir + uid\n if not os.path.exists(docPath):\n os.makedirs(docPath)\n\n return docPath\n else:\n return ''\n\n\ndef obj_Get(obj, BEGIN_URL):\n getURLProcess_mark = True\n\n tryConnectLoop_mark = True\n\n while tryConnectLoop_mark:\n try:\n eventlet.monkey_patch()\n while getURLProcess_mark:\n with eventlet.Timeout(10, False):\n obj.get(BEGIN_URL)\n getURLProcess_mark = False # 从而退出循环\n\n tryConnectLoop_mark = False # 从而退出最外层循环\n except:\n tryConnectLoop_mark = True\n\n print(\"---obj_Get Error !---sleep 3 seconds !---\")\n time.sleep(3)\n\n return obj\n\n\nif __name__ == \"__main__\":\n\n random = np.random.RandomState(12) # RandomState生成随机数种子\n\n key = \"b48ae19da63ad0863828a44a88d10ba9\"\n\n _dir = \"./\"\n _dir = mkDocument(_dir, \"Accounts_Wuhan\")\n _dir += \"/\"\n \"\"\"\n : 不要轻易改变该默认项\n 要改的话,必须\n 上下两个 \"Accounts\"\n 同时改动为相同的!\n \"\"\"\n _dir = \"./Accounts_Wuhan/\"\n\n timeLogFileName = \"TimeLog.json\"\n\n obj = configDriver()\n\n # 设置代理IP\n proxy_addr = \"122.241.72.191:808\"\n\n ori_lng = 113.6833\n ori_lat = 31.36666\n \"\"\"Sample lng : 114.78330000000042 lat : 31.36666\"\"\"\n rightBoundage = 115.0833\n downBoundage = 29.9666\n\n BEGIN_URL, lng, lat = constructURL(random, rightBoundage, downBoundage, ori_lng, ori_lat)\n obj = obj_Get(obj, BEGIN_URL)\n print(\"lng : \" + str(lng) + \" lat : \" + str(lat))\n\n Loop_Mark = True\n while Loop_Mark:\n print(\"---waite 2 second for Get(BEGIN_URL) !---\")\n time.sleep(2)\n\n \"\"\"声明index暂存变量\n 目前是在“此地周边”进行的列表性点击\n \"\"\"\n click_i = 1 # 注意:初始值为1 是规律\n\n scorll_i = 0 # 记录滚动滑块的次数\n\n \"\"\"try:\"\"\"\n box_list = obj.find_elements_by_class_name(\"m-text-cut\")\n box_length = len(box_list)\n print(\"box_length : \", box_length)\n\n while click_i < box_length:\n\n boxes_sample = box_list[click_i]\n boxes_sample.click()\n obj.refresh()\n\n print(\"lng : \" + str(lng) + \" lat : \" + str(lat))\n\n print(\"---waite 1 second for the refreshing---\")\n time.sleep(1)\n\n try:\n docPath = ''\n uid = getUSRID(obj)\n # 临时测试:--------------------------------------\n # 测试:5313321908\n # 曾出错���试:3904590483\n # uid = '3904590483'\n # 曾出错测试:6174060595\n # uid = '6174060595'\n # 曾出错测试:'3636204462'\n # uid = '3636204462'\n print(\"uid : \", uid)\n except:\n uid = 'abc'\n\n try:\n uid_int = int(uid) # 有时:uid 不是数字,要跳过\n docPath = mkDocument(_dir, uid)\n except:\n docPath = ''\n\n if docPath != '':\n writeTimeLog(_dir, uid, timeLogFileName)\n\n file = docPath + \"/\" + uid + \".json\"\n\n \"\"\"This is the logic left before:\n\n host_url = 'https://m.weibo.cn/u/' + str(uid)\n print(\"---host_url !---\")\n\n recorded_POIPanel_Texts = get_Weibo_host(obj, host_url, file)\n\n POIExist_Count = len(recorded_POIPanel_Texts)\n \"\"\"\n\n getWeibo(uid, file, lng, lat)\n else:\n print(\"The Account Exists ! \")\n\n # 去click 下一个img-box\n # 注意:+2 是规律\n click_i += 2\n\n print(\"click_i : \", click_i)\n print(\"scroll_i : \", scorll_i)\n\n if click_i < box_length:\n print(\"---click_i < box_length !---\")\n obj = obj_Get(obj, BEGIN_URL)\n\n print(\"---waite 2 second for Get(BEGIN_URL) !---\")\n time.sleep(2)\n\n box_list = obj.find_elements_by_class_name(\"m-text-cut\")\n box_length = len(box_list)\n print(\"---newlength_panel_list---\", box_length)\n\n elif click_i >= box_length:\n print(\"---click_i >= box_length !---\")\n\n scorll_i += 1\n if scorll_i == 2:\n break # 从而退出该while 循环\n\n # 执行js代码(让滚动条向下偏移n个像素(作用:动态加载了更多信息))\n js = 'var q=document.body.scrollTop=10000'\n obj.execute_script(js) # 该函数可以执行一组字符串形式的js代码\n\n print(\"---滚动条下拉---\")\n print(\"---Sleep 2 Seconds for the more INFO Loaded !---\")\n time.sleep(2)\n\n box_list = obj.find_elements_by_class_name(\"m-img-box\")\n new_box_list_length = len(box_list)\n print(\"---newlength_panel_list---\", new_box_list_length)\n\n if not new_box_list_length > click_i:\n break # 从而退出该while 循环\n else:\n box_length = new_box_list_length\n\n print(\"---退出while 循环---\")\n\n \"\"\"上面的做完才构造新的URL\"\"\"\n BEGIN_URL, lng, lat = constructURL(random, rightBoundage, downBoundage, ori_lng, ori_lat)\n obj = obj_Get(obj, BEGIN_URL)\n\n \"\"\"\n except:\n print(\"---Error Appearance---\")\n time.sleep(2)\n \"\"\"\n","sub_path":"PhantomjsSpider_Wuhan_Using/PhantomjsSpider_Wuhan_Using_Loc2lnglat.py","file_name":"PhantomjsSpider_Wuhan_Using_Loc2lnglat.py","file_ext":"py","file_size_in_byte":23056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127258","text":"def longestarray(array):\n maximum = 0\n counter = 0\n difference = []\n for j in range(N-1):\n difference.append(array[j] - array[j+1])\n difference.append(-1e9)\n for k in range(len(difference)-1):\n if difference[k] == difference[k+1]:\n counter += 1\n else:\n maximum = max(maximum, counter)\n counter = 0\n return maximum+2\n\n\n\n\ntestcases = int(input())\nfor i in range(testcases):\n N = int(input())\n numbers = list(map(int, input().split()))\n result = longestarray(numbers)\n print('Case #' + str(i+1) + ': ' + str(result))","sub_path":"longestarray(1).py","file_name":"longestarray(1).py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189235976","text":"import random\nimport math\nimport numpy as np\n\nCONST_UP = 0\nCONST_RIGHT = 1\nCONST_DOWN = 2\nCONST_LEFT = 3\n\ndef main():\n g = Game(4)\n #g.play()\n g.initialize()\n player = AI()\n player.solveGame(g, 2,output = True)\n #player.findBestEnergyParam()\n\nclass Game:\n\n def __init__(self, size):\n self.size = size\n self.array = [[0 for i in range(size)] for i in range(size)]\n self.allMoves = [CONST_UP, CONST_RIGHT, CONST_DOWN, CONST_LEFT]\n self.possibleMoves = []\n\n def getCell(self, x, y):\n return self.array[x][y]\n\n ###NEW###\n def getState(self):\n return np.array(self.array[0] + self.array[1] + self.array[2] + self.array[3], ndmin = 2)\n ###NEW###\n def isOver(self):\n return len(self.possibleMoves) == 0\n\n #have to start the game with one tile in it\n def initialize(self):\n x = random.randint(0, self.size-1)\n y = random.randint(0, self.size-1)\n self.array[x][y] = 2\n self.setPossibleMoves()\n\n def reset(self):\n self.array = [[0 for i in range(self.size)] for i in range(self.size)]\n\n def copy(self):\n result = Game(self.size)\n result.array = self.array\n return result\n\n ###NEW###\n def makeMove(self, move):\n if type(move) == type(\"string\"):\n move = move.lower()\n if move in ['u', 'up', '2', CONST_UP]:\n self.moveUp()\n elif move in ['d', 'down', '4', CONST_DOWN]:\n self.moveDown()\n elif move in ['r', 'right', '3', CONST_RIGHT]:\n self.moveRight()\n elif move in ['l','left', '1', CONST_LEFT]:\n self.moveLeft()\n\n ###NEW###\n @staticmethod\n def makeShift(grid, move):\n newGrid = None\n changed = False\n if type(move) == type(\"string\"):\n move = move.lower()\n if move in ['u', 'up', '2', CONST_UP]:\n newGrid, changed = Game.shiftUp(grid, False)\n elif move in ['d', 'down', '4', CONST_DOWN]:\n newGrid, changed = Game.shiftDown(grid, False)\n elif move in ['r', 'right', '3', CONST_RIGHT]:\n newGrid, changed = Game.shiftRight(grid, False)\n elif move in ['l','left', '1', CONST_LEFT]:\n newGrid, changed = Game.shiftLeft(grid, False)\n\n return (newGrid, changed)\n\n ###NEW###\n def setPossibleMoves(self):\n result = []\n for move in self.allMoves:\n newGrid, changed = Game.makeShift(self.array, move)\n if changed:\n result += [move]\n self.possibleMoves = result\n\n def moveLeft(self):\n newArray, changed = Game.shiftLeft(self.array, True)\n self.array = newArray\n if changed:\n self.setPossibleMoves()\n return changed\n\n def moveRight(self):\n newArray, changed = Game.shiftRight(self.array, True)\n self.array = newArray\n if changed:\n self.setPossibleMoves()\n return changed\n\n def moveUp(self):\n newArray, changed = Game.shiftUp(self.array, True)\n self.array = newArray\n if changed:\n self.setPossibleMoves()\n return changed\n\n def moveDown(self):\n newArray, changed = Game.shiftDown(self.array, True)\n self.array = newArray\n if changed:\n self.setPossibleMoves()\n return changed\n\n @staticmethod\n def pickRandomEmptyLoc(grid):\n emptyLocs = [(x,y) for x in range(len(grid)) for y in range(len(grid)) if grid[x][y] == 0 ]\n if len(emptyLocs) > 0:\n return emptyLocs[int(random.random()*len(emptyLocs))]\n else:\n return (-1,-1)\n\n @staticmethod\n def shiftLeft(grid, spawn = True):\n resultArray = []\n size = len(grid)\n for i in range(size):\n row = grid[i]\n reduced_row = []\n for entry in row:\n if not entry == 0:\n reduced_row += [entry]\n final_row = []\n for j in range(len(reduced_row)):\n if j < len(reduced_row) -1 and reduced_row[j] == reduced_row[j+1]:\n final_row += [2*reduced_row[j]]\n reduced_row[j+1] = 0\n elif reduced_row[j] > 0:\n final_row += [reduced_row[j]]\n \n final_row += [0]*(size-len(final_row))\n resultArray += [final_row]\n\n changed = not all([all([grid[i][j] == resultArray[i][j] for i in range(size)]) for j in range(size)])\n\n\n if spawn and changed:\n spawn_loc = Game.pickRandomEmptyLoc(resultArray)\n if spawn_loc[0] != -1:\n \n rand_double = random.random()\n if rand_double < .9:\n new = 2\n else:\n new = 4\n resultArray[spawn_loc[0]][spawn_loc[1]] = new\n\n return (resultArray, changed)\n\n @staticmethod\n def shiftRight(grid, spawn = True):\n resultArray = []\n size = len(grid)\n for i in range(size):\n row = grid[i]\n reduced_row = []\n for entry in row:\n if not entry == 0:\n reduced_row += [entry]\n final_row = []\n reduced_row.reverse()\n for j in range(len(reduced_row)):\n if j < len(reduced_row) -1 and reduced_row[j] == reduced_row[j+1]:\n final_row += [2*reduced_row[j]]\n reduced_row[j+1] = 0\n elif reduced_row[j] > 0:\n final_row += [reduced_row[j]]\n \n final_row += [0]*(size-len(final_row))\n final_row.reverse()\n resultArray += [final_row]\n\n changed = not all([all([grid[i][j] == resultArray[i][j] for i in range(size)]) for j in range(size)])\n\n\n if spawn and changed:\n spawn_loc = Game.pickRandomEmptyLoc(resultArray)\n if spawn_loc[0] != -1:\n \n rand_double = random.random()\n if rand_double < .9:\n new = 2\n else:\n new = 4\n resultArray[spawn_loc[0]][spawn_loc[1]] = new\n\n return (resultArray, changed)\n\n @staticmethod\n def shiftUp(grid, spawn = True):\n resultArray = []\n size = len(grid)\n for i in range(size):\n col = [grid[x][i] for x in range(size)]\n reduced_col = []\n for entry in col:\n if not entry == 0:\n reduced_col += [entry]\n final_col = []\n for j in range(len(reduced_col)):\n if j < len(reduced_col) -1 and reduced_col[j] == reduced_col[j+1]:\n final_col += [2*reduced_col[j]]\n reduced_col[j+1] = 0\n elif reduced_col[j] > 0:\n final_col += [reduced_col[j]]\n \n final_col += [0]*(size-len(final_col))\n resultArray += [final_col]\n resultArray = [[resultArray[i][j] for i in range(size)] for j in range(size)]\n\n changed = not all([all([grid[i][j] == resultArray[i][j] for i in range(size)]) for j in range(size)])\n\n if spawn and changed:\n spawn_loc = Game.pickRandomEmptyLoc(resultArray)\n if spawn_loc[0] != -1:\n \n rand_double = random.random()\n if rand_double < .9:\n new = 2\n else:\n new = 4\n resultArray[spawn_loc[0]][spawn_loc[1]] = new\n\n return (resultArray, changed)\n\n @staticmethod\n def shiftDown(grid, spawn = True):\n resultArray = []\n size = len(grid)\n for i in range(size):\n col = [grid[x][i] for x in range(size)]\n reduced_col = []\n for entry in col:\n if not entry == 0:\n reduced_col += [entry]\n reduced_col.reverse()\n final_col = []\n for j in range(len(reduced_col)):\n if j < len(reduced_col) -1 and reduced_col[j] == reduced_col[j+1]:\n final_col += [2*reduced_col[j]]\n reduced_col[j+1] = 0\n elif reduced_col[j] > 0:\n final_col += [reduced_col[j]]\n \n final_col += [0]*(size-len(final_col))\n final_col.reverse()\n resultArray += [final_col]\n\n resultArray = [[resultArray[i][j] for i in range(size)] for j in range(size)]\n\n changed = not all([all([grid[i][j] == resultArray[i][j] for i in range(size)]) for j in range(size)])\n\n\n if spawn and changed:\n spawn_loc = Game.pickRandomEmptyLoc(resultArray)\n if spawn_loc[0] != -1:\n \n rand_double = random.random()\n if rand_double < .9:\n new = 2\n else:\n new = 4\n resultArray[spawn_loc[0]][spawn_loc[1]] = new\n\n return (resultArray, changed)\n\n\n def __str__(self):\n rows = []\n maxLength = 0\n for i in range(self.size):\n for j in range(self.size):\n length = len(str(self.getCell(i,j)))\n if length > maxLength:\n maxLength = length\n width = maxLength * self.size + 3*(self.size -1) + 4\n fmt = \"{:>\" + str(maxLength) + \"}\"\n\n bar = \"-\"*width + \"\\n\"\n filler = \"| \" + (\" \"*maxLength + \" | \") * self.size + \"\\n\"\n result = \"\" + bar\n for i in range(self.size):\n result += filler + \"|\"\n for j in range(self.size):\n num = self.getCell(i,j)\n if num != 0:\n s = str(num)\n else:\n s = \"\"\n result += \" \" + fmt.format(s) + \" |\"\n result += \"\\n\" + filler + bar\n\n return result\n\nclass AI:\n def __init__(self, energy_param = .12):\n self.energy_param = energy_param\n\n def rewardFunction(self, grid):\n if type(grid) == type(Game(0)):\n grid = grid.array\n return AI.decayingSum(grid) - self.energy_param*AI.energy(grid) \n\n #uses reward function, (returns final board, max value on board)\n def solveGame(self, board, depth = 2, output = True):\n \n games = [] #list of strings of grids\n\n outcomes = {\"energy\" : [], \"reward\" : [], \"energy / sum\" : []} #records the change in these over time\n move_count = 0\n masterOptions = [CONST_UP,CONST_RIGHT, CONST_DOWN, CONST_LEFT]\n\n\n options = masterOptions[:]\n while len(options) > 0:\n move_count += 1\n\n if move_count % 100 == 0 and output:\n print(move_count)\n\n move = self.exploreToDepth(board.array, depth)[1]\n\n if move == CONST_UP:\n move_made = board.moveUp()\n move_str = 'Up'\n elif move == CONST_RIGHT:\n move_made = board.moveRight()\n move_str = 'Right'\n elif move == CONST_DOWN:\n move_made = board.moveDown()\n move_str = 'Down'\n elif move == CONST_LEFT:\n move_made = board.moveLeft()\n move_str = 'Left'\n elif move == -1:\n options = []\n move_made = False\n \n if not move_made:\n if move in options:\n options.remove(move)\n else:\n options = masterOptions[:]\n reward = self.rewardFunction(board)\n outcomes[\"reward\"] += [reward]\n outcomes[\"energy\"] += [AI.energy(board)]\n outcomes[\"energy / sum\"] += [1.*AI.energy(board) / AI.sumValues(board)]\n if output:\n state = str(board)\n games += [state + move_str + \": \" + str(reward)[:5]]\n if output:\n print(combine(games))\n #print(outcomes)\n\n return (AI.maxValue(board), move_count)\n\n\n\n def exploreToDepth(self, grid, depth): #returns (average value of best move, best move)\n if type(grid) == type(Game(0)):\n grid = grid.array\n\n if depth == 0:\n return (self.rewardFunction(grid), -1)\n else:\n n = (depth + 2)\n options = list(range(4))\n values = []\n spawn = depth > 1\n for move in options[:]:\n cum_reward = 0\n remove = False\n for i in range(n):\n if move == CONST_UP: #up\n new_grid, changed = Game.shiftUp(grid, spawn)\n elif move == CONST_RIGHT:#right\n new_grid, changed = Game.shiftRight(grid, spawn)\n elif move == CONST_DOWN:#down\n new_grid, changed = Game.shiftDown(grid, spawn)\n else:#left\n new_grid, changed = Game.shiftLeft(grid, spawn)\n if changed:\n cum_reward += self.exploreToDepth(new_grid, depth -1)[0]\n else:\n remove = True\n if remove:\n options.remove(move)\n else:\n values += [1. * cum_reward / n]\n if len(options) == 0:\n return (-1, -1)\n else:\n return (max(values), options[values.index(max(values))])\n\n\n #random selection, no return value\n def randomExploreGame(self, g, output = True):\n games = []\n outcomes = {\"energy\" : [], \"reward\" : [], \"energy / sum\" : []} #records the change in these over time\n i = 0\n options = [CONST_UP, CONST_RIGHT, CONST_LEFT]\n while len(options) > 0:\n i += 1\n if i % 100 == 0:\n print(i)\n move = options[random.randint(0, len(options)-1)]\n if move == CONST_UP:\n move_made = g.moveUp()\n move_str = 'Up'\n elif move == CONST_RIGHT:\n move_made = g.moveRight()\n move_str = 'Right'\n elif move == CONST_DOWN:\n move_made = g.moveDown()\n move_str = 'Down'\n else:\n move_made = g.moveLeft()\n move_str = 'Left'\n if not move_made:\n options.remove(move)\n else:\n options = [CONST_UP, CONST_RIGHT, CONST_LEFT]\n reward = self.rewardFunction(g)\n outcomes[\"reward\"] += [reward]\n outcomes[\"energy\"] += [AI.energy(g.array)]\n outcomes[\"energy / sum\"] += [AI.energy(g.array) / AI.sumValues(g.array)]\n if output:\n state = str(g)\n games += [state + move_str + \": \" + str(reward)[:5]]\n if output:\n print(combine(games))\n #print(outcomes)\n\n @staticmethod\n def maxValue(grid):\n if type(grid) == type(Game(0)):\n grid = grid.array\n return max([max(x) for x in grid])\n\n @staticmethod\n def sumValues(grid):\n if type(grid) == type(Game(0)):\n grid = grid.array\n return sum([sum(x) for x in grid])\n\n @staticmethod\n def pctEmpty(grid):\n if type(grid) == type(Game(0)):\n grid = grid.array\n num_empty = sum([x.count(0) for x in grid])\n return 1. * num_empty / len(grid)**2\n\n @staticmethod\n def distribution(grid):\n dist = {}\n if type(grid) == type(Game(0)):\n grid = grid.array\n for row in grid:\n for entry in row:\n if entry in dist:\n dist[entry] += 1\n else:\n dist[entry] = 1\n return dist\n\n @staticmethod\n def decayingSum(grid):\n if type(grid) == type(Game(0)):\n grid = grid.array\n bigList = []\n for row in grid:\n bigList += row\n bigList.sort()\n result = 0\n n = len(bigList)\n for i in range(n):\n result += (1.* i/(n-1))**2 * bigList[i]\n\n return result\n\n @staticmethod\n def energy(grid):\n if type(grid) == type(Game(0)):\n grid = grid.array\n totalEnergy = 0\n for i in range(len(grid)):\n for j in range(len(grid)):\n directions = []\n if j < len(grid) - 1:\n directions += [abs(grid[i][j+1] - grid[i][j])]\n if i < len(grid) - 1:\n directions += [abs(grid[i+1][j] - grid[i][j])]\n if j > 0:\n directions += [abs(grid[i][j] - grid[i][j-1])]\n if i > 0:\n directions += [abs(grid[i][j] - grid[i-1][j])]\n totalEnergy += sum(directions) #+ min(directions)\n return totalEnergy\n\n\n def findBestEnergyParam(self):\n prevAvgMax = -100\n prevSteps = -100\n currentAvgSteps = 0\n currentAvgMax = 0\n eps = .5\n param = .075\n step = +.005\n n = 15\n results = []\n while param < .25:\n\n self.energy_param = param\n cumMax = 0\n cumSteps = 0\n for i in range(n):\n g = Game(4)\n g.initialize()\n m, steps = self.solveGame(g, False)\n cumMax += m\n cumSteps += steps\n currentAvgMax = cumMax / n\n currentAvgSteps = cumSteps / n\n print(param, step , currentAvgMax, currentAvgSteps)\n results += [(param, currentAvgMax)]\n\n param += step\n\n results.sort(key = lambda x: x[1])\n return results[-1][0]\n\nclass FeatureBuilder:\n\n def makeFeatureFromGrid(array):\n feature = []\n for row in array:\n feature += [math.log(x,2) for x in row]\n return feature\n\n def makeGridFromFeature(feature):\n grid = []\n size = len(feature)**(1./2)\n for row in range(size):\n row_grid = []\n for col in range(size):\n row_grid += [2**feature(row*size + col)]\n grid += [row_grid]\n return grid\n\n def findEquivalentGrid(feature):\n grid = makeGridFromFeature(feature)\n size = len(grid)\n move_list = [CONST_UP, CONST_RIGHT, CONST_DOWN, CONST_LEFT]\n result = [] #list of feature, move_list pairs\n #reflexive\n result += [(feature[:], move_list[:])]\n\n #flip horiz\n transformed_grid = [[grid[row][size-col] for col in range(size)] for row in range(size)]\n transformed_moves = [CONST_UP, CONST_LEFT, CONST_DOWN, CONST_RIGHT]\n result += [(makeFeatureFromGrid(transformed_grid), transformed_moves)]\n\n #flip vert\n transformed_grid = [[grid[size - row][col] for col in range(size)] for row in range(size)]\n transformed_moves = [CONST_DOWN, CONST_RIGHT, CONST_UP, CONST_LEFT]\n result += [(makeFeatureFromGrid(transformed_grid), transformed_moves)]\n\n #rotate 90 cw\n transformed_grid = [[grid[size - row][col] for col in range(size)] for row in range(size)]\n transformed_moves = [CONST_RIGHT, CONST_DOWN, CONST_LEFT, CONST_UP]\n result += [(makeFeatureFromGrid(transformed_grid), transformed_moves)]\n\n #rotate 180 cw\n transformed_grid = [[grid[size - row][size - col] for col in range(size)] for row in range(size)]\n transformed_moves = [CONST_DOWN, CONST_LEFT, CONST_UP, CONST_RIGHT]\n result += [(makeFeatureFromGrid(transformed_grid), transformed_moves)]\n\n #rotate 90 ccw\n transformed_grid = [[grid[row][size - col] for col in range(size)] for row in range(size)]\n transformed_moves = [CONST_LEFT, CONST_UP, CONST_RIGHT, CONST_DOWN]\n result += [(makeFeatureFromGrid(transformed_grid), transformed_moves)]\n\n #flip diag top left to bottom right\n transformed_grid = [[grid[col][row] for col in range(size)] for row in range(size)]\n transformed_moves = [CONST_LEFT, CONST_DOWN, CONST_RIGHT, CONST_UP]\n result += [(makeFeatureFromGrid(transformed_grid), transformed_moves)]\n\n #flip diag top right to bottom left\n transformed_grid = [[grid[size-col][size-row] for col in range(size)] for row in range(size)]\n transformed_moves = [CONST_RIGHT, CONST_UP, CONST_LEFT, CONST_DOWN]\n result += [(makeFeatureFromGrid(transformed_grid), transformed_moves)]\n\n return result\n\n\n#module level functions for manipulating strings\ndef combine(games):\n result = \"\"\n width = 4\n current = \"\"\n for i in range(len(games)):\n if i % width == 0:\n current = games[i]\n else:\n current = horizontalAdd(current, games[i])\n if (i+1) % width == 0:\n result += \"\\n\" + current\n current = \"\"\n if not current == \"\":\n result += \"\\n\" + current\n return result\n\n#add multi-line strings\ndef horizontalAdd(a, b):\n a_lines = a.split(\"\\n\")\n b_lines = b.split(\"\\n\")\n maxLen = max([len(x) for x in a_lines])\n fmt = \"{:<\" + str(maxLen) + \"}\"\n tab = \" \"*4\n result = \"\"\n for i in range(max(len(a_lines), len(b_lines))):\n a_str = \"\"\n if i < len(a_lines):\n a_str = a_lines[i]\n b_str = \"\"\n if i < len(b_lines):\n b_str = b_lines[i]\n result += fmt.format(a_str) + tab + b_str + \"\\n\"\n return result\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"code/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":21524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50762891","text":"import base64, calendar, contextlib, Cookie, gzip, io, itertools, os, pdb, shutil, sqlite3, sys, time, urllib, urlparse, zlib\n\nimport dbiface, tibiacom, update\nfrom htmldoc import HtmlDocument, tag\nfrom common import TIBSTAT_VERSION\n\nSTANCES = (\n (\"F\", \"friend\"),\n (\"A\", \"ally\"),\n (\"U\", \"unspec\"),\n (\"E\", \"enemy\"),)\nSTANCE_VALUES = tuple(map(lambda t: t[0], STANCES))\nSTANCE_CSS_CLASS = dict(STANCES)\n\n#http://www.tibiastat.com/img/tibia.gif\n\ndef char_link(name):\n return tag(\"a\", name, attrs={\"href\": tibiacom.char_page_url(name), \"class\": \"char\"})\n\ndef guild_link(name, stance):\n return tag(\"a\", name, attrs={\n \"href\": tibiacom.guild_members_url(name),\n \"class\": \" \".join((STANCE_CSS_CLASS[stance], \"guild\"))})\n\ndef world_select(htmldoc, curworld, onchange):\n selectAttrs = {\"size\": 1, \"name\": \"world\"}\n if onchange:\n selectAttrs[\"onchange\"] = \"this.form.submit();\"\n with htmldoc.open_tag(\n \"select\",\n selectAttrs,\n inline=False):\n def add_selected_world(world, attrs):\n if curworld == world:\n attrs[\"selected\"] = None\n return attrs\n htmldoc.newline()\n htmldoc.add_tag(\"option\", \"All Worlds\", attrs=add_selected_world(None, {\"value\": \"\"}))\n for world in sorted(a[\"name\"] for a in dbiface.get_worlds()):\n htmldoc.newline()\n htmldoc.add_tag(\"option\", world, attrs=add_selected_world(world, {\"value\": world}))\n\nclass StandardPageContext(object):\n def __init__(self, request):\n #self.request = request\n a = urlparse.urlparse(request.path)\n self.path = a.path\n self.queries = urlparse.parse_qs(a.query)\n self.cookies = Cookie.SimpleCookie(request.headers.getheader(\"Cookie\"))\n def get_guild_stance(self, guild):\n for g, s in self.get_all_guild_stances():\n if g == guild:\n return s\n else:\n return \"U\"\n def get_all_guild_stances(self):\n if \"guildStance\" in self.cookies:\n cookieStr = self.cookies[\"guildStance\"].value\n try:\n cookieStr = zlib.decompress(base64.b64decode(cookieStr))\n except:\n pass\n for a in cookieStr.split(\",\"):\n yield a.split(\"|\", 1)\n def get_selected_world(self):\n return self.get_query(\"world\")\n def guild_link(self, guild):\n return guild_link(guild, self.get_guild_stance(guild))\n def get_query(self, query):\n return self.queries.get(query, (None,))[-1]\n\ndef standard_page(request, title, content):\n context = StandardPageContext(request)\n body = io.BytesIO()\n sink = gzip.GzipFile(mode=\"wb\", fileobj=body)\n #sink = body\n with standard_content_wrapper(sink.write, context, title) as outfile:\n content(outfile, context)\n #print request.headers.getheader(\"Accept-Encoding\")\n request.send_response(200)\n request.send_header(\"Content-Type\", \"text/html\")\n request.send_header(\"Content-Encoding\", \"gzip\")\n request.end_headers()\n sink.close()\n body.seek(0)\n #request.wfile.write(zlib.compress(body.getvalue()))\n #assert not request.wfile.seekable()\n #assert request.wfile.tell() == 0\n shutil.copyfileobj(body, request.wfile)\n #assert request.wfile.tell() != 0\n\nSKYSCRAPER_AD = '''\n'''\n\nLINK_AD = '''\n'''\n\nSEARCH_ENGINE = '''\n
\n
\n \n \n \n \n
\n
\n\n'''\n\n@contextlib.contextmanager\ndef standard_content_wrapper(write, context, title):\n \"\"\"Add the HTML Document to the page context, ready for contents to be written to it, clean up afterwards.\"\"\"\n\n #write('''''')\n doc = HtmlDocument(write)\n headTitle = \"{0} - {1}\".format(title, context.get_selected_world() or \"All Worlds\")\n with doc.open_tag(\"html\"):\n with doc.open_tag(\"head\", inline=False):\n doc.add_tag(\"meta\", inline=False, attrs={\"name\": \"description\", \"content\": \"Tibia statistics fansite that shows current protection zone locks, online characters, guild stances and recent deaths.\"})\n doc.add_tag(\"meta\", inline=False, attrs={\"name\": \"keywords\", \"content\": \"tibia, statistics, stats, fansite, protection zone lock, pzls, pz locks, characters, guilds, online guild stances, recent deaths, deaths\"})\n doc.add_tag(\"title\", headTitle, inline=False)\n doc.add_tag(\"link\", attrs=dict(rel=\"stylesheet\", type=\"text/css\", href=\"/tibstats.css\"), inline=False)\n doc.add_tag(\"link\", attrs=dict(rel=\"icon\", type=\"image/gif\", href=\"http://static.tibia.com/images/gameguides/skull_black.gif\"), inline=False)\n with doc.open_tag(\"body\", inline=False):\n with doc.open_tag(\"div\", attrs={\"id\": \"header\", \"class\": \"bodyrow\"}, inline=False):\n doc.writelns(LINK_AD.split(\"\\n\"))\n #with doc.open_tag(\"div\", attrs={\"class\": \"bodyrow\"}, inline=False):\n #with doc.open_tag(\"div\", attrs={\"style\": \"display: table-cell\"}):\n with doc.open_tag(\"div\", attrs={\"id\": \"main\", \"class\": \"bodyrow\"}, inline=False):\n with doc.open_tag(\"div\", attrs={\"id\": \"left\"}, inline=False):\n with doc.open_tag(\"div\", {\"id\": \"menu\"}, inline=False):\n doc.add_tag(\"div\", \"Menu\", {\"id\": \"menu-title\"})\n for path, entry in PAGES.iteritems():\n if isinstance(entry, MenuPageEntry):\n #world = context.get_selected_world()\n #if world:\n # path += \"?\" + urllib.urlencode({\"world\": world})\n doc.add_tag(\"a\", entry.title, attrs={\"href\": path})\n doc.add_tag(\"br\")\n #with doc.open_tag(\"form\", attrs={\"method\": \"get\", \"class\": \"world-form\"}, inline=False):\n # doc.newline()\n # world_select(doc, context.get_selected_world(), onchange=True)\n #with doc.open_tag(\"div\", attrs={\"id\": \"left-ad\"}):\n # doc.writelns(SKYSCRAPER_AD.split(\"\\n\"))\n with doc.open_tag(\"div\", attrs={\"id\": \"center\"}, inline=False):\n with doc.open_tag(\"div\", attrs={\"id\": \"content-title\"}):\n doc.writelns(SEARCH_ENGINE.split(\"\\n\"))\n doc.write(headTitle)\n with doc.open_tag(\"div\", attrs={\"id\": \"content\"}):\n yield doc\n with doc.open_tag(\"div\", attrs={\"id\": \"footer\", \"class\": \"bodyrow\"}):\n doc.write(\"Version \" + TIBSTAT_VERSION)\n\ndef stattab_table_tag(openTag):\n return openTag(\"table\", attrs={\"class\": \"stattab\", \"cellspacing\": 1,}, inline=False)\n\ndef stattab_row_class():\n return itertools.cycle((\"odd\", \"even\"))\n\ndef human_time_diff(stamp):\n diff = dbiface.to_unixepoch(stamp) - int(time.time())\n assert isinstance(diff, int) # if this doesn't hold, we'll generate rubbish\n if diff == 0:\n return \"now\"\n if diff < 0:\n whence = \"ago\"\n diff = -diff # must be positive for identity: x == (x/y)*y + (x%y)\n elif diff > 0:\n whence = \"more\"\n humanbits = []\n for divisor, units in ((60, \"s\"), (60, \"m\"), (24, \"h\"), (None, \"d\")):\n if divisor is not None:\n bitval = diff % divisor\n else:\n bitval = diff\n humanbits.append((\"%d%s\" % (bitval, units)) if bitval else None)\n del bitval\n if divisor is None:\n break\n diff //= divisor\n if diff == 0:\n break\n del diff\n # take the 2 most significant bits, filter the zeroed ones\n return \"\".join(filter(None, itertools.islice(reversed(humanbits), 2))) + \" \" + whence\n\ndef guild_stances(outfile, context):\n doc = outfile\n world = context.get_selected_world()\n doc.add_tag(\"p\", 'Here are listed the guilds for the world you have selected. You may set your personal \"stance\" toward that guild, F=Friend, A=Ally, U=Unspecified, E=Enemy. The guild is then appropriately colored on any page where guild is mentioned to ease categorization at a glance.', attrs={\"style\": \"width: 100%\"})\n with doc.open_tag(\"form\", attrs={\"method\": \"get\"}):\n doc.write(\"World:\")\n world_select(doc, world, onchange=True)\n guildsListed = set()\n with doc.open_tag(\"form\", attrs={\"method\": \"post\",}, inline=False): #\"action\": \"/setcookie\"}):\n with stattab_table_tag(doc.open_tag):\n with doc.open_tag(\"tr\"):\n for heading in (\"Guild Name\", \"Members\") + STANCE_VALUES:\n doc.add_tag(\"th\", heading)\n if not world:\n doc.add_tag(\"th\", \"World\")\n rowClass = stattab_row_class()\n for guild, memberCount in dbiface.list_guilds(world):\n #if not world or world == guildWorld:\n with doc.open_tag(\"tr\", attrs={\"class\": rowClass.next()}, inline=False):\n doc.newline()\n doc.add_tag(\"td\", guild_link(guild, context.get_guild_stance(guild)))\n doc.add_tag(\"td\", memberCount)\n for stance in STANCE_VALUES:\n doc.newline()\n with doc.open_tag(\"td\", inline=True):\n attrs = dict(type=\"radio\", name=guild, value=stance)\n if stance == context.get_guild_stance(guild):\n attrs[\"checked\"] = None\n doc.add_tag(\"input\", attrs=attrs, inline=True)\n #if not world:\n # doc.add_tag(\"td\", guildWorld)\n guildsListed.add(guild)\n# doc.add_tag(\"input\", attrs={\"type\": \"hidden\", \"name\": \"NEXT_LOCATION\", \"value\": \"/whoisonline\"})\n for g, s in context.get_all_guild_stances():\n if g not in guildsListed:\n doc.newline()\n doc.add_tag(\"input\", attrs={\"type\": \"hidden\", \"name\": g, \"value\": s})\n doc.newline()\n doc.add_tag(\"input\", attrs={\"type\": \"submit\", \"value\": \"Change Stances!\"})\n\ndef guild_stances_page(request, title):\n if request.command == \"POST\":\n # client POSTed, form a cookie, and set it, and then redirect them to nonPOST version\n contentLength = request.headers.getheader(\"Content-Length\")\n postData = request.rfile.read(int(contentLength))\n guildStances = dict(urlparse.parse_qsl(postData, strict_parsing=True))\n cookie = Cookie.SimpleCookie()\n cookie[\"guildStance\"] = base64.b64encode(zlib.compress(\",\".join(\"|\".join(a) for a in guildStances.iteritems() if a[1] != \"U\"), 9))\n #cookie[\"guildStance\"] = \",\".join(\"|\".join(a) for a in guildStances.iteritems() if a[1] != \"U\")\n cookie[\"guildStance\"][\"max-age\"] = 30 * 24 * 60 * 60\n request.send_response(303) # See Other (GET)\n request.wfile.write(cookie.output() + '\\r\\n')\n # go back whence thee came\n request.send_header(\"Location\", request.headers.getheader(\"Referer\"))\n request.end_headers()\n else:\n standard_page(request, title, guild_stances)\n\ndef tibstats_stylesheet(request):\n #print request.headers\n with contextlib.closing(open(\"tibstats.css\", \"rb\")) as f:\n fs = os.fstat(f.fileno())\n # variant modification time\n varmtime = request.headers.getheader(\"If-Modified-Since\")\n if varmtime:\n # If-Modified-Since: Sat, 27 Feb 2010 16:13:49 GMT\n varmtime = varmtime.split(\";\", 1)[0]\n varmtime = calendar.timegm(time.strptime(varmtime, \"%a, %d %b %Y %H:%M:%S %Z\"))\n #print fs.st_mtime, varmtime\n if fs.st_mtime <= varmtime:\n request.send_response(304)\n request.end_headers()\n return\n request.send_response(200)\n request.send_header(\"Content-Type\", \"text/css\")\n request.send_header(\"Content-Length\", str(fs.st_size))\n request.send_header(\"Last-Modified\", request.date_time_string(fs.st_mtime))\n request.end_headers()\n shutil.copyfileobj(f, request.wfile)\n\ndef recent_deaths(outfile, context):\n doc = outfile\n limits = (0, 200)\n world = context.get_selected_world()\n try:\n minlevel = int(context.get_query(\"minlevel\"))\n except (ValueError, TypeError):\n minlevel = 45\n with doc.open_tag(\"form\", attrs={\"method\": \"get\"}):\n doc.write(\"World:\")\n world_select(doc, world, onchange=False)\n doc.write(\"Min Level:\")\n doc.add_tag(\"input\", attrs={\"type\": \"text\", \"name\": \"minlevel\", \"value\": minlevel, \"maxlength\": \"3\", \"size\": \"3\"})\n doc.add_tag(\"input\", attrs={\"type\": \"submit\", \"value\": \"Apply Filter\"})\n with stattab_table_tag(doc.open_tag):\n with doc.open_tag(\"tr\"):\n for a in (\"Time\", \"Deceased\", \"Level\", \"Guild\", \"Killer\", \"Accomplices\"):\n doc.add_tag(\"th\", a)\n if not world:\n doc.add_tag(\"th\", \"World\")\n killsIter = dbiface.get_last_deaths(limits, world=world, minlevel=minlevel)\n currentDeath = killsIter.next()\n killsEnded = False\n rowsMade = 0\n rowClass = stattab_row_class()\n while not killsEnded and rowsMade < 30:\n with doc.open_tag(\"tr\", attrs={\"class\": rowClass.next()}):\n doc.add_tag(\"td\", human_time_diff(currentDeath[\"stamp\"]))\n doc.add_tag(\"td\", char_link(currentDeath[\"victim\"]))\n doc.add_tag(\"td\", currentDeath[\"level\"])\n doc.add_tag(\"td\", context.guild_link(currentDeath[\"guild\"]))\n def make_killer(kill):\n if kill[\"isplayer\"]:\n s = char_link(kill[\"killer\"])\n else:\n s = kill[\"killer\"]\n return s\n data = [make_killer(currentDeath)]\n while True:\n try:\n nextKill = killsIter.next()\n except StopIteration:\n killsEnded = True\n break\n if (nextKill[\"stamp\"], nextKill[\"victim\"]) == (currentDeath[\"stamp\"], currentDeath[\"victim\"]):\n a = make_killer(nextKill)\n if nextKill[\"lasthit\"]:\n data.insert(0, a)\n else:\n data.append(a)\n else:\n #currentDeath = nextKill\n nextDeath = nextKill\n break\n doc.add_tag(\"td\", data[0])\n doc.add_tag(\"td\", \", \".join(data[1:]))\n if not world:\n doc.add_tag(\"td\", currentDeath[\"world\"])\n rowsMade += 1\n currentDeath = nextDeath\n\ndef world_online(doc, pageContext):\n doc.newline()\n world = pageContext.get_selected_world()\n #after = update.next_tibiacom_whoisonline_update() - 300\n onlineChars = list(dbiface.get_online_chars(world=world))\n #doc.write(\"This page is still being optimized.
\")\n doc.write(\"There are {0} players online on the worlds you have selected.\".format(len(onlineChars)))\n onlineChars.sort(key=lambda x: int(x[\"level\"]), reverse=True)\n with stattab_table_tag(doc.open_tag):\n with doc.open_tag(\"tr\"):\n doc.add_tag(\"th\", \"Name\")\n doc.add_tag(\"th\", \"Level\")\n doc.add_tag(\"th\", \"Vocation\")\n doc.add_tag(\"th\", \"Guild\")\n if not world:\n doc.add_tag(\"th\", \"World\")\n rowClass = stattab_row_class()\n for char in onlineChars:\n doc.newline()\n rowAttrs = {\"class\": rowClass.next()}\n if char[\"level\"] < 45:\n rowAttrs[\"class\"] += \" greyed\"\n with doc.open_tag(\"tr\", attrs=rowAttrs):\n doc.add_tag(\"td\", char_link(char[\"name\"]))\n for field in (\"level\", \"vocation\"):\n doc.add_tag(\"td\", data=str(char[field]))\n doc.add_tag(\"td\", pageContext.guild_link(char[\"guild\"]))\n if not world:\n doc.add_tag(\"td\", char[\"world\"])\n\ndef pz_locked(doc, pageContext):\n world = pageContext.get_selected_world()\n curtime = int(time.time())\n limits = (0, 30)\n #limits = (0, 200)\n doc.add_tag(\"p\", data=\"Players sorted by descending protection zone lock time remaining. Also shown is their level, vocation, guild, and most recent victim. Shown first are those that are still PZL'd. The second table contains those that should have lost their PZL by now.\")\n column_count = 6\n if not world:\n column_count += 1\n with stattab_table_tag(doc.open_tag):\n def add_header_row():\n with doc.open_tag(\"tr\", inline=False):\n if not world:\n doc.add_tag(\"th\", \"World\")\n doc.add_tag(\"th\", \"PZ Lock End\")\n doc.add_tag(\"th\", \"Killer\")\n doc.add_tag(\"th\", \"Level\")\n doc.add_tag(\"th\", \"Vocation\")\n doc.add_tag(\"th\", \"Guild\")\n doc.add_tag(\"th\", \"Last Victim\")\n add_header_row()\n rowColor = stattab_row_class()\n doing_still_pzlocked_rows = True\n for pzlock in dbiface.get_last_pzlocks(world, limits):\n killerInfo = dbiface.get_char(pzlock[\"killer\"])\n #pdb.set_trace()\n pzEndStamp = dbiface.pz_end(pzlock)\n if doing_still_pzlocked_rows:\n if pzEndStamp < int(time.time()):\n doing_still_pzlocked_rows = False\n with doc.open_tag(\"tr\"):\n with doc.open_tag(\"td\", attrs={\"colspan\": column_count}):\n doc.add_tag(\"hr\")\n add_header_row()\n if world is None or killerInfo[\"world\"] == world:\n rowAttrs = {\"class\": rowColor.next()}\n if not doing_still_pzlocked_rows:\n rowAttrs[\"class\"] += \" greyed\"\n with doc.open_tag(\"tr\", attrs=rowAttrs, inline=False):\n assert killerInfo[\"name\"] == pzlock[\"killer\"]\n if not world:\n doc.add_tag(\"td\", killerInfo[\"world\"])\n doc.add_tag(\"td\", human_time_diff(pzEndStamp))\n doc.add_tag(\"td\", char_link(pzlock[\"killer\"]))\n for field in (\"level\", \"vocation\"):\n doc.add_tag(\"td\", killerInfo[field])\n doc.add_tag(\"td\", pageContext.guild_link(killerInfo[\"guild\"]))\n doc.add_tag(\"td\", char_link(pzlock[\"victim\"]))\n\ndef player_killer_highscores(doc, context):\n world = context.get_selected_world()\n with stattab_table_tag(doc.open_tag):\n with doc.open_tag(\"tr\", inline=False):\n doc.add_tag(\"th\", \"Kill Count\")\n if not world:\n doc.add_tag(\"th\", \"World\")\n doc.add_tag(\"th\", \"Assassin Name\")\n doc.add_tag(\"th\", \"Level\")\n doc.add_tag(\"th\", \"Vocation\")\n doc.add_tag(\"th\", \"Guild\")\n rowClass = stattab_row_class()\n for pker in dbiface.best_player_killers(world):\n with doc.open_tag(\"tr\", attrs={\"class\": rowClass.next()}, inline=False):\n doc.add_tag(\"td\", pker[0])\n if not world:\n doc.add_tag(\"td\", pker[\"world\"])\n doc.add_tag(\"td\", char_link(pker[\"name\"]))\n #pdb.set_trace()\n doc.add_tag(\"td\", pker[\"level\"])\n doc.add_tag(\"td\", pker[\"vocation\"])\n doc.add_tag(\"td\", context.guild_link(pker[\"guild\"]))\n\nclass PageEntry(object):\n def __init__(self, handler):\n self.handler = handler\n def handle_request(self, request):\n self.handler(request)\n\nclass MenuPageEntry(PageEntry):\n def __init__(self, handler, title):\n #pdb.set_trace()\n super(MenuPageEntry, self).__init__(handler)\n self.title = title\n def handle_request(self, request):\n self.handler(request, self.title)\n\nclass StandardPageEntry(MenuPageEntry):\n def __init__(self, handler, title):\n super(StandardPageEntry, self).__init__(handler, title)\n def handle_request(self, request):\n standard_page(request, self.title, self.handler)\n\nPAGES = {\n \"/guildstance\": MenuPageEntry(guild_stances_page, \"Guild Stances\"),\n \"/tibstats.css\": PageEntry(tibstats_stylesheet),\n #\"/tibstats-simple.css\": PageEntry(tibstats_stylesheet),\n \"/recentdeath\": StandardPageEntry(recent_deaths, \"Recent Deaths\"),\n \"/pzlocked\": StandardPageEntry(pz_locked, \"Protection Zone Locked\"),\n \"/whoisonline\": StandardPageEntry(world_online, \"Current Online\"),\n \"/pkhighscore\": StandardPageEntry(player_killer_highscores, \"Best Player Killers\"),}\n\ndef handle_http_request(request):\n try:\n basePath = request.path.split(\"?\", 1)[0]\n if basePath in PAGES:\n PAGES[basePath].handle_request(request)\n return\n else:\n #request.send_error(404)\n request.send_response(302, \"Default paths not set yet\")\n request.send_header(\"Location\", \"/pzlocked\")\n request.end_headers()\n return\n except sqlite3.OperationalError as e:\n if e.args[0] == \"database is locked\":\n request.send_error(408, \"Try again soon\")\n else:\n raise\n except:\n request.send_error(500, \"Computer says no\")\n print >>sys.stderr, \"Headers:\", repr(str(request.headers))\n raise\n","sub_path":"projects/tibstat/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":22833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558904379","text":"# #!/usr/bin/env python\n# # -*- coding: UTF-8 -*-\n\nimport time\nimport requests\nimport xlwt\nimport json\nimport pandas as pd\n\n\ndef get_periodical_year_article(perioId, publishYear):\n \"\"\"\n 获取 XXX年《期刊》的所有文章ID\n :param perioId: 期刊代码,如汉语学习代码为:hanyxx\n :param publishYear: 出刊年份\n :return: []\n \"\"\"\n\n URL = 'http://www.wanfangdata.com.cn/sns/third-web/per/perio/articleList'\n headers = {\n \"User-Agent\": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\"\n }\n\n id_list = []\n # 默认期刊只有6期,从第1期到6期\n for issueNum in range(1, 6):\n # 默认每期的文章最多有30篇\n for page_id in range(1, 4):\n\n datas = {\n \"page\": page_id,\n \"pageSize\": 10,\n \"perioId\": perioId,\n \"publishYear\": publishYear,\n \"issueNum\": issueNum,\n }\n try:\n session = requests.session()\n res = session.post(URL, data=datas, headers=headers)\n data = res.content.decode()\n # print(data)\n info = json.loads(data)\n if not info['pageRow']:\n continue\n else:\n # 获取文章id\n for jn in info['pageRow']:\n id_list.append(jn['article_id'])\n print('《{}》第{}期{}页的文章:'.format(perioId, issueNum, page_id), end=\"\")\n print(info)\n except Exception as e:\n print(e)\n print(id_list)\n return id_list\n\n\ndef get_all_article_id(perioId='hanyxx'):\n \"\"\"\n 获取《某期刊》所有文章ID,这里默认了《汉语学习》,如果需要获取其他期刊的,自行获取相关期刊id,加for循环处理\n :param perioId: 期刊名称\n :return: [[],[]]\n \"\"\"\n all_artile_list = []\n # 2001年到2020年的文章ID\n for year in range(2001, 2021):\n article_id = get_periodical_year_article(perioId, year)\n all_artile_list.append(article_id)\n print(all_artile_list)\n\n return all_artile_list\n\n\ndef json_to_excel(json_data):\n \"\"\"\n 读取json数据并存到xlxs中\n json_data: 数据格式为:[{},{},{}]\n \"\"\"\n json_file = json_data\n print(json_file)\n workbook = xlwt.Workbook()\n sheet1 = workbook.add_sheet('save_data')\n\n # 获取表头,即第一行\n ll = list(json_file[0].keys())\n for i in range(0, len(ll)):\n sheet1.write(0, i, ll[i]) # 写入第一行,i列,数据\n\n # 讲数据写入第2行到N行\n for j in range(0, len(json_file)):\n m = 0\n ls = list(json_file[j].values()) # 获取json字段对应的数据\n for k in ls:\n sheet1.write(j + 1, m, k)\n m += 1\n workbook.save('save_data.xls')\n\n\ndef get_wanfang_dataone_excel(req_id):\n url = 'http://d.wanfangdata.com.cn/Detail/Periodical/'\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36\"\n }\n body = {\n \"Id\": req_id\n }\n try:\n res = requests.post(url, headers=headers, json=body)\n data = res.content.decode()\n # print(data)\n info = json.loads(data)\n print(info)\n # 拼接数据成[{}]\n json_list = []\n if not info['detail']:\n json_list.append('')\n # 拼接数据\n else:\n json_infos = {\n \"文章标题\": info['detail'][0]['periodical']['Title'],\n \"摘要\": info['detail'][0]['periodical']['Abstract'],\n \"关键字\": info['detail'][0]['periodical']['Keywords'],\n \"作者\": info['detail'][0]['periodical']['Creator'],\n \"作者单位\": info['detail'][0]['periodical']['AuthorOrg'],\n \"期刊名称\": info['detail'][0]['periodical']['PeriodicalTitle'],\n \"年,卷(期)\": str(info['detail'][0]['periodical']['PublishYear']) + '(' + str(\n info['detail'][0]['periodical']['Issue']) + \")\",\n \"基金项目\": info['detail'][0]['periodical']['Fund'],\n \"在线发表时间\": info['detail'][0]['periodical']['MetadataOnlineDate'],\n \"链接\": 'http://d.wanfangdata.com.cn/periodical/' + info['detail'][0]['periodical']['Id'],\n }\n\n json_list.append(json_infos)\n return json_list\n except Exception as e:\n print(e)\n\n\ndef get_wanfang_data():\n \"\"\"\n 一开始的DEMO\n :return:\n \"\"\"\n url = 'http://d.wanfangdata.com.cn/Detail/Periodical/'\n\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36\"\n }\n body = {\n \"Id\": \"CASS_43577964\"\n }\n\n start_num = 43577964\n end_num = 43577969\n for i in range(start_num, end_num + 1):\n json_list = []\n article_id = 'CASS_{}'.format(i)\n # 替换请求Boby id\n body['Id'] = article_id\n res = requests.post(url, headers=headers, json=body)\n data = res.content.decode()\n # print(data)\n info = json.loads(data)\n print(info)\n if not info['detail']:\n json_list.append({})\n # 拼接数据\n else:\n json_infos = {\n\n \"文章标题\": info['detail'][0]['periodical']['Title'],\n \"摘要\": info['detail'][0]['periodical']['Abstract'],\n \"关键字\": info['detail'][0]['periodical']['Keywords'],\n \"作者\": info['detail'][0]['periodical']['Creator'],\n \"作者单位\": info['detail'][0]['periodical']['AuthorOrg'],\n \"期刊名称\": info['detail'][0]['periodical']['PeriodicalTitle'],\n \"年,卷(期)\": str(info['detail'][0]['periodical']['PublishYear']) + '(' + str(\n info['detail'][0]['periodical']['Issue']) + \")\",\n \"基金项目\": info['detail'][0]['periodical']['Fund'],\n \"在线发表时间\": info['detail'][0]['periodical']['MetadataOnlineDate'],\n \"链接\": 'http://d.wanfangdata.com.cn/periodical/' + info['detail'][0]['periodical']['Id'],\n\n }\n\n json_list.append(json_infos)\n # 停顿1s,不要频繁发起请求\n # time.sleep(1)\n\n print(json_list)\n return json_list\n\n\ndef pandas_json_to_excel(json_data):\n \"\"\"\n #TODO:pandas追加数据到excel ,有空再弄\n \"\"\"\n\n \n rows_num = 0\n try:\n # 读取excel,获取行数\n df = pd.read_excel('save_data.xls', sheet_name='save_data')\n rows_num = df.shape[0]\n print(rows_num)\n except Exception as e:\n print(e)\n\n writer = pd.ExcelWriter('save_data.xls', sheet_name='save_data')\n for jsn in json_data:\n\n df = pd.DataFrame(pd.json_normalize(jsn))\n if rows_num > 0:\n df.to_excel(writer, startrow=int(rows_num) + 1, sheet_name='save_data')\n else:\n df.to_excel(writer)\n\n\nif __name__ == '__main__':\n # j_data = get_wanfang_data()\n # # json_to_excel(j_data)\n # pandas_json_to_excel(j_data)\n # get_periodical_year_article(perioId='hanyxx', publishYear=2020)\n # get_all_article_id()\n\n article_list = get_all_article_id()\n save_json = []\n for year_list in article_list:\n for arti_id in year_list:\n print(arti_id)\n arti_json = get_wanfang_dataone_excel(arti_id)\n save_json.append(arti_json[0])\n\n json_to_excel(save_json)\n try:\n with open('save.json', 'w', encoding='utf-8') as f:\n f.write(json.dumps(save_json))\n except Exception as e:\n print(e)\n","sub_path":"web_spider/get_papers_to_excel.py","file_name":"get_papers_to_excel.py","file_ext":"py","file_size_in_byte":7938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37831143","text":"import unittest\n\nfrom src.project import Project\nfrom src.student import Student\nfrom src.priority import grade_priority_calculator\nfrom src.priority import keywords_priority_calculator\nfrom src.priority import department_priority_calculator\nfrom src.priority import split_priority_calculator\nfrom src.priority import PrioritySplit\n\n\nclass GradePriorityCalculatorTest(unittest.TestCase):\n\n def test_priority_of_student_is_his_grade_normalized(self):\n student = Student(1, ['a_project'], grade=7)\n self.assertEqual(grade_priority_calculator(student), student.grade / 10)\n\n\nclass KeywordsPriorityCalculatorTest(unittest.TestCase):\n\n def test_priority_of_student_is_one_if_all_keywords_match(self):\n kw_1 = 'kw_1'\n kw_2 = 'kw_2'\n kw_3 = 'kw_3'\n kws = [kw_1, kw_2, kw_3]\n project = Project(1, keywords=kws)\n student = Student(1, [project], keywords=kws)\n self.assertEqual(keywords_priority_calculator(student, project), 1)\n\n def test_priority_of_student_is_zero_if_none_match(self):\n kw_1 = 'kw_1'\n kw_2 = 'kw_2'\n kw_3 = 'kw_3'\n kw_4 = 'kw_4'\n student_kws = [kw_1, kw_2]\n project_kws = [kw_3, kw_4]\n project = Project(1, keywords=project_kws)\n student = Student(1, [project], keywords=student_kws)\n self.assertEqual(keywords_priority_calculator(student, project), 0)\n\n def test_priority_of_student_is_one_if_all_project_keywords_match(self):\n kw_1 = 'kw_1'\n kw_2 = 'kw_2'\n kw_3 = 'kw_3'\n student_kws = [kw_1, kw_2, kw_3]\n project_kws = [kw_1]\n project = Project(1, keywords=project_kws)\n student = Student(1, [project], keywords=student_kws)\n self.assertEqual(keywords_priority_calculator(student, project), 1)\n\n def test_priority_of_student_is_ratio_of_project_keywords_matched(self):\n project_kws = self.n_keywords(10)\n student_kws = self.n_keywords(2)\n student_kws += self.other_keywords(37)\n project = Project(1, keywords=project_kws)\n student = Student(1, [project], keywords=student_kws)\n self.assertEqual(keywords_priority_calculator(student, project), 0.2)\n\n def n_keywords(self, n):\n return ['kw_{}'.format(i) for i in range(1, n + 1)]\n\n def other_keywords(self, n):\n return ['other' for _ in range(n)]\n\n\nclass DepartmentPriorityCalculatorTest(unittest.TestCase):\n\n def test_priority_should_be_zero_if_department_does_not_match(self):\n dept_1 = 'dept_1'\n dept_2 = 'dept_2'\n project = Project(1, department=dept_1)\n student = Student(1, [project], department=dept_2)\n self.assertEqual(department_priority_calculator(student, project), 0)\n\n def test_priority_should_be_one_if_departments_match(self):\n dept = 'dept'\n project = Project(1, department=dept)\n student = Student(1, [project], department=dept)\n self.assertEqual(department_priority_calculator(student, project), 1)\n\n\nclass SplitPriorityCalculatorTest(unittest.TestCase):\n\n def test_split_calculator_is_weighted_correctly(self):\n grade_score = 0.7\n keywords_score = 0.2\n department_score = 1\n def grade_calculator(student, project):\n return grade_score\n def keywords_calculator(student, project):\n return keywords_score\n def department_calculator(student, project):\n return department_score\n split = PrioritySplit(0.5, 0.3, 0.2)\n project = ProjectStub(split)\n self.assertEqual(split_priority_calculator(\n 'a_student', \\\n project, \\\n grade_calculator=grade_calculator, \\\n keywords_calculator=keywords_calculator, \\\n department_calculator=department_calculator \\\n ), 0.35 + 0.06 + 0.2)\n\n\nclass ProjectStub:\n\n def __init__(self, priority_split):\n self.priority_split = priority_split\n\n\nclass PrioritySplitTest(unittest.TestCase):\n\n def test_priority_split_is_normalized(self):\n original_grade_weight = 0.5\n original_keywords_weight = 0.3\n original_department_weight = 0.2\n multiplier = 32\n new_grade_weight = 0.5 * multiplier\n new_keywords_weight = 0.3 * multiplier\n new_department_weight = 0.2 * multiplier\n priority_split = PrioritySplit( \\\n grade_weight=new_grade_weight, \\\n keywords_weight=new_keywords_weight, \\\n department_weight=new_department_weight \\\n )\n self.assertEqual(priority_split.grade_weight, original_grade_weight)\n self.assertEqual(priority_split.keywords_weight, original_keywords_weight)\n self.assertEqual(priority_split.department_weight, original_department_weight)\n\n def test_error_raised_on_negative_grade_weight(self):\n self.assertRaises(\n ValueError, \\\n PrioritySplit, \\\n grade_weight=-1, \\\n keywords_weight=2, \\\n department_weight=3 \\\n )\n\n def test_error_raised_on_negative_keyword_weight(self):\n self.assertRaises(\n ValueError, \\\n PrioritySplit, \\\n grade_weight=1, \\\n keywords_weight=-2, \\\n department_weight=3 \\\n )\n\n def test_error_raised_on_negative_department_weight(self):\n self.assertRaises(\n ValueError, \\\n PrioritySplit, \\\n grade_weight=1, \\\n keywords_weight=2, \\\n department_weight=-4 \\\n )\n","sub_path":"tests/test_priority.py","file_name":"test_priority.py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"392922034","text":"#!/usr/bin/env python\n# Copyright 2017 The LUCI Authors. All rights reserved.\n# Use of this source code is governed under the Apache License, Version 2.0\n# that can be found in the LICENSE file.\n\n# pylint: disable=unused-argument\n\nimport httplib\nimport json\nimport sys\nimport unittest\n\nfrom test_support import test_env\ntest_env.setup_test_env()\n\nimport webapp2\nimport webtest\n\nfrom test_support import test_case\n\nfrom google.protobuf import empty_pb2\n\nfrom components.prpc import encoding\nfrom components.prpc import server\nfrom components.prpc.test import test_pb2\nfrom components.prpc.test import test_prpc_pb2\n\n\nclass TestServicer(object):\n \"\"\"TestServicer implements the Test service in test.proto.\"\"\"\n\n DESCRIPTION = test_prpc_pb2.TestServiceDescription\n\n def __init__(self):\n self.given = None\n self.echoed = None\n self.give_callback = None\n\n def Give(self, request, context):\n if self.give_callback:\n self.give_callback(request, context)\n self.given = request.m\n return empty_pb2.Empty()\n\n def Take(self, _request, _context):\n return test_pb2.TakeResponse(k=self.given)\n\n def Echo(self, request, _context):\n self.echoed = request\n return test_pb2.EchoResponse(response=['hello!', str(request.r.m)])\n\n\nclass BadTestServicer(object):\n \"\"\"BadTestServicer implements the Test service in test.proto, but poorly.\"\"\"\n\n DESCRIPTION = test_prpc_pb2.TestServiceDescription\n\n def Give(self, _request, _context):\n return 5\n\n def Take(self, _request, _context):\n raise Exception(\"Look at me, I'm bad.\")\n\n def Echo(self, request, _context):\n return None # no respose and no status code\n\n\nclass PRPCServerTestCase(test_case.TestCase):\n def setUp(self):\n super(PRPCServerTestCase, self).setUp()\n s = server.Server()\n self.service = TestServicer()\n s.add_service(self.service)\n real_app = webapp2.WSGIApplication(s.get_routes(), debug=True)\n self.app = webtest.TestApp(\n real_app,\n extra_environ={'REMOTE_ADDR': '::ffff:127.0.0.1'},\n )\n bad_s = server.Server()\n bad_s.add_service(BadTestServicer())\n real_bad_app = webapp2.WSGIApplication(bad_s.get_routes(), debug=True)\n self.bad_app = webtest.TestApp(\n real_bad_app,\n extra_environ={'REMOTE_ADDR': '192.192.192.192'},\n )\n\n def make_headers(self, enc):\n return {\n 'Content-Type': enc[1],\n 'Accept': enc[1],\n }\n\n def check_headers(self, headers, prpc_code, origin=None):\n if origin is not None:\n self.assertEqual(headers['Access-Control-Allow-Origin'], origin)\n self.assertEqual(headers['Vary'], 'Origin')\n self.assertEqual(headers['Access-Control-Allow-Credentials'], 'true')\n self.assertEqual(headers['X-Content-Type-Options'], 'nosniff')\n self.assertEqual(headers['X-Prpc-Grpc-Code'], str(prpc_code.value))\n self.assertEqual(\n headers['Access-Control-Expose-Headers'],\n ('X-Prpc-Grpc-Code'),\n )\n\n def check_echo(self, enc):\n headers = self.make_headers(enc)\n headers['Origin'] = 'example.com'\n encoder = encoding.get_encoder(enc)\n req = test_pb2.EchoRequest()\n req.r.m = 94049\n encoded_req = encoder(req)\n if enc == encoding.Encoding.JSON:\n encoded_req = encoded_req[4:]\n http_resp = self.app.post(\n '/prpc/test.Test/Echo',\n encoded_req,\n headers,\n )\n self.check_headers(\n http_resp.headers,\n server.StatusCode.OK,\n origin='example.com',\n )\n self.assertEqual(http_resp.status_int, httplib.OK)\n raw_resp = http_resp.body\n resp = test_pb2.EchoResponse()\n decoder = encoding.get_decoder(enc)\n if enc == encoding.Encoding.JSON:\n raw_resp = raw_resp[4:]\n decoder(raw_resp, resp)\n\n self.assertEqual(len(resp.response), 2)\n self.assertEqual(resp.response[0], 'hello!')\n self.assertEqual(resp.response[1], '94049')\n\n def test_context(self):\n calls = []\n def rpc_callback(_request, context):\n calls.append({\n 'peer': context.peer(),\n 'is_active': context.is_active(),\n 'time_remaining': context.time_remaining(),\n })\n self.service.give_callback = rpc_callback\n\n headers = self.make_headers(encoding.Encoding.BINARY)\n req = test_pb2.GiveRequest(m=3333)\n raw_resp = self.app.post(\n '/prpc/test.Test/Give',\n req.SerializeToString(),\n headers,\n ).body\n self.assertEqual(len(raw_resp), 0)\n\n self.assertEqual(calls, [\n {\n 'is_active': True,\n 'peer': 'ipv6:[::ffff:127.0.0.1]',\n 'time_remaining': None,\n },\n ])\n\n def test_servicer_persistence(self):\n \"\"\"Basic test which ensures the servicer state persists.\"\"\"\n\n headers = self.make_headers(encoding.Encoding.BINARY)\n req = test_pb2.GiveRequest(m=3333)\n raw_resp = self.app.post(\n '/prpc/test.Test/Give',\n req.SerializeToString(),\n headers,\n ).body\n self.assertEqual(len(raw_resp), 0)\n\n req = empty_pb2.Empty()\n raw_resp = self.app.post(\n '/prpc/test.Test/Take',\n req.SerializeToString(),\n headers,\n ).body\n resp = test_pb2.TakeResponse()\n test_pb2.TakeResponse.ParseFromString(resp, raw_resp)\n self.assertEqual(resp.k, 3333)\n\n def test_echo_encodings(self):\n \"\"\"Basic test which checks Echo service works with different encodings.\"\"\"\n\n self.check_echo(encoding.Encoding.BINARY)\n self.check_echo(encoding.Encoding.JSON)\n self.check_echo(encoding.Encoding.TEXT)\n\n def test_bad_headers(self):\n \"\"\"Make sure the server gives a reasonable response for bad headers.\"\"\"\n\n req = test_pb2.GiveRequest(m=825800)\n resp = self.app.post(\n '/prpc/test.Test/Give',\n req.SerializeToString(),\n {},\n expect_errors=True,\n )\n self.assertEqual(resp.status_int, httplib.BAD_REQUEST)\n self.check_headers(resp.headers, server.StatusCode.INVALID_ARGUMENT)\n\n def test_bad_service(self):\n \"\"\"Make sure the server handles an unknown service.\"\"\"\n\n req = test_pb2.GiveRequest(m=825800)\n resp = self.app.post(\n '/prpc/IDontExist/Give',\n req.SerializeToString(),\n self.make_headers(encoding.Encoding.BINARY),\n expect_errors=True,\n )\n self.assertEqual(resp.status_int, httplib.NOT_IMPLEMENTED)\n self.check_headers(resp.headers, server.StatusCode.UNIMPLEMENTED)\n\n def test_bad_method(self):\n \"\"\"Make sure the server handles an unknown method.\"\"\"\n\n req = test_pb2.GiveRequest(m=825800)\n resp = self.app.post(\n '/prpc/test.Test/IDontExist',\n req.SerializeToString(),\n self.make_headers(encoding.Encoding.BINARY),\n expect_errors=True,\n )\n self.assertEqual(resp.status_int, httplib.NOT_IMPLEMENTED)\n self.check_headers(resp.headers, server.StatusCode.UNIMPLEMENTED)\n\n def test_bad_app(self):\n \"\"\"Make sure the server handles a bad servicer implementation.\"\"\"\n\n req = test_pb2.GiveRequest(m=825800)\n resp = self.bad_app.post(\n '/prpc/test.Test/Give',\n req.SerializeToString(),\n self.make_headers(encoding.Encoding.BINARY),\n expect_errors=True,\n )\n self.assertEqual(resp.status_int, httplib.INTERNAL_SERVER_ERROR)\n self.check_headers(resp.headers, server.StatusCode.INTERNAL)\n\n req = empty_pb2.Empty()\n resp = self.bad_app.post(\n '/prpc/test.Test/Take',\n req.SerializeToString(),\n self.make_headers(encoding.Encoding.BINARY),\n expect_errors=True,\n )\n self.assertEqual(resp.status_int, httplib.INTERNAL_SERVER_ERROR)\n self.check_headers(resp.headers, server.StatusCode.INTERNAL)\n\n req = test_pb2.EchoRequest()\n resp = self.bad_app.post(\n '/prpc/test.Test/Echo',\n req.SerializeToString(),\n self.make_headers(encoding.Encoding.BINARY),\n expect_errors=True,\n )\n self.assertEqual(resp.status_int, httplib.INTERNAL_SERVER_ERROR)\n self.check_headers(resp.headers, server.StatusCode.INTERNAL)\n\n def test_bad_request(self):\n \"\"\"Make sure the server handles a malformed request.\"\"\"\n\n resp = self.app.post(\n '/prpc/test.Test/Give',\n 'asdfjasdhlkiqwuebweo',\n self.make_headers(encoding.Encoding.BINARY),\n expect_errors=True,\n )\n self.assertEqual(resp.status_int, httplib.BAD_REQUEST)\n self.check_headers(resp.headers, server.StatusCode.INVALID_ARGUMENT)\n\n\nclass InterceptorsTestCase(test_case.TestCase):\n def make_test_server_app(self, servicer, interceptors):\n s = server.Server()\n s.add_service(servicer)\n for interceptor in interceptors:\n s.add_interceptor(interceptor)\n app = webapp2.WSGIApplication(s.get_routes(), debug=True)\n return webtest.TestApp(app, extra_environ={'REMOTE_ADDR': 'fake-ip'})\n\n def call_echo(self, app, m, headers=None, return_raw_resp=False):\n headers = dict(headers or {})\n headers.update({\n 'Content-Type': encoding.Encoding.JSON[1],\n 'Accept': encoding.Encoding.JSON[1],\n })\n raw_resp = app.post(\n '/prpc/test.Test/Echo',\n json.dumps({'r': {'m': m}}),\n headers,\n expect_errors=True)\n if return_raw_resp:\n return raw_resp\n return json.loads(raw_resp.body[4:])\n\n def test_no_interceptors(self):\n s = TestServicer()\n app = self.make_test_server_app(s, [])\n resp = self.call_echo(app, 123)\n self.assertEqual(resp, {u'response': [u'hello!', u'123']}, )\n self.assertEqual(s.echoed.r.m, 123)\n\n def test_single_noop_interceptor(self):\n calls = []\n\n def interceptor(request, context, details, cont):\n calls.append((request, details))\n return cont(request, context, details)\n\n s = TestServicer()\n app = self.make_test_server_app(s, [interceptor])\n resp = self.call_echo(app, 123, headers={'Authorization': 'x'})\n self.assertEqual(resp, {u'response': [u'hello!', u'123']}, )\n self.assertEqual(s.echoed.r.m, 123)\n\n # Interceptor called and saw relevant metadata.\n self.assertEqual(len(calls), 1)\n req, details = calls[0]\n\n self.assertEqual(req, test_pb2.EchoRequest(r=test_pb2.GiveRequest(m=123)))\n self.assertEqual(details.method, 'test.Test.Echo')\n self.assertEqual(dict(details.invocation_metadata)['authorization'], 'x')\n\n def test_interceptor_replies(self):\n def interceptor(request, context, details, cont):\n return test_pb2.EchoResponse(response=['intercepted!', str(request.r.m)])\n\n s = TestServicer()\n app = self.make_test_server_app(s, [interceptor])\n resp = self.call_echo(app, 123)\n self.assertEqual(resp, {u'response': [u'intercepted!', u'123']}, )\n self.assertIsNone(s.echoed)\n\n def test_interceptor_chain(self):\n calls = []\n\n def make(name):\n def interceptor(request, context, details, cont):\n calls.append(name)\n return cont(request, context, details)\n return interceptor\n\n s = TestServicer()\n app = self.make_test_server_app(s, [make(1), make(2), make(3)])\n resp = self.call_echo(app, 123)\n self.assertEqual(resp, {u'response': [u'hello!', u'123']}, )\n self.assertEqual(s.echoed.r.m, 123)\n\n # Interceptors are called in correct order.\n self.assertEqual(calls, [1, 2, 3])\n\n def test_interceptor_exceptions(self):\n class Error(Exception):\n pass\n\n def outter(request, context, details, cont):\n try:\n return cont(request, context, details)\n except Error as exc:\n context.set_code(server.StatusCode.PERMISSION_DENIED)\n context.set_details(exc.message)\n\n def inner(request, context, details, cont):\n raise Error('FAIL')\n\n s = TestServicer()\n app = self.make_test_server_app(s, [outter, inner])\n resp = self.call_echo(app, 123, return_raw_resp=True)\n self.assertEqual(resp.status_int, 403)\n self.assertTrue('FAIL' in resp.body)\n\n\nif __name__ == '__main__':\n if '-v' in sys.argv:\n unittest.TestCase.maxDiff = None\n unittest.main()\n","sub_path":"appengine/components/components/prpc/server_test.py","file_name":"server_test.py","file_ext":"py","file_size_in_byte":11799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"344470399","text":"\"\"\"\nSubclasses of simulator API things.\n\"\"\"\n\nimport sim.api as api\n\n\nclass BasicHost(api.HostEntity):\n \"\"\"\n Basic host with a ping method\n \"\"\"\n ENABLE_PONG = True # Send Pong in reponse to ping?\n ENABLE_DISCOVERY = True # Send HostDiscoveryPacket when link goes up?\n\n def ping(self, dst, data=None, color=None):\n \"\"\"\n Sends a Ping packet to dst.\n \"\"\"\n self.send(Ping(dst, data=data, color=color), flood=True)\n\n def handle_link_up(self, port, latency):\n \"\"\"\n When a link comes up, send a message to the other side\n\n This is us saying hello so that the other side knows who we are. In the\n real world this is *vaguely* similar to some uses of ARP, maybe DHCP,\n IPv6 NDP, and probably some others. But only vaguely.\n \"\"\"\n if self.ENABLE_DISCOVERY:\n self.send(HostDiscoveryPacket(), flood=True)\n\n def handle_rx(self, packet, port):\n \"\"\"\n Handle packets for the BasicHost\n\n Silently drops messages to nobody.\n Warns about received messages to someone besides itself.\n Prints received messages.\n Returns Pings with a Pong.\n \"\"\"\n if packet.dst is api.NullAddress:\n # Silently drop messages not to anyone in particular\n return\n\n trace = ','.join((s.name for s in packet.trace))\n\n if packet.dst is not self:\n self.log(\"NOT FOR ME: %s %s\" % (packet, trace), level=\"WARNING\")\n else:\n self.log(\"rx: %s %s\" % (packet, trace))\n if type(packet) is Ping and self.ENABLE_PONG:\n # Trace this path\n import sim.core as core\n core.events.highlight_path([packet.src] + packet.trace)\n # Send a pong response\n self.send(Pong(packet), port)\n\n\nclass Ping(api.Packet):\n \"\"\"\n A Ping packet\n \"\"\"\n\n def __init__(self, dst, data=None, color=None):\n super(Ping, self).__init__(dst=dst)\n self.data = data\n self.outer_color[3] = 0.8 # Mostly opaque\n self.inner_color = [1, 1, 1, .8] # white\n if color:\n for i, c in enumerate(color):\n self.outer_color[i] = c\n\n def __repr__(self):\n d = self.data\n if d is not None:\n d = ': ' + str(d)\n else:\n d = ''\n return \"<%s %s->%s ttl:%i%s>\" % (type(self).__name__,\n api.get_name(self.src),\n api.get_name(self.dst),\n self.ttl, d)\n\n\nclass Pong(api.Packet):\n \"\"\"\n A Pong packet\n\n It's a returned Ping. The original Ping is in the .original property.\n \"\"\"\n\n def __init__(self, original):\n super(Pong, self).__init__(dst=original.src)\n self.original = original\n\n # Flip colors from original\n self.outer_color = original.inner_color\n self.inner_color = original.outer_color\n\n def __repr__(self):\n return \"\"\n\n\nclass HostDiscoveryPacket(api.Packet):\n \"\"\"\n Just a way that hosts say hello\n \"\"\"\n\n def __init__(self, *args, **kw):\n # Call original constructor\n super(HostDiscoveryPacket, self).__init__(*args, **kw)\n\n # Host discovery packets are treated as an implementation detail --\n # they're how we know when to call add_static_route(). Thus, we make\n # them invisible in the simulator.\n self.outer_color = [0, 0, 0, 0]\n self.inner_color = [0, 0, 0, 0]\n\n\nclass RoutePacket(api.Packet):\n def __init__(self, destination, latency):\n super(RoutePacket, self).__init__()\n self.latency = latency\n self.destination = destination\n self.outer_color = [1, 0, 1, 1]\n self.inner_color = [1, 0, 1, 1]\n\n def __repr__(self):\n return \"\" % (\n self.destination, self.latency)\n\n\n\nclass Router(api.Entity):\n \"\"\"Implements handler for received packets.\"\"\"\n\n def handle_rx(self, packet, port):\n \"\"\"\n Called by the framework when this router receives a packet.\n\n The implementation calls the appropriate packet-handling function:\n - `handle_route_advertisement`,\n - `handle_host_discovery`, or\n - `handle_data_packet`,\n based on the packet type. You should implement your packet-handling\n logic in those three functions without modifying this function.\n\n !!! DO NOT MODIFY THIS FUNCTION !!!\n \"\"\"\n if isinstance(packet, RoutePacket):\n self.handle_route_advertisement(packet.destination, port,\n packet.latency)\n elif isinstance(packet, HostDiscoveryPacket):\n self.add_static_route(packet.src, port)\n else:\n self.handle_data_packet(packet, port)\n\n def handle_route_advertisement(self, dst, port, route_latency):\n pass\n\n def add_static_route(self, host, port):\n pass\n\n def handle_data_packet(self, packet, in_port):\n pass\n\n\nclass DVRouterBase(Router):\n \"\"\"\n Base class for implementing a distance vector router\n \"\"\"\n POISON_MODE = False # If self.POISON_MODE is True, send poisons.\n DEFAULT_TIMER_INTERVAL = 5 # Default timer interval.\n\n def start_timer(self, interval=None):\n \"\"\"\n Start the timer that calls handle_timer()\n\n This should get called in the constructor. You shouldn't override this.\n \"\"\"\n if interval is None:\n interval = self.DEFAULT_TIMER_INTERVAL\n if interval is None: return\n api.create_timer(interval, self.handle_timer)\n\n def handle_timer(self):\n \"\"\"\n Called periodically when the router should send tables to neighbors\n\n You probably want to override this.\n \"\"\"\n pass\n","sub_path":"CS168/proj1-Distance-Vector-Routing/proj1/simulator/sim/basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":5906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"552445391","text":"# ~~~~parameters~~~~~\n# the src file with answer\nsrc = '/home/vistajin/Desktop/test-aws-saa-with-answer.txt'\n# the key to the one you want to search\nkey = 'DynamoDB'\n\n\ndef remove_blank_line(s):\n return \"\".join([s for s in s.splitlines(True) if s.strip()]).strip()\n\n\nwith open(src, 'r', encoding='UTF-8') as f:\n all_content = f.read()\n questions = str(all_content).split(\"Question \")\n del(questions[0])\n match = 0\n for q in questions:\n question = remove_blank_line(q.split(\"A.\")[0])\n a = q.split(\"Answer: \")[1].split(\"\\n\")[0].strip()\n for n in range(0, len(a)):\n answer = a[n:n+1] + \". \" + remove_blank_line(q.split(a[n:n+1] + \".\")[1].split(chr(ord(a[n:n+1]) + 1) + \".\")[0])\n # answer = a[n:n+1] + \". \" + remove_blank_line(q.split(a[n:n+1])[1])\n if answer.find(key) != -1 or question.find(key) != -1:\n print(\"=============================\")\n print(question)\n print(answer)\n match = match + 1\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print(\"Match: {%d}\" % match)\n\n","sub_path":"python/script/answer-contains-key.py","file_name":"answer-contains-key.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"134527936","text":"\nclass ResultTree():\n def __init__(self, functions):\n self.genealogy = []\n self.genealogy.append({'content': {}, 'index': None})\n self.functions = functions\n\n def assert_root(self):\n assert(len(self.genealogy) == 1)\n\n def get_data(self):\n return self.genealogy[0]['content']\n\n def add_child(self, nodetype, name):\n myself = self.genealogy[-1]['content']\n\n if nodetype == 'dict':\n child = {}\n elif nodetype == 'list':\n child = []\n else:\n raise ValueError('Unknown type.')\n\n if type(myself).__name__ == 'dict':\n if name in myself:\n raise ValueError(\"Key already used.\")\n myself[name] = child\n self.genealogy[-1]['index'] = name\n elif type(myself).__name__ == 'list':\n if nodetype == 'dict':\n myself.append(child)\n elif nodetype == 'list':\n # if nodetype == 'list', then the list already exists, it's myself !\n return\n\n self.genealogy.append({'content': child, 'index': None})\n\n def add_leaf(self, name, content, function=None):\n myself = self.genealogy[-1]['content']\n\n if function:\n f = self.functions[function]\n child = f(content)\n else:\n child = content\n\n if type(myself).__name__ == 'dict':\n if name in myself:\n raise ValueError(\"Key already used.\")\n myself[name] = child\n elif type(myself).__name__ == 'list':\n myself.append(child)\n\n def up(self, skip_a_level, function=None):\n myself = self.genealogy[-1]['content']\n parent = self.genealogy[-2]['content']\n index = self.genealogy[-2]['index']\n\n if skip_a_level:\n def skip_level(e):\n children = list(e.values())\n if len(children) != 1:\n import ipdb\n ipdb.set_trace()\n assert(len(children) == 1)\n return children[0]\n if type(myself).__name__ == 'dict':\n parent[index] = skip_level(myself)\n if type(myself).__name__ == 'list':\n parent[index] = [skip_level(e) for e in myself]\n\n if function:\n f = self.functions[function]\n parent[index] = f(parent[index])\n self.genealogy.pop()\n self.genealogy[-1]['index'] = None\n","sub_path":"weakparser/resulttree.py","file_name":"resulttree.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"519350925","text":"from tkinter import *\nfrom tkinter.filedialog import *\nfrom tkinter.simpledialog import *\nimport math\nimport cv2\nimport numpy\n## 전역 변수부\nwindow, canvas, paper = None, None, None\ninImage, outImage = [], []; inH, inW, outH, outW = [0] * 4\ncvInImage, cvOutImage = None, None\nfilename = ''\nRGB,R, G, B= 3, 0, 1, 2\n# DB 관련\nconn, cur = None, None\nIP = '192.168.56.105'\nUSER = 'winUser'\nPASSWORD = '4321'\nDB = 'photo_db'\nfileList = None\ncount = 0\ntemp = 0\n## 함수 선언부\ndef mainMethod(email,name):\n def malloc(h, w, value=0) :\n retMemory = [ [ value for _ in range(w)] for _ in range(h) ]\n return retMemory\n\n def mallocNumpy(t, h, w):\n retMemory = np.zeros((t, h, w), dtype=np.int16)\n return retMemory\n\n def allocateOutMemory() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n # outImage = []\n # for _ in range(RGB) :\n # outImage.append(malloc(outH, outW))\n outImage = mallocNumpy(RGB, outH, outW)\n\n def openFile() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n ## 파일 선택하기\n filename = askopenfilename(parent=window,\n filetypes=(('Color 파일', '*.jpg;*.png;*.bmp;*.tif'), ('All File', '*.*')))\n ## (중요!) 입력이미지의 높이와 폭 알아내기\n cvInImage = cv2.imread(filename)\n inH = cvInImage.shape[0]\n inW = cvInImage.shape[1]\n ## 입력이미지용 메모리 할당\n # inImage = []\n # for _ in range(RGB) :\n # inImage.append(malloc(inH, inW))\n inImage = mallocNumpy(RGB, inH, inW)\n ## 파일 --> 메모리 로딩\n\n for i in range(inH):\n for k in range(inW):\n inImage[R][i][k] = cvInImage.item(i, k ,B)\n inImage[G][i][k] = cvInImage.item(i, k, G)\n inImage[B][i][k] = cvInImage.item(i, k, R)\n\n equalColor()\n\n import numpy as np\n def saveImage() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if filename == None or filename == '' :\n return\n\n saveCvPhoto = np.zeros((outH, outW, 3), np.uint8)\n for i in range(outH) :\n for k in range(outW) :\n tup = tuple(([outImage[B][i][k],outImage[G][i][k],outImage[R][i][k]]))\n saveCvPhoto[i,k] = tup\n\n saveFp = asksaveasfile(parent=window, mode='wb',defaultextension='.', filetypes=((\"그림 파일\", \"*.png;*.jpg;*.bmp;*.tif\"), (\"모든 파일\", \"*.*\")))\n if saveFp == '' or saveFp == None:\n return\n cv2.imwrite(saveFp.name, saveCvPhoto)\n\n\n def displayImageColor() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if canvas != None :\n canvas.destroy()\n\n VX, VY = 512, 512 # 최대 화면 크기\n ## 크기가 512보다 크면, 최대 512로 보이기....\n if outH <= VY or outW <= VX :\n VX = outW\n VY = outH\n step = 1\n else :\n if outH > outW:\n step = outH / VY\n VX = int(VY * outW / outH)\n else:\n step = outW / VX\n VY = int(VX * outH / outW)\n\n window.geometry(str(int(VX*1.2)) + 'x' + str(int(VY*1.2)))\n canvas = Canvas(window, height=VY, width=VX)\n paper = PhotoImage(height=VY, width=VX)\n canvas.create_image((VX // 2, VY // 2), image=paper, state='normal')\n # 메모리에서 처리한 후, 한방에 화면에 보이기 --> 완전 빠름\n import numpy\n rgbString =\"\"\n for i in numpy.arange(0,outH,step) :\n tmpString = \"\" # 각 줄\n for k in numpy.arange(0, outW, step) :\n i=int(i); k = int(k)\n r = outImage[R][i][k]\n g = outImage[G][i][k]\n b = outImage[B][i][k]\n tmpString += \"#%02x%02x%02x \" % (r, g, b)\n rgbString += '{' + tmpString + '} '\n paper.put(rgbString)\n canvas.pack(expand=1, anchor=CENTER)\n status.configure(text='이미지정보:' + str(outH) + 'x' + str(outW)+' '+filename)\n\n\n ###### 영상 처리 함수 ##########\n def equalColor() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if filename == '' or filename == None:\n return\n ## (중요!) 출력이미지의 높이, 폭을 결정 ---> 알고리즘에 의존\n outH = inH; outW = inW\n ## 출력이미지 메모리 할당\n\n # outImage = []\n # for _ in range(RGB) :\n # outImage.append(malloc(outH, outW))\n #outImage = allocateOutMemory()\n ### 진짜 영상처리 알고리즘 ###\n # for rgb in range(RGB):\n # for i in range(inH):\n # for k in range(inW):\n # outImage[rgb][i][k] = inImage[rgb][i][k]\n outImage = inImage.copy()\n ########################\n displayImageColor()\n import time\n def reverseColor() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if filename == '' or filename == None:\n return\n start = time.time()\n ## (중요!) 출력이미지의 높이, 폭을 결정 ---> 알고리즘에 의존\n outH = inH; outW = inW\n ## 출력이미지 메모리 할당\n outImage = mallocNumpy(RGB, outH, outW)\n ### 진짜 영상처리 알고리즘 ###\n # value = askinteger(\"밝게하기\", \"값\")\n # if value == None :\n # return\n for rgb in range(RGB):\n for i in range(inH):\n for k in range(inW):\n outImage[rgb][i][k] = 255 - inImage[rgb][i][k]\n ########################\n displayImageColor()\n end = time.time()\n second = end-start\n status.configure(text=\"{0:.2f}\".format(second) + \"초 \" + status.cget(\"text\") )\n\n def reverseColor_NP() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if filename == '' or filename == None:\n return\n start = time.time()\n ## (중요!) 출력이미지의 높이, 폭을 결정 ---> 알고리즘에 의존\n outH = inH; outW = inW\n ## 출력이미지 메모리 할당\n outImage = mallocNumpy(RGB, outH, outW)\n ### 진짜 영상처리 알고리즘 ###\n # value = askinteger(\"밝게하기\", \"값\")\n # if value == None :\n # return\n outImage = 255 - inImage\n ########################\n displayImageColor()\n end = time.time()\n second = end - start\n status.configure(text=\"{0:.2f}\".format(second) + \"초 \" + status.cget(\"text\") )\n\n def addColor() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if filename == '' or filename == None:\n return\n start = time.time()\n ## (중요!) 출력이미지의 높이, 폭을 결정 ---> 알고리즘에 의존\n outH = inH; outW = inW\n ## 출력이미지 메모리 할당\n outImage = mallocNumpy(RGB, outH, outW)\n ### 진짜 영상처리 알고리즘 ###\n value = askinteger(\"밝게하기\", \"값\")\n if value == None:\n return\n for rgb in range(RGB):\n for i in range(inH):\n for k in range(inW):\n out = inImage[rgb][i][k] + value\n if out > 255:\n outImage[rgb][i][k] = 255\n else:\n outImage[rgb][i][k] = out\n ########################\n displayImageColor()\n end = time.time()\n second = end-start\n status.configure(text=\"{0:.2f}\".format(second) + \"초 \" + status.cget(\"text\") )\n\n def addColor_NP() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if filename == '' or filename == None:\n return\n start = time.time()\n ## (중요!) 출력이미지의 높이, 폭을 결정 ---> 알고리즘에 의존\n outH = inH; outW = inW\n ## 출력이미지 메모리 할당\n outImage = mallocNumpy(RGB, outH, outW)\n ### 진짜 영상처리 알고리즘 ###\n value = askinteger(\"밝게하기\", \"값\")\n if value == None :\n return\n inImage = inImage.astype(np.int16)\n outImage = inImage + value\n\n # 조건으로 범위 지정\n outImage = np.where(outImage > 255, 255, outImage)\n outImage = np.where(outImage < 0, 0, outImage)\n ########################\n displayImageColor()\n end = time.time()\n second = end - start\n status.configure(text=\"{0:.2f}\".format(second) + \"초 \" + status.cget(\"text\") )\n\n\n def grayColor() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if filename == '' or filename == None:\n return\n ## (중요!) 출력이미지의 높이, 폭을 결정 ---> 알고리즘에 의존\n outH = inH; outW = inW\n ## 출력이미지 메모리 할당\n outImage = mallocNumpy(RGB, outH, outW)\n ### 진짜 영상처리 알고리즘 ###\n for i in range(inH):\n for k in range(inW):\n c = inImage[R][i][k] + inImage[G][i][k] + inImage[B][i][k]\n c = int(c/3)\n outImage[R][i][k] = outImage[G][i][k] = outImage[B][i][k] = c\n ########################\n displayImageColor()\n\n\n ### MySQL 관련 함수 ###\n import tempfile\n import os\n import pymysql\n import random\n def upMySQL() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage\n if filename == None or filename == '':\n return\n\n saveCvPhoto = np.zeros((outH, outW, 3), np.uint8)\n for i in range(outH):\n for k in range(outW):\n tup = tuple(([outImage[B][i][k], outImage[G][i][k], outImage[R][i][k]]))\n saveCvPhoto[i, k] = tup\n\n saveFname = tempfile.gettempdir() + '/' + os.path.basename(filename)\n cv2.imwrite(saveFname, saveCvPhoto)\n ##############\n '''\n DROP DATABASE IF exists photo_db;\n CREATE DATABASE photo_db;\n USE photo_db;\n CREATE TABLE photo_table (\n p_id INT PRIMARY KEY,\n p_fname VARCHAR(255),\n p_ext CHAR(5),\n p_size BIGINT,\n p_height INT,\n p_width INT,\n p_photo LONGBLOB,\n p_upDate DATE,\n p_upUser CHAR(10) -- Foreign Key\n )\n '''\n conn = pymysql.connect(host=IP, user=USER, password=PASSWORD, db=DB, charset='utf8')\n cur = conn.cursor() # 빈 트럭 준비\n p_id = random.randint(-2100000000, 2100000000)\n tmpName = os.path.basename(os.path.basename(saveFname))\n p_fname, p_ext = tmpName.split('.')\n p_size = os.path.getsize(saveFname)\n tmpImage = cv2.imread(saveFname)\n p_height = tmpImage.shape[0]\n p_width = tmpImage.shape[1]\n p_upDate = '20201008' # 구글링\n p_upUser = 'root' # 로그인한 사용자\n\n # 파일을 읽기\n fp = open(saveFname, 'rb')\n blobData = fp.read()\n fp.close()\n\n # 파일 정보 입력\n sql = \"INSERT INTO photo_table(p_id, p_fname, p_ext, p_size, p_height, p_width, \"\n sql += \"p_upDate, p_UpUser, p_photo) VALUES (\" + str(p_id) + \", '\" + p_fname + \"', '\" + p_ext\n sql += \"', \" + str(p_size) + \",\" + str(p_height) + \",\" + str(p_width) + \", '\" + p_upDate\n sql += \"', '\" + p_upUser + \"', %s )\"\n tupleData = (blobData,)\n cur.execute(sql,tupleData)\n\n conn.commit()\n cur.close()\n conn.close()\n messagebox.showinfo('성공', filename + ' 잘 입력됨.')\n\n #############\n\n\n def downMySQL() : # 파일 열기 개념....\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n ###################\n conn = pymysql.connect(host=IP, user=USER, password=PASSWORD, db=DB, charset='utf8')\n cur = conn.cursor() # 빈 트럭 준비\n sql = \"SELECT p_id, p_fname, p_ext, p_size FROM photo_table\"\n cur.execute(sql)\n fileList = cur.fetchall()\n cur.close()\n conn.close()\n ##################\n # 서브 윈도창 나오기.\n def downLoad() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n selectIndex = listData.curselection()[0]\n conn = pymysql.connect(host=IP, user=USER, password=PASSWORD, db=DB, charset='utf8')\n cur = conn.cursor() # 빈 트럭 준비\n sql = \"SELECT p_fname, p_ext, p_photo FROM photo_table WHERE p_id= \"\n sql += str(fileList[selectIndex][0])\n cur.execute(sql)\n p_fname, p_ext, p_photo = cur.fetchone()\n\n fullPath = tempfile.gettempdir() + '/' + p_fname + '.' + p_ext\n fp = open(fullPath, 'wb')\n fp.write(p_photo)\n print(fullPath)\n fp.close()\n cur.close()\n conn.close()\n\n filename = fullPath\n subWindow.destroy()\n ####\n cvInImage = cv2.imread(filename)\n inH = cvInImage.shape[0]\n inW = cvInImage.shape[1]\n ## 입력이미지용 메모리 할당\n inImage = []\n for _ in range(RGB):\n inImage.append(malloc(inH, inW))\n ## 파일 --> 메모리 로딩\n\n for i in range(inH):\n for k in range(inW):\n inImage[R][i][k] = cvInImage.item(i, k, B)\n inImage[G][i][k] = cvInImage.item(i, k, G)\n inImage[B][i][k] = cvInImage.item(i, k, R)\n\n equalColor()\n ####\n\n subWindow = Toplevel(window)\n subWindow.geometry('300x400')\n\n ## 스크롤바 나타내기\n frame = Frame(subWindow)\n scrollbar = Scrollbar(frame)\n scrollbar.pack(side='right', fill = 'y')\n listData = Listbox(frame, yscrollcommand=scrollbar.set); listData.pack()\n scrollbar['command']=listData.yview\n frame.pack()\n\n for fileTup in fileList:\n listData.insert(END, fileTup[1:])\n btnDownLoad = Button(subWindow, text='!!다운로드!!', command=downLoad)\n btnDownLoad.pack(padx=10, pady=10)\n\n ## 엑셀 처리 부분\n import xlrd\n import xlwt\n def saveExcel() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n saveFp = asksaveasfile(parent=window, mode='wb',defaultextension='xls',\n filetypes=((\"엑셀 파일\", \"*.xls\"), (\"모든 파일\", \"*.*\")))\n if saveFp == '' or saveFp == None:\n return\n xlsName = saveFp.name\n #sheetName = os.path.basename(filename) # cat01_256.png\n wb = xlwt.Workbook()\n ws_R = wb.add_sheet(\"RED\")\n ws_G = wb.add_sheet(\"GREEN\")\n ws_B = wb.add_sheet(\"BLUE\")\n for i in range(outH) :\n for k in range(outW) :\n ws_R.write(i,k, outImage[R][i][k])\n ws_G.write(i, k, outImage[G][i][k])\n ws_B.write(i, k, outImage[B][i][k])\n\n wb.save(xlsName)\n print('Excel. save ok...')\n\n\n def openExcel() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n\n filename = askopenfilename(parent=window,\n filetypes=(('엑셀 파일', '*.xls'), ('All File', '*.*')))\n\n workbook = xlrd.open_workbook(filename)\n wsList = workbook.sheets() # 3장 워크시트\n inH = wsList[0].nrows\n inW = wsList[0].ncols\n ## 입력이미지용 메모리 할당\n inImage = []\n for _ in range(RGB):\n inImage.append(malloc(inH, inW))\n ## 파일 --> 메모리 로딩\n for i in range(inH):\n for k in range(inW):\n inImage[R][i][k] = int(wsList[R].cell_value(i, k))\n inImage[G][i][k] = int(wsList[G].cell_value(i, k))\n inImage[B][i][k] = int(wsList[B].cell_value(i, k))\n\n equalColor()\n\n import xlsxwriter\n def drawExcel() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n saveFp = asksaveasfile(parent=window, mode='wb',defaultextension='xls',\n filetypes=((\"엑셀 파일\", \"*.xls\"), (\"모든 파일\", \"*.*\")))\n if saveFp == '' or saveFp == None:\n return\n xlsName = saveFp.name\n #sheetName = os.path.basename(filename) # cat01_256.png\n wb = xlsxwriter.Workbook(xlsName)\n ws_R = wb.add_worksheet(\"RED\")\n ws_G = wb.add_worksheet(\"GREEN\")\n ws_B = wb.add_worksheet(\"BLUE\")\n\n # 셀 크기를 조절\n ws_R.set_column(0, outW-1, 1.0) # 엑셀에서 0.34\n for i in range(outH) :\n ws_R.set_row(i, 9.5) # 엑셀에서 약 0.35\n ws_G.set_column(0, outW - 1, 1.0) # 엑셀에서 0.34\n for i in range(outH):\n ws_G.set_row(i, 9.5) # 엑셀에서 약 0.35\n ws_B.set_column(0, outW - 1, 1.0) # 엑셀에서 0.34\n for i in range(outH):\n ws_B.set_row(i, 9.5) # 엑셀에서 약 0.35\n # 메모리 --> 엑셀 파일\n for i in range(outH) :\n for k in range(outW) :\n ## Red 시트\n data = outImage[R][i][k]\n if data <= 15 :\n hexStr = '#' + ('0' + hex(data)[2:]) + '0000'\n else :\n hexStr = '#' + hex(data)[2:] + '0000'\n # 셀 속성 변경\n cell_format = wb.add_format()\n cell_format.set_bg_color(hexStr)\n ws_R.write(i,k,'', cell_format)\n\n wb.close()\n print('Excel Art. save ok...')\n\n ### OpenCV 용 함수 모음 ###\n def cvOut2outImage() : # OpenCV의 결과 --> OutImage 메모리에 넣기\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n ## 결과 메모리의 크기\n outH = cvOutImage.shape[0]\n outW = cvOutImage.shape[1]\n ## 입력이미지용 메모리 할당\n outImage = []\n for _ in range(RGB) :\n outImage.append(malloc(outH, outW))\n ## cvOut --> 메모리\n for i in range(outH):\n for k in range(outW):\n if (cvOutImage.ndim == 2) : # 그레이, 흑백\n outImage[R][i][k] = cvOutImage.item(i, k)\n outImage[G][i][k] = cvOutImage.item(i, k)\n outImage[B][i][k] = cvOutImage.item(i, k)\n else :\n outImage[R][i][k] = cvOutImage.item(i, k ,B)\n outImage[G][i][k] = cvOutImage.item(i, k, G)\n outImage[B][i][k] = cvOutImage.item(i, k, R)\n\n def grayscale_CV() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n if filename == None :\n return\n ##### OpenCV 용 영상처리 ###\n cvOutImage = cv2.cvtColor(cvInImage, cv2.COLOR_BGR2GRAY)\n cvOut2outImage()\n ########################\n displayImageColor()\n\n def cartoon_CV() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n if filename == None :\n return\n ##### OpenCV 용 영상처리 ###\n cvOutImage = cv2.cvtColor(cvInImage, cv2.COLOR_RGB2GRAY)\n cvOutImage = cv2.medianBlur(cvOutImage, 7)\n edges = cv2.Laplacian(cvOutImage, cv2.CV_8U, ksize=5)\n ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)\n cvOutImage = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)\n cvOut2outImage()\n ########################\n displayImageColor()\n\n def faceDetect_CV() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n if filename == None :\n return\n ##### OpenCV 용 영상처리 ###\n face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')\n grey = cv2.cvtColor(cvInImage[:], cv2.COLOR_BGR2GRAY)\n # 얼굴 찾기\n cvOutImage = cvInImage[:]\n fact_rects = face_cascade.detectMultiScale(grey, 1.1, 5)\n for x, y, w, h in fact_rects:\n cv2.rectangle(cvOutImage, (x, y), (x + h, y + w), (0, 255, 0), 3)\n\n cvOut2outImage()\n ########################\n displayImageColor()\n\n def catFaceDetect_CV() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n if filename == None :\n return\n ##### OpenCV 용 영상처리 ###\n face_cascade = cv2.CascadeClassifier('haarcascade_frontalcatface.xml')\n grey = cv2.cvtColor(cvInImage[:], cv2.COLOR_BGR2GRAY)\n # 얼굴 찾기\n cvOutImage = cvInImage[:]\n fact_rects = face_cascade.detectMultiScale(grey, 1.1, 5)\n for x, y, w, h in fact_rects:\n cv2.rectangle(cvOutImage, (x, y), (x + h, y + w), (0, 255, 0), 3)\n\n cvOut2outImage()\n ########################\n displayImageColor()\n\n def ssdNet(image) :\n global count\n CONF_VALUE = 0.8 # 20% 인정\n CLASSES = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\n \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\n \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\",\n \"sofa\", \"train\", \"tvmonitor\"]\n COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n net = cv2.dnn.readNetFromCaffe(\"MobileNetSSD_deploy.prototxt.txt\", \"MobileNetSSD_deploy.caffemodel\")\n (h, w) = image.shape[:2]\n\n blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)\n net.setInput(blob)\n detections = net.forward()\n\n count = 0\n for i in np.arange(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n if confidence > CONF_VALUE:\n count +=1\n idx = int(detections[0, 0, i, 1])\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n label = \"{}: {:.2f}%\".format(CLASSES[idx], confidence * 100)\n print('count',count,label)\n cv2.rectangle(image, (startX, startY), (endX, endY), COLORS[idx], 2)\n y = startY - 15 if startY - 15 > 15 else startY + 15\n cv2.putText(image, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)\n return image\n\n\n def deepStopImage_CV() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n if filename == None:\n return\n ##### OpenCV 용 영상처리 ###\n cvOutImage = ssdNet(cvInImage)\n\n cvOut2outImage()\n ########################\n displayImageColor()\n\n #영상\n def deepMoveImage_CV() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n\n movieName = askopenfilename(parent=window,\n filetypes=(('동영상 파일', '*.mp4;*.avi'), ('All File', '*.*')))\n s_factor = 0.5 # 화면 크기 비율(조절 가능)\n\n # cv2.VideoCapture(\"동영상 경로\") : 프레임 단위로 저장\n capture = cv2.VideoCapture(movieName)\n\n\n frameCount = 0 # 처리할 프레임의 숫자 (자동증가)\n ##### OpenCV 용 영상처리 ###\n while True:\n ret, frame = capture.read()\n if not ret: # 동영상을 읽기 실패\n break\n frameCount += 1\n if frameCount % 30 == 0 : # 숫자 조절 가능 (속도 문제)\n frame = cv2.resize(frame, None, fx=s_factor, fy=s_factor, interpolation=cv2.INTER_AREA)\n ## 1장짜리 SSD 딥러닝 ##\n retImage = ssdNet(frame)\n ####################\n cv2.imshow('Video', retImage)\n\n # 입력한숫자ms마다 프레임을 재생합니다.\n key = cv2.waitKey(1) # 화면 속도 조절\n\n if key == 27: # esc 키\n break\n elif key == ord('c') or key == ord('C'):\n # 키보드가 아닌, 조건에 의해서 처리도 가능함...\n # 예로 사람이 3명이상 등장하면...... 강아지가 나타나면...\n cvInImage = cvOutImage = retImage\n filename = movieName\n cvOut2outImage()\n displayImageColor()\n\n capture.release()\n #cv2.destroyAllWindows()\n ########################\n #displayImageColor()\n\n #영상\n def deepMoveImage_CV2() :\n global window, canvas, paper, inImage, outImage, inH, inW, outH, outW, filename\n global cvInImage, cvOutImage, fileList\n global temp\n\n movieName = askopenfilename(parent=window,\n filetypes=(('동영상 파일', '*.mp4;*.avi'), ('All File', '*.*')))\n s_factor = 0.5 # 화면 크기 비율(조절 가능)\n\n # cv2.VideoCapture(\"동영상 경로\") : 프레임 단위로 저장\n capture = cv2.VideoCapture(movieName)\n\n\n frameCount = 0 # 처리할 프레임의 숫자 (자동증가)\n ##### OpenCV 용 영상처리 ###\n while True:\n ret, frame = capture.read()\n if not ret: # 동영상을 읽기 실패\n break\n frameCount += 1\n # print('frameCount:',frameCount)\n #영상 프레임 = 이미지\n frame = cv2.resize(frame, None, fx=s_factor, fy=s_factor, interpolation=cv2.INTER_AREA)\n\n ## 1장짜리 SSD 딥러닝 ##\n\n frameCount += 1\n if frameCount % 10 == 0: # 숫자 조절 가능 (속도 문제)\n # 영상 프래임 원본 저장\n retImage = ssdNet(frame)\n\n # 이미지 처리작업\n cvInImage = retImage\n\n # cvOutImage = cv2.cvtColor(cvInImage, cv2.COLOR_RGB2GRAY)\n # cvOutImage = cv2.medianBlur(cvOutImage, 7)\n # edges = cv2.Laplacian(cvOutImage, cv2.CV_8U, ksize=5)\n # ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)\n # cvOutImage = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)\n\n #그레이스케일 효과\n cvOutImage = cv2.cvtColor(cvInImage, cv2.COLOR_BGR2GRAY)\n cvOut2outImage()\n\n # 원본영상 출력\n cv2.imshow('VideoOriginal', retImage)\n\n # 이미지 처���영상 출력\n retImage2 = cvOutImage\n cv2.imshow('Video', retImage2)\n\n\n # 입력한숫자ms마다 프레임을 재생합니다.\n key = cv2.waitKey(60) # 화면 속도 조절\n\n if key == 27: # esc 키\n break\n elif key == ord('c') or key == ord('C'):\n # 키보드가 아닌, 조건에 의해서 처리도 가능함...\n # 예로 사람이 3명이상 등장하면...... 강아지가 나타나면...\n cvInImage = cvOutImage = retImage\n filename = movieName\n cvOut2outImage()\n displayImageColor()\n # elif count >=3 :\n # cvInImage = cvOutImage = retImage\n # filename = movieName\n # cvOut2outImage()\n # displayImageColor()\n # print('count : ', count)\n\n if (count > temp) and (temp != None) :\n temp = count\n print('temp:',temp,' count:',count)\n cvInImage = cvOutImage = retImage\n filename = movieName\n cvOut2outImage()\n displayImageColor()\n\n\n capture.release()\n #cv2.destroyAllWindows()\n ########################\n #displayImageColor()\n\n ## 메인 코드부\n window = Tk()\n window.title('칼라 영상처리 Ver 0.8(include 하르케스케이드)')\n window.geometry('512x512')\n #window.resizable(height=False, width=False)\n status = Label(window, text='이미지정보:', bd=1, relief=SUNKEN, anchor=W)\n status.pack(side=BOTTOM, fill=X)\n\n ### 메뉴 만들기 ###\n mainMenu = Menu(window)\n window.configure(menu=mainMenu)\n\n fileMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"파일\", menu=fileMenu)\n fileMenu.add_command(label=\"열기(Open)\", command=openFile)\n fileMenu.add_command(label=\"저장(Save)\", command=saveImage)\n fileMenu.add_separator()\n fileMenu.add_command(label=\"닫기(Close)\")\n\n pixelMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"화소점 처리\", menu=pixelMenu)\n pixelMenu.add_command(label=\"동일영상\", command=equalColor)\n pixelMenu.add_command(label=\"반전영상\", command=reverseColor)\n pixelMenu.add_command(label=\"반전영상(NumPy)\", command=reverseColor_NP)\n pixelMenu.add_command(label=\"밝게하기\", command=addColor)\n pixelMenu.add_command(label=\"밝게하기(NumPy)\", command=addColor_NP)\n pixelMenu.add_command(label=\"그레이스케일\", command=grayColor)\n\n MySQLMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"MySQL\", menu=MySQLMenu)\n MySQLMenu.add_command(label=\"MySQL에 저장\", command=upMySQL)\n MySQLMenu.add_command(label=\"MySQL에서 열기\", command=downMySQL)\n\n excelMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"Excel\", menu=excelMenu)\n excelMenu.add_command(label=\"Excel에 저장\", command=saveExcel)\n excelMenu.add_command(label=\"Excel에서 열기\", command=openExcel)\n excelMenu.add_separator()\n excelMenu.add_command(label=\"Excel 아트\", command=drawExcel)\n\n openCVMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"OpenCV\", menu=openCVMenu)\n openCVMenu.add_command(label=\"그레이 스케일\", command=grayscale_CV)\n openCVMenu.add_command(label=\"카툰 이미지\", command=cartoon_CV)\n\n harrCVMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"머신러닝\", menu=harrCVMenu)\n harrCVMenu.add_command(label=\"하르케스케이드(얼굴)\", command=faceDetect_CV)\n harrCVMenu.add_command(label=\"하르케스케이드(고영희씨)\", command=catFaceDetect_CV)\n\n deepCVMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"딥러닝\", menu=deepCVMenu)\n deepCVMenu.add_command(label=\"사물 인식(정지영상)\", command=deepStopImage_CV)\n deepCVMenu.add_command(label=\"사물 인식(동영상)\", command=deepMoveImage_CV)\n deepCVMenu.add_command(label=\"사물 인식(연습)\", command=deepMoveImage_CV2)\n ######################\n\n window.mainloop()\n","sub_path":"[6] 빅데이터 분석 플랫폼 시스템 개발/pythonProject Ver10.26/PROJECT/SHOPPING MALL 2020-10-11/DeepLearning.py","file_name":"DeepLearning.py","file_ext":"py","file_size_in_byte":32103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"206218145","text":"# -*- coding: utf-8 -*-\n\n# open and file 是类似的\n\n\n\n\nfo = open('/pythontry/test.txt')\n# <_io.TextIOWrapper name='/pythontry/cp.py' mode='r' encoding='cp936'>\n# mode='r' 是只读的意思\nprint(fo.read()); # 通过read展示\nfo.close();\n\n\n","sub_path":"file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24217280","text":"import wx\nfrom wx.lib.pubsub import Publisher\nimport pyharvest.Time as Time\nfrom core.Config import HarvestConfig\nimport gui.Auth as Auth\nimport gui.Tasks as Tks\n\nclass HarvestApp:\n app = None\n mainFrame = None\n \n def __init__(self):\n self.app = wx.App(False)\n self.mainFrame = HarvestFrame(None)\n \n def run(self):\n self.app.MainLoop()\n\nclass HarvestFrame(wx.Frame):\n def __init__(self, parent, title = \"pyHarvest Tracker\"):\n self.validProjects = {}\n \n wx.Frame.__init__(self, parent, title = title)\n \n self.initMenus()\n self.initListeners()\n \n self.Show(True)\n \n self.conf = HarvestConfig()\n self.applicationUrl = self.conf.get('appUrl')\n \n if not self.applicationUrl:\n self.showAppUrlDialog()\n \n self.showAuthWindow()\n self.SetInitialSize()\n \n def initListeners(self):\n Publisher().subscribe(self.authEntered, (\"auth.information_entered\"))\n Publisher().subscribe(self.timerToggled, (\"task.timer_toggle\"))\n Publisher().subscribe(self.sendNewTask, (\"task.new_task\"))\n \n def initMenus(self):\n menuBar = wx.MenuBar()\n \n fileMenu = wx.Menu()\n newButton = fileMenu.Append(wx.NewId(), \"&New Task\")\n exitButton = fileMenu.Append(wx.ID_EXIT, \"E&xit\", \"Exit.\")\n \n self.Bind(wx.EVT_MENU, self.newTask, newButton)\n \n editMenu = wx.Menu()\n preferencesButton = editMenu.Append(wx.NewId(), 'Preferences')\n \n menuBar.Append(fileMenu, \"&File\")\n menuBar.Append(editMenu, \"Edit\")\n \n self.SetMenuBar(menuBar)\n \n def showAppUrlDialog(self):\n dlg = wx.TextEntryDialog(\n self,\n \"Please enter the URL of your harvest app. It will be https://{companyname}.harvestapp.com\",\n \"Please enter url\",\n \"\",\n wx.OK | wx.TE_LEFT\n )\n \n if dlg.ShowModal():\n self.applicationUrl = dlg.GetValue()\n self.conf.set('appUrl', self.applicationUrl)\n \n def showAuthWindow(self):\n self.username = self.conf.get('username')\n \n self.authWin = Auth.AuthPanel(self, self.username)\n self.authWin.Show()\n \n def showProjectError(self):\n dlg = wx.MessageDialog(\n self,\n \"Sorry, either you have entered your credentials incorrectly, or you have no projects.\" + \\\n \" If you feel you entered the data correctly, please contact your Harvest administrator.\",\n \"There was a problem.\"\n )\n \n dlg.ShowModal()\n dlg.Destroy()\n self.showAuthWindow()\n \n def showInterface(self):\n self.taskView = Tks.TaskView(self, self.dayData['entries'])\n self.taskView.Show()\n self.SetInitialSize()\n \n def timerToggled(self, e):\n \"\"\"\n Called when the user clicks on a timer to be toggled.\n \n @param event e\n \n @return mixed\n \"\"\"\n id = e.data['id']\n if not id:\n return\n \n return self.api.toggleTimer(id)\n \n def newTask(self, e):\n self.taskDialog = Tks.NewTaskDialog(self, self.validProjects, -1, \"New Task\")\n self.taskDialog.Show()\n \n def loadInitialData(self):\n self.api = Time.TimeApi(\n self.applicationUrl,\n self.username,\n self.password\n )\n \n self.dayData = self.api.getDaily()\n \n if not self.dayData or not self.dayData['projects']:\n self.showProjectError()\n return\n \n self.breakdownProjects()\n \n self.showInterface()\n \n def authEntered(self, e):\n self.username = e.data['username']\n \n self.conf.set('username', self.username)\n \n self.password = e.data['password']\n self.authWin.Hide()\n self.authWin.Destroy()\n \n self.loadInitialData()\n \n def breakdownProjects(self):\n for project in self.dayData['projects']:\n if not project.client:\n continue\n \n if not project.client in self.validProjects:\n self.validProjects[project.client] = {}\n \n if not project.name in self.validProjects[project.client]:\n self.validProjects[project.client][project.name] = None\n \n self.validProjects[project.client][project.name] = project\n \n def sendNewTask(self, e):\n res = self.api.createTask(e.data['notes'], e.data['project_id'], e.data['task_id'], e.data['hours'])\n \n self.taskDialog.Hide()\n self.taskDialog.Destroy()","sub_path":"gui/Frame.py","file_name":"Frame.py","file_ext":"py","file_size_in_byte":4819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"501809986","text":"# Run analysis on all .edgelist files.\n# Run with: python analyzePosts.py \n\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport csv\n\nNUM_HUBS = 300\n\nfor idx in range (0, NUM_HUBS):\n\n # 1. Read edgelist file & create graph.\n graph = nx.read_edgelist(\"./pubski_data/%s.edgelist\" % (idx), create_using=nx.DiGraph())\n\n # Draw graph for funzies.\n pos = nx.spring_layout(graph)\n node_colors = ['#10BDBB'] * len(graph.nodes())\n node_colors[1] = '#F37901'\n nx.draw_networkx_nodes(graph, pos, node_color=node_colors)\n nx.draw_networkx_labels(graph, pos, font_size=8)\n nx.draw_networkx_edges(graph, pos, edge_color='#8097A4', connectionstyle='arc3,rad=0.2', arrowsize=12)\n\n # Uncomment this section for a graph every 25 Pubskis.\n # if ((idx % 25) == 0):\n # plt.show()\n # plt.clf()\n\n # ----------------------------------------------------------------------------------------------\n # 2. Do analytics! \n # There are so many: https://networkx.github.io/documentation/stable/reference/index.html\n # print(nx.info(graph))\n\n num_nodes = len(graph.nodes())\n num_edges = len(graph.edges())\n degrees = nx.degree_histogram(graph)\n avg_degree = float('%.3f'%(sum(degrees) / len(degrees)))\n print('\\nbasic info', num_nodes, num_edges, avg_degree)\n\n # number of edges over number of possible edges. d = m / n(n-1)\n density = float('%.3f'%nx.density(graph))\n print('density', density)\n\n # Centrality Measures \n\n # the degree centrality for a node v is the fraction of nodes it is connected to.\n degree_centralities = nx.degree_centrality(graph)\n dcs = [n for _, n in degree_centralities.items()]\n avg_degree_centrality = float('%.3f'%(sum(dcs) / len(dcs)))\n min_degree_centrality = float('%.3f'%min(degree_centralities.values()))\n max_degree_centrality = float('%.3f'%max(degree_centralities.values()))\n print('degree centrality', avg_degree_centrality, min_degree_centrality, max_degree_centrality)\n\n # eigenvector centrality computes the centrality for a node based on the centrality of its neighbors.\n try: \n eigenvector_centralities = nx.eigenvector_centrality(graph)\n ecs = [n for _, n in eigenvector_centralities.items()]\n avg_ecs = float('%.3f'%(sum(ecs) / len(ecs)))\n min_ecs = float('%.3f'%min(eigenvector_centralities.values()))\n max_ecs = float('%.3f'%max(eigenvector_centralities.values()))\n print('eigenvector centrality', avg_ecs, min_ecs, max_ecs)\n except: \n avg_ecs = -1\n min_ecs = -1\n max_ecs = -1\n\n # betweenness centrality of a node v is the sum of the fraction of all-pairs shortest paths that pass through v\n betweenness_centralities = nx.betweenness_centrality(graph)\n bcs = [n for _, n in betweenness_centralities.items()]\n avg_bcs = float('%.3f'%(sum(bcs) / len(bcs)))\n min_bcs = float('%.3f'%min(betweenness_centralities.values()))\n max_bcs = float('%.3f'%max(betweenness_centralities.values()))\n print('betweenness centrality', avg_bcs, min_bcs, max_bcs)\n\n # Clique Measures\n\n # the max subgraph of nodes which are all adjacent to each other. \n from networkx.algorithms.approximation import clique\n max_clique = clique.max_clique(graph)\n max_clique_size = len(max_clique)\n print('max clique size', max_clique, max_clique_size)\n\n # Clustering Measures\n\n # num closed triplets / num total triplets - measure the degree of nodes tending to cluster together.\n clustering_coefficient = nx.average_clustering(graph)\n clustering_coefficient = float('%.3f'%clustering_coefficient)\n print('clustering coefficient', clustering_coefficient)\n\n # compute graph transitivity, the fraction of all possible triangles present in G.\n transitivity = nx.transitivity(graph)\n transitivity = float('%.3f'%transitivity)\n print('transitivity', transitivity)\n\n # Community Measures * \n\n # from networkx.algorithms import community\n # a lot of these are for finding community within a graph\n # whereas we are finding community across graphs...\n\n # Component Measures \n\n # strongly connected means all nodes have edges to all other nodes in the subgraph.\n num_strongly_connected = nx.number_strongly_connected_components(graph)\n print('num strongly connected components', num_strongly_connected)\n\n # Cover Measures\n\n # set of nodes s.t. each edge in the graph is incident to at least one node in said set.\n from networkx.algorithms.approximation import vertex_cover\n vertex_cover_nodes = vertex_cover.min_weighted_vertex_cover(graph)\n vertex_cover_size = len(vertex_cover_nodes)\n print('vertex cover', vertex_cover_nodes, vertex_cover_size)\n\n # Distance Measures\n\n # currently not possible b/c \n # NetworkXError: Foundinfinte path length b/c the digraph is not strongly connected.\n\n # the eccentricity of a node v is the maximum distance from v to all other nodes in G\n # eccentricities = nx.eccentricity(graph)\n # eccs = [n for _, n in eccentricities.items()]\n # avg_ecc = float('%.3f'%(sum(eccs) / len(eccs)))\n # min_ecc = float('%.3f'%min(eccentricities.values()))\n # max_ecc = float('%.3f'%max(eccentricities.values()))\n # print('eccentricity', avg_ecc, min_ecc, max_ecc)\n\n # diameter\n # diameter = nx.diameter(graph)\n # print(diameter)\n\n # Shortest Path Measures\n\n try: \n avg_shortest_path = nx.average_shortest_path_length(graph)\n avg_shortest_path = float('%.3f'%avg_shortest_path)\n print('avg shortest path len', avg_shortest_path)\n except: \n avg_shortest_path = -1\n\n # Similarity Measures\n\n # this could be a fun way to compare the current graph and previous.\n # but it apparently requires scipy :(\n # if idx > 0:\n # prev_graph = nx.read_edgelist(\"./pubski_data/%s.edgelist\" % (idx - 1), create_using=nx.DiGraph())\n # edit_dist = nx.graph_edit_distance(graph, prev_graph)\n # print('edit dist', edit_dist)\n\n\n \n # ----------------------------------------------------------------------------------------------\n # 3. Write results files!\n with open(\"./pubski_data/results.csv\", mode=\"a\") as results_file:\n fn = ['index', 'num_nodes', 'num_edges', 'density', 'avg_degree',\n 'avg_degree_central', 'min_degree_central', 'max_degree_central',\n 'avg_eigen_central', 'min_eigen_central', 'max_eigen_central',\n 'avg_btwn_central', 'min_btwn_central', 'max_btwn_central',\n 'max_clique_size', 'clustering_coefficient', 'transitivity',\n 'num_strongly_connected_components', 'vertex_cover_size', 'avg_shortest_path_len']\n results_writer = csv.DictWriter(results_file, fieldnames=fn)\n results_writer.writerow({\n 'index': idx, \n 'num_nodes': num_nodes,\n 'num_edges': num_edges,\n 'avg_degree': avg_degree,\n 'density': density, \n 'avg_degree_central': avg_degree_centrality,\n 'min_degree_central': min_degree_centrality,\n 'max_degree_central': max_degree_centrality,\n 'avg_eigen_central': avg_ecs,\n 'min_eigen_central': min_ecs,\n 'max_eigen_central': max_ecs,\n 'avg_btwn_central': avg_bcs,\n 'min_btwn_central': min_bcs,\n 'max_btwn_central': max_bcs,\n 'max_clique_size': max_clique_size,\n 'clustering_coefficient': clustering_coefficient,\n 'transitivity': transitivity,\n 'num_strongly_connected_components': num_strongly_connected,\n 'vertex_cover_size': vertex_cover_size,\n 'avg_shortest_path_len': avg_shortest_path\n })\n\n\n","sub_path":"analyzePosts.py","file_name":"analyzePosts.py","file_ext":"py","file_size_in_byte":7723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"625283345","text":"#Problem available at: https://leetcode.com/problems/valid-anagram/submissions/\nclass Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n \n l1 = list(s)\n l1.sort()\n \n l2 = list(t)\n l2.sort()\n \n return True if l1 == l2 else False\n ","sub_path":"ValidAnagram.py","file_name":"ValidAnagram.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"250911480","text":"\"\"\"add vote records table\n\nRevision ID: c55027ef9bc\nRevises: 3c88a7f436af\nCreate Date: 2013-01-17 17:04:35.530198\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'c55027ef9bc'\ndown_revision = '3c88a7f436af'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom bungeni.models.fields import FSBlob\n\n\ndef upgrade():\n op.create_table('item_schedule_vote',\n sa.Column('vote_id', sa.Integer(), nullable=False),\n sa.Column('schedule_id', sa.Integer(), nullable=False),\n sa.Column('date', sa.DateTime()),\n sa.Column('title', sa.Unicode(length=1024)),\n sa.Column('description', sa.UnicodeText()),\n sa.Column('result', sa.Unicode(length=255)),\n sa.Column('votes_for', sa.Integer()),\n sa.Column('votes_against', sa.Integer()),\n sa.Column('votes_absent', sa.Integer()),\n sa.Column('file', sa.Unicode(length=32)),\n sa.Column('language', sa.Unicode(length=5)),\n sa.PrimaryKeyConstraint('vote_id'),\n )\n op.create_foreign_key(\"item_schedule_vote_schedule_id_fkey\",\n \"item_schedule_vote\", \"item_schedule\", [\"schedule_id\"], [\"schedule_id\"]\n )\n\n\ndef downgrade():\n op.drop_table(\"item_schedule_vote\")\n","sub_path":"bungeni.buildout/trunk/data/alembic/versions/c55027ef9bc_add_vote_records_tab.py","file_name":"c55027ef9bc_add_vote_records_tab.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645210116","text":"\"\"\"\nThis module contains OverviewPage class and all relevant objects\n\"\"\"\nimport os\nimport datetime\n\nfrom PyQt5.QtWidgets import (QWidget, QFrame, QGridLayout, QTextEdit, QPushButton, QVBoxLayout, QHBoxLayout, QLabel, QScrollArea, QDateTimeEdit)\nfrom PyQt5.QtCore import Qt, QUrl, QByteArray, QModelIndex, QAbstractListModel, QPointF, pyqtSlot, QPoint\nfrom PyQt5.QtGui import QIcon, QColor\nfrom PyQt5.QtQml import QQmlApplicationEngine\nfrom PyQt5.QtQuickWidgets import QQuickWidget\nfrom PyQt5.QtQuick import QQuickView\n\nfrom norlyst.config import CLASSIFICATION_COLOR_DICT, CLASSIFICATION_STRING_DICT, CLASSIFICATION_PRIORITY_DICT, PROJECT_FILE_PATH\n\nclass OverviewPage(QWidget):\n \"\"\"\n OverviewPage contains functionality related to viewing an overview of a single day.\n \"\"\"\n def __init__(self, parent, database_access):\n super(QWidget, self).__init__(parent)\n self.layout = QGridLayout(self)\n\n self.overview_map = OverviewMap(self)\n\n self.scroll_area = QScrollArea(self)\n self.scroll_area.setWidgetResizable(True)\n self.scroll_area.setWidget(OverviewList(self.scroll_area))\n self.scroll_area.setFixedWidth(900)\n\n self.title_label = QLabel('EVENT LIST', self)\n self.title_label.setFixedWidth(250)\n\n self.daily_lock_manager = DailyLockManager(self, database_access)\n\n self.layout.addWidget(self.daily_lock_manager, 0, 3)\n self.layout.addWidget(self.title_label, 0, 2)\n self.layout.addWidget(self.overview_map, 0, 0, 2, 2)\n self.layout.addWidget(self.scroll_area, 1, 2, 1, 2)\n\n self.setLayout(self.layout)\n\n def setEventClassifications(self, event_classifications, chosen_date):\n \"\"\"\n Function for passing the event_classifications from the norlyst main widget to the overview_map and list of this widget.\n \"\"\"\n self.daily_lock_manager.setDailyLockForDate(chosen_date)\n self.overview_map.setEventClassifications(event_classifications)\n self.scroll_area.widget().setEventClassifications(event_classifications, self.daily_lock_manager.lock_status)\n\n if self.scroll_area.widget().getFocusedEventBox():\n self.scroll_area.ensureVisible(0, self.scroll_area.widget().getOffsetToFocusedEventClassification(), 200, 200)\n\n\"\"\"\nDAILY LOCK IMPLEMENTATION\n-------------------------\n\"\"\"\nclass DailyLockManager(QWidget):\n \"\"\"\n This class contains the functionality for locking and unlocking a certain day for the user and protecting the database for simultaneous changes by concurrent users.\n \"\"\"\n def __init__(self, parent, database_access):\n super(QWidget, self).__init__(parent)\n self.setFixedWidth(650)\n self.layout = QHBoxLayout(self)\n self.layout.setAlignment(Qt.AlignRight)\n\n self.__database_access = database_access\n\n self.events_date = (datetime.datetime.now() - datetime.timedelta(days=1)).date()\n self.lock_status = self.__database_access.isDateLockedToUser(self.events_date)\n\n self.__lock_label = QLabel(\"Automatic Event Date:\", self)\n self.__lock_button = QPushButton('', self)\n if self.lock_status:\n self.__lock_button.setIcon(QIcon('{0}/resources/icons/unlock.png'.format(PROJECT_FILE_PATH)))\n else:\n self.__lock_button.setIcon(QIcon('{0}/resources/icons/lock.png'.format(PROJECT_FILE_PATH)))\n self.__lock_button.setFixedSize(30, 30)\n self.__lock_button.clicked.connect(self.lockButtonPressed)\n\n self.__daily_lock_date = QDateTimeEdit(self.events_date)\n self.__daily_lock_date.setCalendarPopup(True)\n self.__daily_lock_date.setDisplayFormat(\"dd-MM-yyyy\")\n self.__daily_lock_date.setFixedWidth(150)\n self.__daily_lock_date.dateTimeChanged.connect(self.setEventDateToDateTimeEditValue)\n\n self.layout.addWidget(self.__lock_label)\n self.layout.addWidget(self.__daily_lock_date)\n self.layout.addWidget(self.__lock_button)\n\n def setDailyLockForDate(self, chosen_date):\n \"\"\"\n Function for setting this lock into the correct position for this date\n \"\"\"\n if self.__database_access.isDateLockedToUser(chosen_date):\n self.lock_status = True\n self.__lock_button.setIcon(QIcon('{0}/resources/icons/lock.png'.format(PROJECT_FILE_PATH)))\n else:\n self.lock_status = False\n self.__lock_button.setIcon(QIcon('{0}/resources/icons/unlock.png'.format(PROJECT_FILE_PATH)))\n\n def setEventDateToDateTimeEditValue(self):\n \"\"\"\n Function that sets a new value to event_date from the DateTimeEdit widget\n \"\"\"\n self.events_date = self.__daily_lock_date.date().toPyDate()\n self.setNewEventsDate()\n\n def setNewEventsDate(self):\n \"\"\"\n Function for setting the date for the tool and spreading the information around the program\n \"\"\"\n self.parent().parent().parent().parent().setEventsForChosenDate(self.events_date)\n\n def lockButtonPressed(self):\n \"\"\"\n Function for locking the chosen date of the daily lock manager\n \"\"\"\n if self.lock_status:\n self.parent().parent().parent().parent().saveChanges()\n self.__database_access.unlockDayForUser(self.events_date)\n else:\n self.__database_access.lockDayForUser(self.events_date)\n\n self.parent().parent().parent().parent().setEventsForChosenDate(self.events_date)\n\n\"\"\"\nOVERVIEW MAP FUNCTIONALITY\n--------------------------\n\"\"\"\n\nclass OverviewMap(QQuickWidget):\n \"\"\"\n This class contains functionality related to the overview Map\n \"\"\"\n def __init__(self, parent):\n super(QQuickWidget, self).__init__(parent)\n\n self.model = MarkerModel()\n self.context = self.rootContext()\n self.context.setContextProperty('markerModel', self.model)\n\n self.setSource(QUrl.fromLocalFile('{0}/map.qml'.format(PROJECT_FILE_PATH)))\n self.setResizeMode(QQuickWidget.SizeRootObjectToView)\n self.show()\n\n self.rootObject().childItems()[0].clicked.connect(self.mapEvent)\n\n def setEventClassifications(self, event_classifications):\n \"\"\"\n Function for setting the event classifications for the overviewMap\n \"\"\"\n self.model.clearAll()\n for ec in event_classifications:\n if ec.unimportant:\n continue\n\n if ec.getEvent().getLatitude().val is None:\n continue\n\n if ec.priority > 9999:\n ec_color = QColor(*CLASSIFICATION_COLOR_DICT[21])\n else:\n ec_color = QColor(*CLASSIFICATION_COLOR_DICT[ec.classification])\n\n self.model.addMarker(MapMarker(\n ec.event_id,\n QPointF(ec.getEvent().getLatitude().val, ec.getEvent().getLongitude().val),\n ec_color,\n ec.focus\n ))\n\n @pyqtSlot(int)\n def mapEvent(self, event_id):\n \"\"\"\n Function for focusing on a single event from clicking of a symbol on the map\n \"\"\"\n self.parent().parent().parent().parent().focusOnEvent(event_id)\n\nclass MapMarker(object):\n \"\"\"\n This class contains the information of a single marker on the map\n \"\"\"\n def __init__(self, event_id, position, color, highlight):\n self._position = position\n self._color = color\n self._event_id = event_id\n self._highlight = highlight\n\n def position(self):\n return self._position\n\n def setPosition(self, position):\n self._position = position\n\n def color(self):\n return self._color\n\n def setColor(self, color):\n self._color = color\n\n def eventId(self):\n return self._event_id\n\n def setEventId(self, event_id):\n self._event_id = event_id\n\n def highlight(self):\n return self._highlight\n\n def setHighlight(self, highlight):\n self._highlight = highlight\n\nclass MarkerModel(QAbstractListModel):\n position_role = Qt.UserRole + 1\n color_role = Qt.UserRole + 2\n event_id_role = Qt.UserRole + 3\n highlight_role = Qt.UserRole + 4\n\n _roles = {\n position_role: QByteArray(b'markerPosition'),\n color_role: QByteArray(b'markerColor'),\n event_id_role: QByteArray(b'markerEventId'),\n highlight_role: QByteArray(b'markerHighlight'),\n }\n\n def __init__(self, parent = None):\n QAbstractListModel.__init__(self, parent)\n self._markers = []\n\n def rowCount(self, index = QModelIndex()):\n return len(self._markers)\n\n def roleNames(self):\n return self._roles\n\n def data(self, index, role=Qt.DisplayRole):\n if index.row() >= self.rowCount():\n return QVariant()\n\n marker = self._markers[index.row()]\n\n if role == MarkerModel.position_role:\n return marker.position()\n elif role == MarkerModel.color_role:\n return marker.color()\n elif role == MarkerModel.event_id_role:\n return marker.eventId()\n elif role == MarkerModel.highlight_role:\n return marker.highlight()\n\n return QVariant()\n\n def setData(self, index, value, role=Qt.EditRole):\n if index.isValid():\n marker = self._markers[index.row()]\n\n if role == MarkerModel.position_role:\n return marker.setPosition(value)\n elif role == MarkerModel.color_role:\n return marker.setColor(value)\n elif role == MarkerModel.event_id_role:\n return marker.setEventId(value)\n elif role == MarkerModel.highlight_role:\n return marker.setHighlight(value)\n\n self.dataChanged.emit(index, index)\n\n return QAbstractListModel.setData(self, index, value, role)\n\n def removeRows(self, row, count, index):\n if (count == 0 or not self._markers):\n return True\n\n self.beginRemoveRows(index, row, row + count - 1)\n\n for i in reversed(range(row, row + count)):\n self._markers.pop(i)\n\n self.endRemoveRows()\n\n return True\n\n def addMarker(self, marker):\n self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())\n self._markers.append(marker)\n self.endInsertRows()\n\n def clearAll(self):\n self.beginResetModel()\n self._markers.clear()\n self.endResetModel()\n\n return True\n\n\"\"\"\nOVERVIEW LIST FUNCTIONALITY\n---------------------------\n\"\"\"\n\nclass OverviewList(QWidget):\n \"\"\"\n This class contains functionality related to the overview list\n \"\"\"\n def __init__(self, parent):\n super(QWidget, self).__init__(parent)\n\n self.layout = QVBoxLayout(self)\n self.layout.setAlignment(Qt.AlignTop)\n self.layout.setSpacing(8)\n\n self.classification_boxes = []\n for i in [1,2,3,4,5,6,7,10,20,21]:\n self.classification_boxes.append(ClassificationBox(self, i))\n\n self.event_boxes = []\n self.event_boxes.extend(self.classification_boxes)\n self.__priority_counter = 0\n\n self.setLayout(self.layout)\n\n def getFocusedEventBox(self):\n \"\"\"\n This function returns the focused EventBox object and None if None are focused\n \"\"\"\n for e_box in self.event_boxes:\n if e_box.getFocus():\n return e_box\n return None\n\n def getNewPriorityNumber(self):\n \"\"\"\n This function advances the priority counter with 1 and returns the new value for the event box\n \"\"\"\n self.__priority_counter += 1\n return self.__priority_counter\n\n def setEventClassifications(self, event_classifications, lock_status):\n \"\"\"\n Function for setting the event classifications for the overviewList\n \"\"\"\n self.event_boxes = []\n self.event_boxes.extend(self.classification_boxes)\n\n self.__priority_counter = 0\n\n for e_class in event_classifications:\n if e_class.unimportant:\n continue\n\n self.event_boxes.append(EventBox(self, e_class, lock_status))\n if e_class.priority != -1:\n if e_class.priority > 9999 and e_class.priority - 10000 > self.__priority_counter:\n self.__priority_counter = e_class.priority - 10000\n elif e_class.priority > -1 and e_class.priority > self.__priority_counter:\n self.__priority_counter = e_class.priority\n\n self.orderEventBoxes()\n\n def orderEventBoxes(self):\n \"\"\"\n Function for ordering EventBoxes\n \"\"\"\n for i in reversed(range(self.layout.count())):\n self.layout.itemAt(i).widget().setParent(None)\n\n self.event_boxes.sort(key = lambda x: x.getPriority(), reverse=True)\n\n for e_box in self.event_boxes:\n self.layout.addWidget(e_box)\n\n def getOffsetToFocusedEventClassification(self):\n \"\"\"\n Function for getting the offset to the focused Event Classification\n \"\"\"\n offset = 0\n\n for ec in self.event_boxes:\n offset += ec.height() + 8\n if ec.getFocus():\n break\n\n return offset\n\nclass ClassificationBox(QFrame):\n \"\"\"\n This class is the divider box for different event_classifications\n \"\"\"\n def __init__(self, parent, classification_type):\n super(QFrame, self).__init__(parent)\n self.setFrameStyle(QFrame.Box)\n self.setStyleSheet('background-color: rgb({0}, {1}, {2})'.format(*CLASSIFICATION_COLOR_DICT[classification_type]))\n self.setFixedWidth(400)\n self.setFixedHeight(40)\n\n self.priority = CLASSIFICATION_PRIORITY_DICT[classification_type]\n\n self.layout = QVBoxLayout(self)\n self.layout.setAlignment(Qt.AlignTop)\n\n self.layout.addWidget(QLabel(\"\" + CLASSIFICATION_STRING_DICT[classification_type]+\"\", self))\n\n self.setLayout(self.layout)\n\n def getPriority(self):\n return self.priority\n\n def getFocus(self):\n return False\n\n def getEventId(self):\n return -1\n\n def getHeight(self):\n return 40\n\nclass EventBox(QFrame):\n \"\"\"\n This class contains a single event description for a single day. These objects will be listed in the OverviewList widget.\n \"\"\"\n def __init__(self, parent, event_classification, lock_status):\n super(QFrame, self).__init__(parent)\n self.setFixedWidth(850)\n self.setFrameStyle(QFrame.Box)\n if event_classification.focus:\n self.setLineWidth(3)\n\n self.setStyleSheet('background-color: white')\n\n self.layout = QGridLayout(self)\n self.layout.setAlignment(Qt.AlignTop)\n self.layout.setContentsMargins(0, 0, 0, 0)\n self.layout.setSpacing(0)\n\n self.__text_layout = QVBoxLayout()\n self.__text_layout.setSpacing(5)\n self.__text_layout.setContentsMargins(5, 5, 5, 5)\n self.__button_layout = QHBoxLayout()\n self.__button_layout.setSpacing(4)\n self.__button_layout.setContentsMargins(5, 5, 5, 5)\n\n self.__event_classification = event_classification\n event = self.__event_classification.getEvent()\n\n self.__id_label = QLabel('ID: {0} - {1}'.format(event.event_id, event.waveform_h[0].getWaveformFileName()))\n self.__id_label.setContentsMargins(5, 5, 5, 5)\n self.__id_label.setStyleSheet('background-color: rgb({0}, {1}, {2}); border-bottom: 1px solid black'.format(*CLASSIFICATION_COLOR_DICT[event_classification.classification]))\n\n if event.getOriginTime() is None:\n origin_time = \"-\"\n else:\n origin_time = event.getOriginTime().val.strftime(\"%H:%M:%S\")\n\n self.__event_values_text = QLabel('Time: {0} Latitude: {1} Longitude: {2} Magnitude: {3}'.format(\n origin_time,\n event.getLatitude().val,\n event.getLongitude().val,\n event.getMagnitude().val,)\n , self)\n self.__event_values_text.setFixedHeight(20)\n\n category_string = \"Event Classification: {0} \".format(self.__event_classification.classification)\n if self.__event_classification.eqex is not None:\n category_string += 'EQ/EX: {0} '.format(self.__event_classification.eqex)\n if self.__event_classification.certainty is not None:\n category_string += 'Certainty: {0}'.format(self.__event_classification.certainty)\n\n self.__event_categorization_text = QLabel(category_string, self)\n self.__event_categorization_text.setFixedHeight(20)\n\n self.__remove_priority_button = QPushButton('', self)\n self.__remove_priority_button.setIcon(QIcon('{0}/resources/icons/remove.png'.format(PROJECT_FILE_PATH)))\n self.__remove_priority_button.setFixedSize(25, 25)\n self.__remove_priority_button.clicked.connect(self.removePriority)\n\n if (self.__event_classification.priority < 0 or self.__event_classification.priority > 9999):\n self.__remove_priority_button.hide()\n\n self.__push_to_top_button = QPushButton('', self)\n self.__push_to_top_button.setIcon(QIcon('{0}/resources/icons/push_to_top.png'.format(PROJECT_FILE_PATH)))\n self.__push_to_top_button.setFixedSize(25, 25)\n self.__push_to_top_button.clicked.connect(self.pushToTopPressed)\n\n self.__set_as_important_button = QPushButton('', self)\n if self.__event_classification.priority > 9999:\n self.__set_as_important_button.setIcon(QIcon('{0}/resources/icons/set_as_unimportant.png'.format(PROJECT_FILE_PATH)))\n else:\n self.__set_as_important_button.setIcon(QIcon('{0}/resources/icons/set_as_important.png'.format(PROJECT_FILE_PATH)))\n self.__set_as_important_button.setFixedSize(25, 25)\n self.__set_as_important_button.clicked.connect(self.setAsImportantPressed)\n\n self.__text_layout.addWidget(self.__event_values_text)\n self.__text_layout.addWidget(self.__event_categorization_text)\n\n self.__button_layout.addWidget(self.__remove_priority_button, 0, Qt.AlignTop)\n self.__button_layout.addWidget(self.__push_to_top_button, 0, Qt.AlignTop)\n self.__button_layout.addWidget(self.__set_as_important_button, 0, Qt.AlignTop)\n\n self.layout.addWidget(self.__id_label, 0, 0, 1, 2)\n self.layout.addLayout(self.__text_layout, 1, 0)\n self.layout.addLayout(self.__button_layout, 1, 1)\n\n if lock_status:\n self.unlockEventBox()\n else:\n self.lockEventBox()\n\n def getHeight(self):\n \"\"\"\n Function for getting the height of this object\n \"\"\"\n return 60\n\n def getEventId(self):\n \"\"\"\n Function for getting event classification event_id\n \"\"\"\n return self.__event_classification.event_id\n\n def getFocus(self):\n \"\"\"\n Get event focus status\n \"\"\"\n return self.__event_classification.focus\n\n def getPriority(self):\n \"\"\"\n Function for getting the priority of this event box\n \"\"\"\n if self.__event_classification.done:\n return -10\n elif self.__event_classification.priority == -1:\n return 0 - self.__event_classification.classification\n else:\n return self.__event_classification.priority\n\n def removePriority(self):\n \"\"\"\n Function for removing the priority number of this event\n \"\"\"\n self.__event_classification.priority = -1\n self.parent().parent().parent().parent().parent().parent().parent().setEventClassifications()\n self.__remove_priority_button.setVisible(False)\n self.repaint()\n\n def setAsImportantPressed(self):\n \"\"\"\n Function for setting a single event box as important.\n \"\"\"\n if self.__event_classification.priority > 9999:\n self.__set_as_important_button.setIcon(QIcon('{0}/resources/icons/set_as_important.png'.format(PROJECT_FILE_PATH)))\n self.__event_classification.priority -= 10001\n self.__push_to_top_button.setEnabled(True)\n self.__event_classification.focus = False\n self.parent().parent().parent().parent().parent().parent().parent().setEventClassifications()\n else:\n self.__event_classification.priority += 10001\n self.__set_as_important_button.setIcon(QIcon('{0}/resources/icons/set_as_unimportant.png'.format(PROJECT_FILE_PATH)))\n self.__push_to_top_button.setEnabled(False)\n self.highlightEvent()\n\n def pushToTopPressed(self):\n \"\"\"\n Function for pushing a event to the top of the priority list\n \"\"\"\n self.__event_classification.priority = self.parent().getNewPriorityNumber()\n\n self.parent().parent().parent().parent().parent().parent().parent().setEventClassifications()\n self.__remove_priority_button.setVisible(True)\n self.__remove_priority_button.repaint()\n\n def unlockEventBox(self):\n \"\"\"\n Function for unlocking an event box for interaction\n \"\"\"\n self.__set_as_important_button.setEnabled(True)\n self.__push_to_top_button.setEnabled(True)\n self.__remove_priority_button.setEnabled(True)\n\n\n def lockEventBox(self):\n \"\"\"\n Function for locking an event box from interaction\n \"\"\"\n self.__set_as_important_button.setEnabled(False)\n self.__push_to_top_button.setEnabled(False)\n self.__remove_priority_button.setEnabled(False)\n\n def highlightEvent(self):\n \"\"\"\n Function for highlighting this event classification\n \"\"\"\n self.parent().parent().parent().parent().parent().parent().parent().focusOnEvent(self.__event_classification.event_id)\n\n def mousePressEvent(self, event):\n \"\"\"\n Highlight the event classification when clicking an event classification box\n \"\"\"\n self.highlightEvent()\n","sub_path":"norlyst/overviewPage.py","file_name":"overviewPage.py","file_ext":"py","file_size_in_byte":21959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"190480092","text":"import matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib.pyplot import *\nimport src\nimport fourier\nfrom convolution import conv\nfrom scipy import stats\nimport numpy as np\nfrom functions import band_square_lattice\nimport os\n\nnp.set_printoptions(precision=3)\n\ndef linregress(x, y):\n return stats.linregress(x, y)[0]\n\n\ndef dyson(wn, beta, H, St, axis):\n dim = np.shape(H)[0]\n Sw, jumpS = fourier.t2w(St, beta, axis, 'fermion')\n tau0 = np.identity(dim)\n Gw = np.linalg.inv(1j*wn[:,None,None]*tau0 - H[None,:,:] - Sw)\n #jumpG = -np.identity(dim)[None,:,:]\n jumpG = -1\n return fourier.w2t(Gw, beta, axis, 'fermion', jumpG)\n \n\ndef test_dyson():\n beta = 16.0\n nw = 128\n dim = 1\n norb = 3\n\n wn = (2*np.arange(nw)+1) * np.pi / beta\n H = np.random.randn(norb, norb)\n H += np.transpose(H)\n\n # solve full dyson for bare Green's function\n St = np.zeros((2*nw+1, norb, norb))\n Gt_exact = dyson(wn, beta, H, St, 0)\n\n figure()\n plot(Gt_exact[:,0,0].real)\n plot(Gt_exact[:,0,0].imag)\n title('exact G')\n\n # solve for 11 component using embedding selfenergy\n St = np.zeros((2*nw+1, norb-dim, norb-dim))\n Gt_bath = dyson(wn, beta, H[dim:,dim:], St, 0)\n\n St = np.einsum('ab,wbc,cd->wad', H[:dim,dim:], Gt_bath, H[dim:,:dim])\n Gt = dyson(wn, beta, H[:dim, :dim], St, 0)\n\n print('diff')\n print(np.mean(np.abs(Gt-Gt_exact[:,:dim,:dim])))\n\n figure()\n plot(Gt[:,0,0].real)\n plot(Gt[:,0,0].imag)\n title('embedding test')\n show()\n\n\ndef old_test_dyson():\n '''\n embedding selfenergy test\n '''\n \n beta = 16.0\n nw = 128\n dim = 1\n norb = 3\n\n wn =(2*np.arange(nw)+1) * np.pi / beta\n\n H = np.random.randn(norb, norb)\n H += np.transpose(H)\n\n # solve full dyson for bare Green's function\n\n tau0 = np.identity(norb)\n Gw_exact = np.linalg.inv(1j*wn[:,None,None]*tau0 - H[None,:,:])\n jump = -np.identity(norb)\n Gt_exact = fourier.w2t(Gw_exact, beta, 0, 'fermion', jump) \n\n figure()\n plot(Gt_exact[:,0,0].real)\n plot(Gt_exact[:,0,0].imag)\n title('exact G')\n\n # solve for 11 component using embedding selfenergy\n \n tau0 = np.identity(norb-dim)\n Gw_bath = np.linalg.inv(1j*wn[:,None,None]*tau0 - H[None,dim:,dim:]) \n jump = -np.identity(norb-dim)\n Gt_bath = fourier.w2t(Gw_bath, beta, 0, 'fermion', jump)\n\n St = np.einsum('ab,wbc,cd->wad', H[:dim,dim:], Gt_bath, H[dim:,:dim])\n Sw = fourier.t2w(St, beta, 0, 'fermion')[0]\n\n tau0 = np.identity(dim)\n Gw = np.linalg.inv(1j*wn[:,None,None]*tau0 - H[None,:dim,:dim] - Sw)\n jump = -np.identity(dim)\n Gt = fourier.w2t(Gw, beta, 0, 'fermion', jump)\n\n print('diff')\n print(np.mean(np.abs(Gt-Gt_exact[:,:dim,:dim])))\n\n figure()\n plot(Gt[:,0,0].real)\n plot(Gt[:,0,0].imag)\n title('embedding test')\n show()\n\nif __name__=='__main__':\n test_dyson()\n\n","sub_path":"test/dyson.py","file_name":"dyson.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"347009236","text":"import datetime\n\nfrom legistar.events import LegistarEventsScraper\nfrom pupa.scrape import Event, Organization\n\nclass OaklandEventScraper(LegistarEventsScraper):\n TIMEZONE = \"US/Pacific\"\n EVENTSPAGE = \"https://oakland.legistar.com/Calendar.aspx\"\n BASE_URL = \"http://www2.oaklandnet.com/\"\n\n def scrape(self):\n current_year= self.now().year\n index = 0\n\n for event, agenda in self.events(since=current_year):\n index += 1\n print(event)\n print(agenda)\n\n event_name = event['Name'].replace('*', '')\n event_date = self.__parse_meeting_date(event['Meeting Date'], event['iCalendar']['url'])\n event_location = self.__parse_meeting_location(event['Meeting Location'])\n ocd_event = Event(name=event_name,\n start_date=event_date,\n # description=event['Meeting\\xa0Topic'], # Appears no description is available in Oakland Legistar\n location_name=event_location,\n status=self.__parse_meeting_status(event_name, event_date, event['Meeting Time']))\n\n\n if event[\"Meeting Details\"] != 'Not\\xa0available' and event[\"Meeting Details\"] != 'Meeting\\xa0details':\n ocd_event.add_source(event[\"Meeting Details\"]['url'], note='web')\n else:\n ocd_event.add_source(self.EVENTSPAGE)\n\n self.addDocs(ocd_event, event, 'Agenda')\n self.addDocs(ocd_event, event, 'Minutes')\n # This code is per documentation; line above is from another city's code\n # #add a pdf of meeting minutes\n # ocd_event.add_media_link(note=\"Meeting minutes\",\n # url=\"http://example.com/hearing/minutes.pdf\",\n # media_type=\"application/pdf\")\n\n # add an mpeg video\n if event['Video'] != 'Not\\xa0available':\n ocd_event.add_media_link(note=event['Video']['label'],\n url=event['Video']['url'],\n media_type=\"video/mpeg\")\n\n # add participating orgs\n participating_orgs = self.__parse_participating_orgs(event_name)\n print(\"###event_name: %s\" % event_name)\n \n for org in participating_orgs:\n print(\"###org: %s\" % org)\n ocd_event.add_committee(name=org)\n ocd_event.validate()\n\n # #add a person\n # ocd_event.add_person(name=\"Joe Smith\", note=\"Hearing Chair\")\n\n # #add an agenda item to this event\n # a = ocd_event.add_agenda_item(description=\"Testimony from concerned citizens\")\n\n # #the testimony is about transportation and the environment\n # a.add_subject(\"Transportation\")\n # a.add_subject(\"Environment\")\n\n # #and includes these two committees\n # a.add_committee(\"Transportation\")\n # a.add_committee(\"Environment and Natural Resources\")\n\n # #these people will be present\n # a.add_person(\"Jane Brown\")\n # a.add_person(\"Alicia Jones\")\n # a.add_person(\"Fred Green\")\n\n # #they'll be discussing this bill\n # a.add_bill(\"HB101\")\n\n # #here's a document that is included\n # a.add_media_link(note=\"Written version of testimony\",\n # url=\"http://example.com/hearing/testimony.pdf\",\n # media_type=\"application/pdf\")\n\n print(ocd_event)\n\n yield ocd_event\n\n \"\"\"\n if index < 5:\n yield ocd_event\n else:\n raise StopIteration()\n \"\"\"\n\n def __parse_meeting_date(self, date_str, ical_url):\n event_date = self.toTime(date_str)\n response = self.get(ical_url, verify=False)\n event_time = self.ical(response.text).subcomponents[0]['DTSTART'].dt\n event_date = event_date.replace(hour=event_time.hour,\n minute=event_time.minute)\n return event_date\n\n def __parse_meeting_location(self, location_str):\n return location_str.split('\\n')[0]\n\n def __parse_meeting_status(self, event_name, event_date, meeting_time_str):\n if event_name.lower().find('cancelled') or meeting_time_str.lower() in ('deferred', 'cancelled'):\n status = 'cancelled'\n elif self.now() < event_date:\n status = 'confirmed'\n else:\n status = 'passed'\n\n return status\n\n def __parse_participating_orgs(self, event_name):\n orgs = []\n org_str = event_name.replace(\"Concurrent Meeting of the\", '')\n org_tokens = org_str.split('and_the')\n\n for org_token in org_tokens: \n # org = None\n org_name = org_token\n org_type = 'committee'\n\n if org_token == 'City Council':\n org_name = 'Oakland City Council'\n org_type = 'legislature'\n\n org_name = org_name.replace(\"- CANCELLED\", '')\n orgs.append(org_name)\n\n return orgs\n\n","sub_path":"oakland/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":4654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"553753198","text":"#! /usr/bin/env python \n\"\"\"\n MatrixDFT: Matrix-based discrete Fourier transforms for computing PSFs. \n\n See Soummer et al. 2007 JOSA\n\n The main user interface in this module is a class MatrixFourierTransform. \n Internally this will call one of several subfunctions depending on the \n specified centering type. These have to do with where the (0,0) element of the Fourier\n transform is located, i.e. where the PSF center ends up.\n\n - 'FFTSTYLE' centered on one pixel\n - 'SYMMETRIC' centerd on crosshairs between middle pixel\n - 'ADJUSTIBLE', always centered in output array depending on whether it is even/odd\n\n 'ADJUSTIBLE' is the default.\n\n\n This module was originally called \"Slow Fourier Transform\", and this\n terminology still appears in some places in the code. Note that this is\n 'slow' only in the sense that if you perform the exact same calculation as\n an FFT, the FFT algorithm is much faster. However this algorithm gives you\n much more flexibility in choosing array sizes and sampling, and often lets\n you replace \"fast calculations on very large arrays\" with \"relatively slow\n calculations on much smaller ones\". \n\n\n\n Example\n -------\n mf = matrixDFT.MatrixFourierTransform()\n result = mf.perform(pupilArray, focalplane_size, focalplane_npix)\n\n\n\n\n History\n -------\n Code originally by A. Sivaramakrishnan\n 2010-11-05 Revised normalizations for flux conservation consistent\n with Soummer et al. 2007. Updated documentation. -- M. Perrin\n 2011-2012: Various enhancements, detailed history not kept, sorry.\n 2012-05-18: module renamed SFT.py -> matrixDFT.py\n 2012-09-26: minor big fixes\n\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function, unicode_literals)\n\n__all__ = ['MatrixFourierTransform']\n\nimport numpy as np\nimport astropy.io.fits as fits\n\nimport logging\n_log = logging.getLogger('poppy')\n\n\n\n# master routine combining all centering types\ndef DFT_combined(pupil, nlamD, npix, offset=(0.0,0.0), inverse=False, centering='FFTSTYLE', **kwargs):\n \"\"\"\n\n This function attempts to merge and unify the behaviors of all the other DFT routines\n into one master, flexible routines. It thus should subsume:\n DFT_fftstyle\n DFT_fftstyle_rect\n DFT_adjustible\n DFT_symmetric\n\n As of Jan 2013, this works OK for even-sized arrays, but for odd-sized arrays it\n appears to get the sense of fftstyle and symmetry flipped. Some debugging still needed?\n See the code in tests/test_matrixDFT.py. -MP\n\n Parameters\n ----------\n pupil : 2d ndarray\n pupil array (n by m). This can also be an image array if you're computing an\n inverse transformation.\n nlamD : float\n size of focal plane array, in units of lam/D\n (corresponds to 'm' in Soummer et al. 2007 4.2)\n npix : int\n number of pixels per side side of destination plane array\n (corresponds to 'N_B' in Soummer et al. 2007 4.2)\n This will be the # of pixels in the image plane for a forward\n transformation, in the pupil plane for an inverse. \n\n inverse : bool\n Is this a forward or inverse transformation?\n centering : string\n What type of centering convention should be used for this FFT? \n 'FFTYSTYLE', 'SYMMETRIC', 'ADJUSTIBLE'\n\n\n\n \"\"\"\n\n npupY, npupX = pupil.shape[0:2]\n\n if np.isscalar(npix): \n npixY, npixX = npix, npix\n else:\n npixY, npixX = npix[0:2] \n\n if not np.isscalar(nlamD): \n nlamDY, nlamDX = nlamD[0:2]\n else:\n nlamDY, nlamDX = nlamD, nlamD\n\n if inverse:\n dX = nlamDX / float(npupX)\n dY = nlamDY / float(npupY)\n dU = 1.0/float(npixY)\n dV = 1.0/float(npixX)\n else:\n dU = nlamDX / float(npixX)\n dV = nlamDX / float(npixX)\n dX = 1.0/float(npupX)\n dY = 1.0/float(npupY)\n\n#\n# du = nlamD / float(npix)\n# dv = nlamD / float(npix)\n#\n# dx = 1.0/float(npup)\n# dy = 1.0/float(npup)\n#\n if centering.upper() == 'FFTSTYLE':\n Xs = (np.arange(npupX) - (npupX/2)) * dX\n Ys = (np.arange(npupY) - (npupY/2)) * dY\n\n Us = (np.arange(npixY) - npixX/2) * dU\n Vs = (np.arange(npixX) - npixY/2) * dV\n elif centering.upper() == 'ADJUSTIBLE':\n Xs = (np.arange(npupX) - float(npupX)/2.0 - offset[1] + 0.5) * dX\n Ys = (np.arange(npupY) - float(npupY)/2.0 - offset[0] + 0.5) * dY\n\n Us = (np.arange(npixY) - float(npixX)/2.0 - offset[1] + 0.5) * dU\n Vs = (np.arange(npixX) - float(npixY)/2.0 - offset[0] + 0.5) * dV\n elif centering.upper() == 'SYMMETRIC':\n Xs = (np.arange(npupX) - float(npupX)/2.0 + 0.5) * dX\n Ys = (np.arange(npupY) - float(npupY)/2.0 + 0.5) * dY\n\n Us = (np.arange(npixY) - float(npixX)/2.0 + 0.5) * dU\n Vs = (np.arange(npixX) - float(npixY)/2.0 + 0.5) * dV\n\n\n\n\n\n XU = np.outer(Xs, Us)\n YV = np.outer(Ys, Vs)\n\n\n expXU = np.exp(-2.0 * np.pi * 1j * XU)\n expYV = np.exp(-2.0 * np.pi * 1j * YV)\n\n #print(\"\")\n #print dx, dy, du, dv\n #print(\"\")\n\n if inverse:\n expYV = expYV.T.copy()\n t1 = np.dot(expYV, pupil)\n t2 = np.dot(t1, expXU)\n else:\n expXU = expXU.T.copy()\n t1 = np.dot(expXU, pupil)\n t2 = np.dot(t1, expYV)\n\n #return nlamD/(npup*npix) * t2 * dx * dy\n norm_coeff = np.sqrt( ( nlamDY* nlamDX) / (npupY*npupX*npixY*npixX))\n #return float(nlamD)/(npup*npix) * t2 \n return norm_coeff * t2 \n\n\n\n# FFTSTYLE centering\ndef DFT_fftstyle(pupil, nlamD, npix, inverse=False, **kwargs):\n \"\"\"\n\n Compute an \"FFTSTYLE\" matrix fourier transform.\n This means that the zero-order term is put all in a \n single pixel.\n\n Parameters\n ----------\n pupil\n pupil array (n by n)\n nlamD\n size of focal plane array, in units of lam/D\n (corresponds to 'm' in Soummer et al. 2007 4.2)\n npix\n number of pixels per side side of focal plane array\n (corresponds to 'N_B' in Soummer et al. 2007 4.2)\n\n\n \"\"\"\n\n npup = pupil.shape[0]\n\n du = nlamD / float(npix)\n dv = nlamD / float(npix)\n\n dx = 1.0/float(npup)\n dy = 1.0/float(npup)\n\n Xs = (np.arange(npup) - (npup/2)) * dx\n Ys = (np.arange(npup) - (npup/2)) * dy\n\n Us = (np.arange(npix) - npix/2) * du\n Vs = (np.arange(npix) - npix/2) * dv\n\n XU = np.outer(Xs, Us)\n YV = np.outer(Ys, Vs)\n\n\n expXU = np.exp(-2.0 * np.pi * 1j * XU)\n expYV = np.exp(-2.0 * np.pi * 1j * YV)\n\n #print(\"\")\n #print( dx, dy, du, dv)\n #print(\"\")\n\n if inverse:\n expYV = expYV.T.copy()\n t1 = np.dot(expYV, pupil)\n t2 = np.dot(t1, expXU)\n else:\n expXU = expXU.T.copy()\n t1 = np.dot(expXU, pupil)\n t2 = np.dot(t1, expYV)\n\n #return nlamD/(npup*npix) * t2 * dx * dy\n return float(nlamD)/(npup*npix) * t2 \n\n\n# FFTSTYLE centering, rectangular pupils supported\ndef DFT_fftstyle_rect(pupil, nlamD, npix, inverse=False):\n \"\"\"\n\n Compute an \"FFTSTYLE\" matrix fourier transform.\n This means that the zero-order term is put all in a \n single pixel.\n\n This version supports rectangular, non-square arrays,\n in which case nlamD and npix should be 2-element\n tuples or lists, using the usual Pythonic order (Y,X)\n\n Parameters\n ----------\n pupil\n pupil array (n by n)\n nlamD\n size of focal plane array, in units of lam/D\n (corresponds to 'm' in Soummer et al. 2007 4.2)\n npix\n number of pixels per side side of focal plane array\n (corresponds to 'N_B' in Soummer et al. 2007 4.2)\n\n\n \"\"\"\n\n npupY, npupX = pupil.shape[0:2]\n\n if np.isscalar(npix): #hasattr(npix, '__getitem__'):\n npixY, npixX = npix, npix\n else:\n npixY, npixX = npix[0:2] \n\n if np.isscalar(nlamD): # hasattr(nlamD, '__getitem__'):\n nlamDY, nlamDX = nlamD, nlamD\n else:\n nlamDY, nlamDX = nlamD[0:2]\n\n\n if inverse:\n dX = nlamDX / float(npupX)\n dY = nlamDY / float(npupY)\n dU = 1.0/float(npixY)\n dV = 1.0/float(npixX)\n else:\n dU = nlamDX / float(npixX)\n dV = nlamDX / float(npixX)\n dX = 1.0/float(npupX)\n dY = 1.0/float(npupY)\n\n Xs = (np.arange(npupX) - (npupX/2)) * dX\n Ys = (np.arange(npupY) - (npupY/2)) * dY\n\n Us = (np.arange(npixX) - npixX/2) * dU\n Vs = (np.arange(npixY) - npixY/2) * dV\n\n YV = np.outer(Ys, Vs)\n XU = np.outer(Xs, Us)\n\n expYV = np.exp(-2.0 * np.pi * 1j * YV) \n expXU = np.exp(-2.0 * np.pi * 1j * XU)\n\n expYV = expYV.T.copy()\n t1 = np.dot(expYV, pupil)\n t2 = np.dot(t1, expXU)\n\n if inverse:\n #print expYV.shape, pupil.shape, expXU.shape\n t2 = t2[::-1, ::-1]\n #else:\n #expYV = expYV.T.copy() # matrix npixY * npupY\n #t1 = np.dot(expYV, pupil) # matrix npixY * npupX? dot prod combined last axis of expYV and first axis of pupil.\n #t2 = np.dot(t1, expXU) # matrix npixY * npixX\n #print expYV.shape, pupil.shape, expXU.shape\n\n #print \"\"\n\n #return nlamD/(npup*npix) * t2 * dx * dy\n # normalization here is almost certainly wrong:\n norm_coeff = np.sqrt( float( nlamDY* nlamDX) / (npupY*npupX*npixY*npixX))\n #mean_npup = np.sqrt(npupY**2+npupX**2)\n #mean_npix = np.sqrt(npixY**2+npixX**2)\n return norm_coeff * t2 \n\n\n# SYMMETRIC centering : PSF centered between 4 pixels\ndef DFT_symmetric(pupil, nlamD, npix, **kwargs):\n \"\"\"\n Compute a \"SYMMETRIC\" matrix fourier transform. \n This means that the zero-order term is spread evenly\n between the center 4 pixels.\n\n Parameters\n ----------\n pupil\n pupil array (n by n)\n nlamD\n size of focal plane array, in units of lam/D\n (corresponds to 'm' in Soummer et al. 2007 4.2)\n npix\n number of pixels per side side of focal plane array\n (corresponds to 'N_B' in Soummer et al. 2007 4.2)\n\n\n \"\"\"\n\n\n\n npup = pupil.shape[0]\n\n du = nlamD / float(npix)\n dv = nlamD / float(npix)\n\n dx = 1.0/float(npup)\n dy = 1.0/float(npup)\n\n Xs = (np.arange(npup) - float(npup)/2.0 + 0.5) * dx\n Ys = (np.arange(npup) - float(npup)/2.0 + 0.5) * dy\n\n Us = (np.arange(npix) - float(npix)/2.0 + 0.5) * du\n Vs = (np.arange(npix) - float(npix)/2.0 + 0.5) * dv\n\n XU = np.outer(Xs, Us)\n YV = np.outer(Ys, Vs)\n\n\n expXU = np.exp(-2.0 * np.pi * 1j * XU)\n expYV = np.exp(-2.0 * np.pi * 1j * YV)\n expXU = expXU.T.copy()\n\n t1 = np.dot(expXU, pupil)\n t2 = np.dot(t1, expYV)\n #print \"\"\n #print dx, dy, du, dv\n #print \"\"\n\n\n #return t2 * dx * dy\n return float(nlamD)/(npup*npix) * t2 \n\n## --- OBSOLETED BY DFT_adjustible_rect just below ----\n## \n## # ADJUSTIBLE centering: PSF centered on array regardless of parity\n## def DFT_adjustible(pupil, nlamD, npix, offset=(0.0,0.0), inverse=False, **kwargs):\n## \"\"\"\n## Compute an adjustible-center matrix fourier transform. \n## \n## For an output array with ODD size n,\n## the PSF center will be at the center of pixel (n-1)/2\n## \n## For an output array with EVEN size n, \n## the PSF center will be in the corner between pixel (n/2-1,n/2-1) and (n/2,n/2)\n## \n## Those coordinates all assume Python/IDL style pixel coordinates running from\n## (0,0) up to (n-1, n-1). \n## \n## Parameters\n## ----------\n## pupil : array\n## pupil array (n by n)\n## nlamD : float or tuple\n## size of focal plane array, in units of lam/D\n## (corresponds to 'm' in Soummer et al. 2007 4.2)\n## npix : float or tuple\n## number of pixels per side side of focal plane array\n## (corresponds to 'N_B' in Soummer et al. 2007 4.2)\n## offset: tuple\n## an offset in pixels relative to the above\n## \n## \"\"\"\n## \n## \n## npup = pupil.shape[0]\n## \n## du = nlamD / float(npix)\n## dv = nlamD / float(npix)\n## \n## dx = 1.0/float(npup)\n## dy = 1.0/float(npup)\n## \n## Xs = (np.arange(npup) - float(npup)/2.0 - offset[1] + 0.5) * dx\n## Ys = (np.arange(npup) - float(npup)/2.0 - offset[0] + 0.5) * dy\n## \n## Us = (np.arange(npix) - float(npix)/2.0 - offset[1] + 0.5) * du\n## Vs = (np.arange(npix) - float(npix)/2.0 - offset[0] + 0.5) * dv\n## \n## XU = np.outer(Xs, Us)\n## YV = np.outer(Ys, Vs)\n## \n## \n## expXU = np.exp(-2.0 * np.pi * 1j * XU)\n## expYV = np.exp(-2.0 * np.pi * 1j * YV)\n## expXU = expXU.T.copy()\n## \n## t1 = np.dot(expXU, pupil)\n## t2 = np.dot(t1, expYV)\n## \n## #return t2 * dx * dy\n## return float(nlamD)/(npup*npix) * t2 \n## \n\n# ADJUSTIBLE centering:PSF centered on array regardless of parity, with rectangular pupils allowed\ndef DFT_adjustible_rect(pupil, nlamD, npix, offset=(0.0,0.0), inverse=False, **kwargs):\n \"\"\"\n Compute an adjustible-center matrix fourier transform. \n\n For an output array with ODD size n,\n the PSF center will be at the center of pixel (n-1)/2\n \n For an output array with EVEN size n, \n the PSF center will be in the corner between pixel (n/2-1,n/2-1) and (n/2,n/2)\n\n Those coordinates all assume Python/IDL style pixel coordinates running from\n (0,0) up to (n-1, n-1). \n\n\n This version supports rectangular, non-square arrays,\n in which case nlamD and npix should be 2-element\n tuples or lists, using the usual Pythonic order (Y,X)\n\n\n\n Parameters\n ----------\n pupil : array\n pupil array (n by n)\n nlamD : float or tuple\n size of focal plane array, in units of lam/D\n (corresponds to 'm' in Soummer et al. 2007 4.2)\n npix : float or tuple\n number of pixels per side side of focal plane array\n (corresponds to 'N_B' in Soummer et al. 2007 4.2)\n offset: tuple\n an offset in pixels relative to the above\n\n \"\"\"\n\n\n npupY, npupX = pupil.shape[0:2]\n\n if np.isscalar(npix): \n npixY, npixX = npix, npix\n else:\n npixY, npixX = npix[0:2] \n\n if np.isscalar(nlamD): \n nlamDY, nlamDX = nlamD, nlamD\n else:\n nlamDY, nlamDX = nlamD[0:2]\n\n\n if inverse:\n dX = nlamDX / float(npupX)\n dY = nlamDY / float(npupY)\n dU = 1.0/float(npixY)\n dV = 1.0/float(npixX)\n else:\n dU = nlamDX / float(npixX)\n dV = nlamDX / float(npixX)\n dX = 1.0/float(npupX)\n dY = 1.0/float(npupY)\n\n Xs = (np.arange(npupX) - float(npupX)/2.0 - offset[1] + 0.5) * dX\n Ys = (np.arange(npupY) - float(npupY)/2.0 - offset[0] + 0.5) * dY\n\n Us = (np.arange(npixX) - float(npixX)/2.0 - offset[1] + 0.5) * dU\n Vs = (np.arange(npixY) - float(npixY)/2.0 - offset[0] + 0.5) * dV\n\n YV = np.outer(Ys, Vs)\n XU = np.outer(Xs, Us)\n\n\n expXU = np.exp(-2.0 * np.pi * 1j * XU)\n expYV = np.exp(-2.0 * np.pi * 1j * YV)\n\n expYV = expYV.T.copy()\n t1 = np.dot(expYV, pupil)\n t2 = np.dot(t1, expXU)\n\n if inverse:\n #print expYV.shape, pupil.shape, expXU.shape\n t2 = t2[::-1, ::-1]\n\n norm_coeff = np.sqrt( float( nlamDY* nlamDX) / (npupY*npupX*npixY*npixX))\n return norm_coeff * t2 \n\n# back compatibility aliases for older/more confusing terminology: \n## SFT1 = DFT_fftstyle \n## SFT1rect = DFT_fftstyle_rect \n## SFT2 = DFT_symmetric\n## SFT3 = DFT_adjustible\n## SFT3rect = DFT_adjustible_rect\n\n\n\nclass MatrixFourierTransform:\n \"\"\"Implements a discrete matrix Fourier transform for optical \n propagation, following the algorithms discussed in \n Soummer et al. 2007 JOSA 15 24\n\n Parameters\n ----------\n centering : string\n Either 'SYMMETRIC', 'FFTSTYLE', or 'ADJUSTIBLE'. \n Sets whether the DFT result is centered at pixel n/2+1 (FFTSTYLE) \n or on the crosshairs between the central pixels (SYMMETRIC),\n or exactly centered in the array no matter what (ADJUSTIBLE). \n Default is FFTSTYLE. \n\n\n Example\n -------\n mft = MatrixFourierTransform()\n mft.perform(pupilArray, focalplane_size, focalplane_npix)\n\n\n History\n -------\n Code by Sivaramakrishnan based on Soummer et al.\n 2010-01 Documentation updated by Perrin\n 2013-01 'choice' keyword renamed to 'centering' for clarity. 'choice' is retained\n as an option for back compatibility, however it is deprecated.\n\n \"\"\"\n\n def __init__(self, centering=\"FFTSTYLE\", verbose=False):\n\n self.verbose=verbose\n\n self._dft_fns = {'FFTSTYLE':DFT_fftstyle, \"SYMMETRIC\":DFT_symmetric, \"ADJUSTIBLE\":DFT_adjustible_rect, 'FFTRECT': DFT_fftstyle_rect}\n #self.centering_methods= (\"FFTSTYLE\", \"SYMMETRIC\", \"ADJUSTIBLE\", 'FFTRECT')\n centering = centering.upper()\n if centering not in self._dft_fns.keys():\n raise ValueError(\"Error: centering method must be one of [%s]\" % ', '.join(self._dft_fns.keys()))\n self.centering = centering\n\n\n if self.verbose:\n _log.info(\"This instance of MatrixFourierTransform is a(n) {0} set-up calling {1} \".format(centering, self._dft_fns[centering]))\n _log.debug(\"MatrixDFT initialized using centering type = {0}\".format(centering))\n\n def perform(self, pupil, nlamD, npix, **kwargs):\n \"\"\" Forward Fourier Transform \n\n Parameters\n --------------\n pupil : 2D ndarray\n Real or complex valued 2D array representing the input image to transform\n nlamD : float\n Size of desired output region in lambda/D units, assuming that the pupil fills the\n input array. I.e. this is in units of the spatial frequency that is just Nyquist sampled\n by the input array\n npix : int\n Number of pixels to use for representing across that region lambda/D units in size.\n\n Returns a 2D complex valued Fourier transform array.\n\n \"\"\"\n\n dft_fn_to_call = self._dft_fns[self.centering]\n _log.debug(\"MatrixDFT mode {0} calling {1}\".format( self.centering, str(dft_fn_to_call)))\n\n if not np.isscalar(nlamD) or not np.isscalar(npix):\n if self.centering == 'FFTSTYLE' or self.centering=='SYMMETRIC':\n raise RuntimeError('The selected MatrixDFT centering mode, {0}, does not support rectangular arrays.'.format(self.centering))\n return dft_fn_to_call(pupil, nlamD, npix, **kwargs)\n\n\n def inverse(self, image, nlamD, npix):\n \"\"\" Inverse Fourier Transform \n\n Parameters\n --------------\n image : 2D ndarray\n Real or complex valued 2D array representing the input image to transform, which\n presumably is the result of some previous forward transform.\n nlamD : float\n Size of desired output region in lambda/D units, assuming that the pupil fills the\n input array. I.e. this is in units of the spatial frequency that is just Nyquist sampled\n by the input array\n npix : int\n Number of pixels to use for representing across that region lambda/D units in size.\n\n Returns a 2D complex valued Fourier transform array.\n\n\n \"\"\"\n return self.perform(image, nlamD, npix, inverse=True)\n\n# This function is used nowhere in poppy or webbpsf, and it really\n# does not do much of anything useful - so let's delete it. Aug 2014.\n# def performFITS(hdulist, focalplane_size, focalplane_npix):\n# \"\"\" Perform an MFT, and return the result as a fits.HDUlist \"\"\"\n# newHDUlist = hdulist.copy()\n# newim = self.perform(hdulist[0].data, focalplane_size, focalplane_npix)\n#\n# newHDUlist[0].data = newim\n# #TODO fits header keyword updates\n#\n# return newHDUlist\n\n## SlowFourierTransform = MatrixFourierTransform # back compatible name\n\n#---------------------------------------------------------------------\n# Test functions \n# are now in tests/test_matrixDFT.py\n\n","sub_path":"poppy/matrixDFT.py","file_name":"matrixDFT.py","file_ext":"py","file_size_in_byte":19825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"414335583","text":"#Venkata Gogineni\n#Student ID- 0788305\n#Cryptography - Prof Kinber\n#Lab 1 Assignment\n\nfrom Crypto.Cipher import AES\nimport base64\nimport os\n\nSIZE_BLOCK = 32\n#key = b'D7C39820ED431E98A85C5590CBA23626'\nkey = os.urandom(SIZE_BLOCK)\n#key = b'1CC99486DF2819EFC31EC26D7F05D4DC8D801762C4E83A6019DA3A0A3034F350'\n#message = 'This is my super secret message and I call it a sweet little one'\ncipher = AES.new(key)\n\nmessage = input(\"Please enter the secret message: \")\n\nprint (\"The secret message is: \"), message\n\ndef padding(text):\n return text + ((SIZE_BLOCK-len(text)%SIZE_BLOCK) * '{')\n\ndef encrypt(plaintext):\n global cipher\n return cipher.encrypt(padding(plaintext))\n\nencrypted = encrypt(message)\nprint(encrypted)\n\nfile = open('C:/Python27/encryptedintoFile.txt', 'wb')\nfile.write(encrypted)\nfile.close()\n\nciphertext = open('C:/Python27/encryptedintoFile.txt', 'rb').readlines()\nprint (\"Ciphertext from file is: \", ciphertext)\n\ndef decrypt(ciphertext):\n global cipher\n dec = cipher.decrypt(ciphertext).decode('utf-8')\n l = dec.count('{')\n return dec[:len(dec)-l]\n\n\n\ndecrypted = decrypt(encrypted)\n\nprint (\"Decrypted is: \",decrypted)","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"457706969","text":"from bs4 import BeautifulSoup\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport pandas as pd\nimport numpy as np\nimport requests\nimport tqdm\nimport re\nfrom tqdm import tqdm\nfrom notify_run import Notify\nimport csv\nfrom csv import writer\n\nnotify = Notify()\nprint(notify.register())\n\n# set up retry with backoff bc of maxpreps limiting\nsession = requests.Session()\nretry = Retry(connect=10,total=10, backoff_factor=0.5)\nadapter = HTTPAdapter(max_retries=retry)\nsession.mount('http://', adapter)\nsession.mount('https://', adapter)\n# now just use session.get instead of requests.get\n\nurl_names = 'https://www.maxpreps.com/rankings/baseball-spring-18/{}/national.htm'\nurl_scores = 'https://www.maxpreps.com/high-schools/{})/baseball-spring-18/schedule.htm'\nurl_contact_info = 'https://www.maxpreps.com/high-schools/{})/home.htm'\n#state_set = ['california','colorado','illinois','iowa','kentucky','new-hampshire','new-jersey','new-mexico','south-dakota','tennessee']\nschool_name=[]\n\ndef append_list_as_row(file_name, list_of_elem):\n # Open file in append mode\n with open(file_name, 'a', newline='') as write_obj:\n # Create a writer object from csv module\n csv_writer = writer(write_obj)\n # Add contents of list as last row in the csv file\n csv_writer.writerow(list_of_elem)\n write_obj.close()\n\n#518 pages\nfor x in tqdm(range(0,100,1)):\n names = url_names.format(x)\n r = session.get(names)\n sopa = BeautifulSoup(r.text,'html.parser')\n for item in sopa.find_all('tr'):\n try:\n school_name.append(item.find('th', attrs={'class':'school','scope':'row'}))\n except:\n school_name.append(np.nan)\nnew_list = []\nfor i in school_name:\n i = str(i)\n count = 0\n for char in i:\n if char == '/':\n count +=1\n elif count == 2:\n new_list.append(char)\nbig_string = ''.join(new_list)\nmy_keys = big_string.split(')')\n\nnotify.send('I am about to run the main scraper')\n\n#Scraper for Scores - need to parse through the url for each of the schools....\nfor name in tqdm(my_keys):\n scores = url_scores.format(name)\n r = session.get(scores)\n soup = BeautifulSoup(r.text,'html.parser')\n # print(scores)\n try:\n team_1=(soup.find('h1', attrs={'class':'Heading__StyledHeading-sc-1ape2tl-0 kYQvou f28_heavy'}).text)\n team_1 = team_1[0:team_1.find(\"Baseba\")-1]\n # team_1= name[0:name.find('(')-1] # this works ok, not capitalized though\n # team_1 = name\n # bf = item.find('h1', attrs={'class': 'ckzGWy'})\n # print(\"got a team 1\")\n except:\n team_1=(np.nan)\n #Start to collect the scores:\n try:\n contact = url_contact_info.format(name)\n r = session.get(contact)\n # print(\"going to find address at \", contact)\n soup_2 = BeautifulSoup(r.text,'html.parser')\n for item_2 in soup_2.find_all('dl', attrs={'class':'SchoolInfo__StyledData-sc-804m01-2 yPrMn'}):\n try:\n team_1_address=(item_2.find('dd', attrs={'class':'Text__StyledText-g7xgdj-0 eCGytY f16_tall'}).text)\n except:\n team_1_address=('nan,nan,nan,nan')\n except:\n team_1_address=('nan,nan,nan,nan')\n # continue \n for item in soup.find_all('tr'):\n #mascot,score,team_1, away_team,date_of_contest,result,place_played,time_of_contest,zip_code,city,state, team_2_city, team_2_state, address,location,gender,sport = ([], )*19\n # address=('nan,nan,nan,nan')\n try:\n score = (item.find('span', attrs={'class':'Text__StyledText-g7xgdj-0 ipvVIk'}).text)\n except:\n score = ('nan-nan')\n # TODO Assign the scores to the teams Post processing properly\n try:\n # here is wherer we need to strip the href out of the tag to get away team city\n element = item.find('a', attrs={'class':'StyledAnchor-sc-14cqspo-0 fAexHO'})\n team_2=(element.text)\n #href_tag = element['href']\n # print(element['href'])\n away_location_pair = re.search('\\((.*)\\)', element['href']) # look for text inside parens\n # print(away_location_pair.group(1).split(','))\n team_2_city=(away_location_pair.group(1).split(',')[0])\n team_2_state=(away_location_pair.group(1).split(',')[1]).upper()\n except:\n team_2=(np.nan)\n team_2_city=(np.nan)\n team_2_state=(np.nan)\n try:\n # print(item)\n result=(item.find('span', attrs={'class':'Text__StyledText-g7xgdj-0 byvOZr'}).text) # win stylization\n except: # the loss stylization is of class type sc-eCssSg dyMwZa. if they don't have win, it's a loss\n try:\n result=(item.find('span', attrs={'class':'Text__StyledText-g7xgdj-0 ddInom'}).text) # loss stylization\n except:\n try:\n result=(item.find('span', attrs={'class':'Text__StyledText-g7xgdj-0 jboaTf'}).text) # actual tie stylization\n except:\n result=(\"NoScoreReported\")\n try:\n date_of_contest=(item.find('div', attrs={'class':'Text__StyledText-g7xgdj-0 eHnusR f16_bold_tall'}).text)\n except:\n date_of_contest=(np.nan)\n try:\n place_played=(item.find('div', attrs={'class':'Text__StyledText-g7xgdj-0 itManz f14_tall'}).text)\n except:\n place_played=(np.nan)\n try:\n time_of_contest=(item.find('div', attrs={'class':'Text__StyledText-g7xgdj-0 eHnusR f14_tall'}).text)\n except:\n time_of_contest=(np.nan)\n # try:\n # mascot=(item.find('span', attrs={'class','Text__StyledText-jknly0-0 StyledSchoolHeader__StyledSchoolMascotName-sc-1ps5it5-2 kjABeh jvGvem'}).text)\n # except:\n # mascot=(np.nan)\n # try:\n # for x in range(1):\n # contact = url_contact_info.format(name)\n # r = session.get(contact)\n # soup_2 = BeautifulSoup(r.text,'html.parser')\n # for item_2 in soup_2.find_all('dl', attrs={'class':'SchoolInfo__StyledData-sc-804m01-2 yPrMn'}):\n # try:\n # address=(item_2.find('dd', attrs={'class':'Text__StyledText-g7xgdj-0 cjPYhL'}).text)\n # except:\n # address=('nan,nan,nan,nan')\n # except:\n # address=('nan,nan,nan,nan')\n # # continue \n\n #try:\n # # grab the anchor that links to the box score\n # element = item.find(\"a\", attrs={'class':'fKwvDC'})\n # href_tag = element['href']\n # # print(\"element: \" , element)\n # # print(\"going to get url: \", href_tag)\n # box_score_r = session.get(href_tag)\n # box_score_soup = BeautifulSoup(box_score_r.text, 'html.parser')\n # team_alpha = box_score_soup.find('tr', attrs={'class':'first'})\n # team_beta = box_score_soup.find('tr', attrs={'class':'last alternate'})\n\n # # alpha_scores = [np.nan, np.nan, np.nan, np.nan, np.nan]\n # alpha_scores = []\n # # alpha_score_idx = 0\n # # this gets all the td elements\n # for score_a in team_alpha.find_all('td'):\n # # alpha_scores[alpha_score_idx] = int(score_a.text)\n # # sometimes the text will be a '-' bc it's not available. the int conversion will fail\n # # and the score list will be nan. \n # alpha_scores.append(int(score_a.text))\n # # alpha_score_idx = alpha_score_idx + 1\n # # but it also includes the number of games won. get rid of that\n # # alpha_game_wins = alpha_scores[alpha_score_idx-1]\n # # alpha_game_wins = alpha_scores[len(alpha_scores)-1]\n # alpha_game_wins = alpha_scores.pop()\n # # alpha_scores[alpha_score_idx] = np.nan\n # # print(alpha_scores)\n # # print(alpha_game_wins)\n\n # # beta_scores = [np.nan, np.nan, np.nan, np.nan, np.nan]\n # beta_scores = []\n # # beta_score_idx = 0\n # # this gets all the td elements\n # for score_a in team_beta.find_all('td'):\n # # beta_scores[beta_score_idx] = int(score_a.text)\n # beta_scores.append(int(score_a.text))\n # # beta_score_idx = beta_score_idx + 1\n # # but it also includes the number of games won. get rid of that\n # # beta_game_wins = beta_scores[beta_score_idx-1]\n # # beta_game_wins = beta_scores[len(beta_scores)-1]\n # beta_game_wins = beta_scores.pop()\n # # beta_scores[beta_score_idx] = np.nan\n # # print(beta_scores)\n # # print(beta_game_wins)\n\n # # # this gets all the td elements\n # # beta_scores = [np.nan, np.nan, np.nan, np.nan, np.nan]\n # # beta_score_idx = 0\n # # for score_a in team_beta.find_all('td'):\n # # beta_scores[beta_score_idx] = int(score_a.text)\n # # beta_score_idx = beta_score_idx + 1\n # # # but it also includes the number of games won. get rid of that\n # # beta_game_wins = beta_scores[beta_score_idx-1]\n # # beta_scores[beta_score_idx] = np.nan\n\n # if(beta_game_wins > alpha_game_wins):\n # # here team_beta is the winner\n # if(result == 'W'):\n # # team beta is team 1\n # team_2_score_list = alpha_scores\n # team_1_score_list = beta_scores\n # team_1_games_won = beta_game_wins\n # team_2_games_won = alpha_game_wins\n # elif(result == 'L'):\n # # team beta is team 2\n # team_1_score_list = alpha_scores\n # team_2_score_list = beta_scores\n # team_2_games_won = beta_game_wins\n # team_1_games_won = alpha_game_wins\n # else:\n # print('Result bad')\n # elif(beta_game_wins < alpha_game_wins):\n # # here team_beta is the loser\n # if(result == 'W'):\n # # team beta is team 2\n # team_1_score_list = alpha_scores\n # team_2_score_list = beta_scores\n # team_2_games_won = beta_game_wins\n # team_1_games_won = alpha_game_wins\n # elif(result == 'L'):\n # # team beta is team 1\n # team_2_score_list = alpha_scores\n # team_1_score_list = beta_scores\n # team_1_games_won = beta_game_wins\n # team_2_games_won = alpha_game_wins\n # else:\n # print('Result bad')\n # team_2_score_list = np.nan\n # team_1_score_list = np.nan\n # team_1_games_won = np.nan\n # team_2_games_won = np.nan\n\n # else:\n # print(\"tie game, team_a: \", alpha_game_wins, \" beta: \" , beta_game_wins)\n # # whose scores are whose? does it matter since they're the same game wins? could search for other data and match lowercase string names\n # team_1_score_list = alpha_scores\n # team_2_score_list = beta_scores\n # team_2_games_won = beta_game_wins\n # team_1_games_won = alpha_game_wins\n\n # # print(\"team_alpha: \", alpha_scores, \"\\nteam_beta: \", beta_scores)\n # # in the soup we are looking for which has children , etc for however many games\n # # then we look for a which has the same kinds of children. yoink these scores outta there!\n\n # # print(element['href'])\n #except:\n # # print('it no worky')\n # alpha_scores = np.nan\n # beta_scores = np.nan\n # team_1_score_list = np.nan\n # team_2_score_list = np.nan\n # team_1_games_won = np.nan\n # team_2_games_won = np.nan\n # #append np.nan to all the individual_game_scores\n\n #at this point we need to follow the 'box score' link and scrape the game scores for each set. instead of just 3-0, we need to find that team 1 scored [25, 25, 25] points in the sets, team 2 score [8, 19, 11]\n # row = [score, team_1, team_2, date_of_contest, result, place_played, time_of_contest, team_2_city, team_2_state, address]\n # append_list_as_row('volleyball_1.csv', row)\n # print(str(score))\n # print(\"team1: \", str(team_1)) # all nan\n # print(\"team1 games: \", str(team_1_games_won))\n # print(\"team1 list \", str(team_1_score_list))\n # print(\"team2: \", str(team_2))\n # print(\"team2 games: \", str(team_2_games_won))\n # print(\"team2 list \", str(team_2_score_list))\n # print(\"date: \",str(date_of_contest))\n # print(\"team1 result: \",str(result))\n # print(\"place_played: \",str(place_played))\n # print(\"time: \",str(time_of_contest))\n # print(\"team 2 city: \", str(team_2_city))\n # print(\"team 2 state: \", str(team_2_state))\n # print(\"team 1 addr: \", str(address))\n # print(\"=======\")\n\n row = [team_1, team_2, score, date_of_contest, result, place_played, time_of_contest, team_2_city, team_2_state, team_1_address]\n append_list_as_row('boys_baseball_1_100.csv', row)\n # with open('volleyball_1.csv', 'a') as f_object:\n # writer_object = writer(f_object)\n # # zip, city, state, home/away(location)\n # row = [score, team_1, team_2, date_of_contest, result, place_played, time_of_contest, team_2_city, team_2_state, address]\n # append_list_as_row('volleyball_1.csv', row)\n # writer_object.writerow(str(score))\n # writer_object.writerow(str(team_1))\n # writer_object.writerow(str(team_2))\n # writer_object.writerow(str(date_of_contest))\n # writer_object.writerow(str(result))\n # writer_object.writerow(str(place_played))\n # writer_object.writerow(str(time_of_contest))\n # writer_object.writerow(str(team_2_city))\n # writer_object.writerow(str(team_2_state))\n # writer_object.writerow(str(address))\n # f_object.close()\nnotify.send('I am finished - come check on me')\n","sub_path":"baseball/boys_baseball.py","file_name":"boys_baseball.py","file_ext":"py","file_size_in_byte":14632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"575409380","text":"from pyanno.kappa import *\r\nfrom pyanno.multinom import *\r\nfrom pyanno.util import *\r\n\r\nimport unittest\r\n\r\nclass TestUtil(unittest.TestCase):\r\n def test_vec_copy(self):\r\n c = []\r\n d = []\r\n vec_copy(c,d)\r\n self.assertEquals(c,d)\r\n a = [1,2,3]\r\n b = [4,5,6]\r\n vec_copy(a,b)\r\n self.assertEquals(a,b)\r\n def test_fill_vec(self):\r\n a = []\r\n fill_vec(a,0)\r\n self.assertEquals([],a)\r\n b = [1]\r\n fill_vec(b,3)\r\n self.assertEquals([3],b)\r\n c = [1,2,3]\r\n fill_vec(c,5)\r\n self.assertEquals([5,5,5],c)\r\n def test_fill_mat(self):\r\n a = [[]]\r\n fill_mat(a,0)\r\n self.assertEquals([[]],a)\r\n b = [[1,2,3]]\r\n fill_mat(b,5)\r\n self.assertEquals([[5,5,5]],b)\r\n c = [[1,2],[3,4]]\r\n fill_mat(c,6)\r\n self.assertEquals([[6,6],[6,6]],c)\r\n def test_fill_tens(self):\r\n a = [[[]]]\r\n fill_tens(a,0)\r\n self.assertEquals([[[]]],a)\r\n b = [[[1,2],[3,4]],[[5,6],[7,8]]]\r\n fill_tens(b,10)\r\n self.assertEquals([[[10,10],[10,10]],[[10,10],[10,10]]],b)\r\n def test_alloc_vec(self):\r\n a = alloc_vec(0)\r\n self.assertEquals([],a)\r\n b = alloc_vec(1)\r\n self.assertEquals([0.0],b)\r\n c = alloc_vec(2,9.0)\r\n self.assertEquals([9.0,9.0],c)\r\n def test_alloc_mat(self):\r\n a = alloc_mat(1,0)\r\n self.assertEquals([[]],a)\r\n b = alloc_mat(1,1,3.0)\r\n self.assertEquals([[3.0]],b)\r\n c = alloc_mat(2,3,5.0)\r\n self.assertEquals([[5.0,5.0,5.0],[5.0,5.0,5.0]],c)\r\n def test_alloc_tens(self):\r\n a = alloc_tens(1,1,0)\r\n self.assertEquals([[[]]],a)\r\n b = alloc_tens(1,1,1)\r\n self.assertEquals([[[0.0]]],b)\r\n c = alloc_tens(2,3,4,9)\r\n self.assertEquals([[[9,9,9,9],[9,9,9,9],[9,9,9,9]],\r\n [[9,9,9,9],[9,9,9,9],[9,9,9,9]]],c)\r\n def test_alloc_tens4(self):\r\n a = alloc_tens4(1,1,1,0)\r\n self.assertEquals([[[[]]]],a)\r\n b = alloc_tens4(1,1,1,1)\r\n self.assertEquals([[[[0.0]]]],b)\r\n c = alloc_tens4(1,2,3,4,9)\r\n self.assertEquals([[[[9,9,9,9],[9,9,9,9],[9,9,9,9]],\r\n [[9,9,9,9],[9,9,9,9],[9,9,9,9]]]],c)\r\n def test_vec_sum(self):\r\n self.assertEquals(0,vec_sum([]))\r\n self.assertEquals(1,vec_sum([1]))\r\n self.assertEquals(3,vec_sum([1,2]))\r\n def test_mat_sum(self):\r\n self.assertEquals(0,mat_sum([[]]))\r\n self.assertEquals(1,mat_sum([[1]]))\r\n self.assertEquals(3,mat_sum([[1,2]]))\r\n self.assertEquals(21,mat_sum([[1,2,3],[4,5,6]]))\r\n def test_prob_norm(self):\r\n theta = [0.2]\r\n prob_norm(theta)\r\n self.assert_prob_normed(theta)\r\n\r\n\r\n def assert_prob_normed(self,theta):\r\n self.assert_(len(theta) > 0)\r\n for theta_i in theta:\r\n self.assert_(theta_i >= 0.0)\r\n self.assert_(theta_i <= 1.0)\r\n self.assertAlmostEqual(1.0,vec_sum(theta),3)\r\n\r\nclass TestKappa(unittest.TestCase):\r\n def test_agr(self):\r\n cm1 = [[1]]\r\n self.assertEquals(1.0,agr(cm1))\r\n cm2 = [[41,3],[9,47]]\r\n self.assertAlmostEqual((41.0 + 47.0)/100.0,agr(cm2))\r\n cm3 = [[44,6],[6,44]]\r\n self.assertAlmostEqual(0.88,agr(cm3))\r\n def test_s(self):\r\n cm1 = [[44,6],[6,44]]\r\n self.assertAlmostEqual((0.88-0.5)/(1.0-0.5),s(cm1))\r\n cm2 = [[44,6,0,0],[6,44,0,0],[0,0,0,0],[0,0,0,0]]\r\n self.assertAlmostEqual(0.84,s(cm2))\r\n self.assertAlmostEqual(0.88,agr(cm2))\r\n def test_pi(self):\r\n cm1 = [[44,6,0],[6,44,0],[0,0,0]]\r\n self.assertAlmostEqual(0.88,agr(cm1))\r\n self.assertAlmostEqual(0.82,s(cm1))\r\n self.assertAlmostEqual(0.76,pi(cm1))\r\n cm2 = [[77,1,2],[1,6,3],[2,3,5]]\r\n self.assertAlmostEqual(0.88,agr(cm2))\r\n self.assertAlmostEqual(0.82,s(cm2))\r\n self.assertAlmostEqual((0.88-0.66)/(1.0-0.66),pi(cm2))\r\n cm3 = [[990,5],[5,0]]\r\n self.assertAlmostEqual(0.99,agr(cm3))\r\n self.assertAlmostEqual(0.98,s(cm3))\r\n self.assertAlmostEqual((0.99-0.99005)/(1.0-0.99005),pi(cm3))\r\n def test_kappa(self):\r\n cm1 = [[8,1],\r\n [4,2]]\r\n ce = ((12.0*9.0) + (6.0*3.0))/(15.0*15.0)\r\n ag = 10.0/15.0\r\n k = (ag - ce)/(1.0 - ce)\r\n self.assertAlmostEqual(k,kappa(cm1))\r\n cm2 = [[7,5,0],\r\n [1,9,2],\r\n [0,8,4]]\r\n ce2 = (8.0*12.0 + 22.0*12.0 + 6.0*12.0)/(36.0*36.0)\r\n ag2 = 20.0/36.0\r\n k2 = (ag2 - ce2)/(1.0 - ce2)\r\n self.assertAlmostEqual(k2,kappa(cm2))\r\n def test_global_prevalence(self):\r\n item = [0,0]\r\n label = [0,1]\r\n theta_hat = global_prevalence(item,label)\r\n assertAlmostEqualLists(self,[0.5,0.5],theta_hat)\r\n item2 = [0,0,0, 1,1]\r\n label2 = [0,0,1, 1,2]\r\n theta_hat2 = global_prevalence(item2,label2)\r\n assertAlmostEqualLists(self,[4.0/12.0, 5.0/12.0, 3.0/12.0],theta_hat2)\r\n def test_K(self):\r\n item = [0,0,0]\r\n anno = [0,1,2]\r\n lab = [0,0,1]\r\n ag = 1.0/3.0\r\n ag_exp = (1.0*1.0)/(3.0*3.0) + (2.0*2.0)/(3.0*3.0)\r\n Ke = (ag - ag_exp)/(1.0 - ag_exp)\r\n self.assertAlmostEqual(Ke,K(item,anno,lab))\r\n def test_K_2(self):\r\n item = [0,0,0, 1,1, 2]\r\n anno = [0,1,2, 0,1, 0]\r\n lab = [0,0,1, 1,1, 0]\r\n ag = 2.0/4.0\r\n ag_exp = (5.0/9.0)**2 + (4.0/9.0)**2\r\n Ke = (ag - ag_exp)/(1.0 - ag_exp)\r\n self.assertAlmostEqual(Ke,K(item,anno,lab))\r\n def test_K_3(self):\r\n item = [0,0,0, 1,1, 2,2,2,2,2,2,2]\r\n anno = [0,1,2, 0,1, 0,1,2,3,4,5,6]\r\n lab = [0,0,1, 1,1, 0,1,2,1,0,1,2]\r\n ag = (1.0 + 1.0 + 1.0 + 3.0 + 1.0)/(3.0 + 1.0 + 21.0)\r\n ag_exp = (20.0/63.0)**2 + (37.0/63.0)**2 + (6.0/63.0)**2\r\n Ke = (ag - ag_exp)/(1.0 - ag_exp)\r\n self.assertAlmostEqual(Ke,K(item,anno,lab))\r\n def test_chance_adj_agr(self):\r\n self.assertAlmostEqual((0.9-0.5)/(1.0-0.5),chance_adj_agr(0.9,0.5))\r\n\r\nclass TestMultinom(unittest.TestCase):\r\n def testbase2(self):\r\n self.assertEquals(2,2)\r\n\r\ndef assertAlmostEqualLists(testcase,x,y):\r\n testcase.assertEquals(len(x),len(y))\r\n n = 0\r\n while n < len(x):\r\n testcase.assertAlmostEqual(x[n],y[n])\r\n n += 1\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"pyanno/trunk/unit_test.py","file_name":"unit_test.py","file_ext":"py","file_size_in_byte":6464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"89199959","text":"from . import plugin\nfrom googleapiclient.discovery import build\nfrom urllib.parse import quote\n\nimport json\nimport requests\n\nclass AutoScooglePlugin(plugin.NoBotPlugin):\n def __google_search(self, search_term):\n service = build(\"customsearch\", \"v1\", developerKey=self._config.get('AUTOSCOOGLE_API_KEY'))\n res = service.cse().list(q=search_term, cx=self._config.get('AUTOSCOOGLE_CSE_ID'), num=1).execute()\n return res['items'][0]\n\n def receive(self, request):\n if super().receive(request) is False:\n return False\n responses = []\n user = request['user']\n subject = None\n text = request.get('text', '').lower()\n for trigger in self._config['AUTOSCOOGLE_TRIGGERS']:\n if trigger in text.lower():\n if trigger.startswith(\"what\"):\n subject = text\n elif trigger.startswith(\"who\"):\n subject = text.replace(trigger, \"\")\n else:\n subject = \"what is \" + text.replace(trigger, \"\")\n if \"?\" in subject:\n subject = subject.split(\"?\")[0]\n self._log.debug(f\"################## Subject is {subject}\")\n break\n if subject:\n result = self.__google_search(\n search_term=subject,\n )\n self._log.debug(json.dumps(result, indent=2))\n url = result.get('link', result.get('formattedUrl'))\n attachments = [\n {\n \"mrkdwn_in\": [\"text\"],\n \"text\": url,\n }\n ]\n if \"pagemap\" in result.keys():\n pagemap = result[\"pagemap\"]\n image_url = None\n if \"cse_thumbnail\" in pagemap.keys() and \"src\" in pagemap[\"cse_thumbnail\"][0].keys():\n image_url = pagemap[\"cse_thumbnail\"][0][\"src\"]\n elif \"cse_image\" in pagemap.keys() and \"src\" in pagemap[\"cse_image\"][0].keys():\n image_url = pagemap[\"cse_image\"][0][\"src\"]\n if image_url:\n attachments[0][\"image_url\"] = image_url\n if \"metatags\" in pagemap and \"og:title\" in pagemap[\"metatags\"][0].keys():\n attachments[0][\"title\"] = pagemap[\"metatags\"][0][\"og:title\"]\n elif result.get(\"title\"):\n attachments[0][\"title\"] = result[\"title\"]\n if url:\n responses.append(\n {\n 'channel': request['channel'],\n 'text': 'I Auto-Scoogled that for you:',\n 'attachments': attachments,\n }\n )\n return responses\n","sub_path":"plugins/autoscoogle.py","file_name":"autoscoogle.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"495012721","text":"#!/usr/bin/env python\n\n\"\"\"\nCopyright 2018 Marcus Hammar\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\nimport urllib\nimport logging\n\nfrom google.appengine.ext import ndb\n\nimport webapp2\n\nclass Device(ndb.Model):\n device_id = ndb.StringProperty()\n\nclass Value(ndb.Model):\n device_id = ndb.StringProperty()\n device_key = ndb.StringProperty()\n device_value = ndb.StringProperty()\n device_timestamp = ndb.DateTimeProperty(auto_now=True)\n\nclass Delete(webapp2.RequestHandler):\n\n def get(self):\n device_id = self.request.get('device','')\n\n if (device_id == ''):\n self.error(404)\n self.response.write('ERROR (Device should not be empty)')\n return\n\n q = Value.query(Value.device_id == device_id)\n for p in q:\n p.key.delete()\n\n q = Device.query(Device.device_id == device_id)\n for p in q:\n p.key.delete()\n\n self.response.write('OK')\n\nclass Add(webapp2.RequestHandler):\n\n def get(self):\n device_id = self.request.get('device','')\n\n if (device_id == ''):\n self.error(404)\n self.response.write('ERROR (Device should not be empty)')\n return\n\n q = Device.query(Device.device_id == device_id)\n for p in q:\n p.key.delete()\n\n device = Device()\n device.device_id = device_id\n device.put()\n self.response.write('OK')\n\nclass SetOrGet(webapp2.RequestHandler):\n\n def get(self):\n device_id = self.request.get('device','')\n device_key = self.request.get('key','')\n device_value = self.request.get('value','')\n\n logging.info('HTTPS: ' + self.request.environ['HTTPS'])\n\n q = Device.query(Device.device_id == device_id)\n if q.count() != 1:\n self.error(404)\n self.response.write('ERROR (Device not found)')\n return\n\n if (device_key == ''):\n self.error(404)\n self.response.write('ERROR (Key should not be empty)')\n return\n\n if (device_value == ''):\n q = Value.query(Value.device_id == device_id, Value.device_key == device_key)\n\n if q.iter().has_next():\n self.response.write(q.iter().next().device_value)\n else:\n self.error(404)\n self.response.write('ERROR (Key not found)')\n\n else:\n q = Device.query(Device.device_id == device_id)\n\n if q.count() != 0:\n\n q = Value.query(Value.device_id == device_id, Value.device_key == device_key)\n\n for p in q:\n p.key.delete()\n\n value = Value()\n value.device_id = self.request.get('device')\n value.device_key = self.request.get('key')\n value.device_value = self.request.get('value')\n value.put()\n self.response.write('OK')\n else:\n self.error(404)\n self.response.write('ERROR (Device missing)')\n\napp = webapp2.WSGIApplication([\n ('/', SetOrGet),\n ('/add/', Add),\n ('/delete/', Delete),\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"94616595","text":"import os \nimport shutil\ndef walk(path):\n if not os.path.exists(path):\n return -1\n for root,dirs,names in os.walk(path):\n for filename in names:\n # print filename\n shutil.copyfile(os.path.join(root,filename),'/home/lgy/download/NTU-RGBD/rgb_raw/all/'+filename) \nif __name__=='__main__':\n path = \"/home/lgy/workspace/rgb_lstm/data/train/\"\n walk(path)","sub_path":"data/others/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177130660","text":"from django.urls import path,include\nfrom . import views\nfrom django.views.generic import TemplateView\n\nurlpatterns=[\n #front page,menu\n path('',views.index,name=\"index\"),\n #views product by category\n path('category//',views.category,name=\"cat\"),\n path('signup/',views.signup,name='signup'),\n path('profile/',views.profile,name=\"profile\"),\n path('updateprofile/',views.updateprofile,name=\"updateprofile\"),\n\n\n path('cart/',views.cart,name=\"cart\"),\n path('shipping/',views.shipping,name=\"shipping\"),\n\n path('term&condition/',TemplateView.as_view(template_name=\"termCondition.html\")),\n path('policy/',TemplateView.as_view(template_name=\"policy.html\")),\n\n path('checkout/',views.checkout,name=\"checkout\"),\n\n path('paymentSuccess/',views.paymentSuccess,name=\"paymentSuccess\"),\n path('success/',TemplateView.as_view(template_name=\"payment/success.html\")),\n\n path('paymentFailer/',views.paymentFailer,name=\"paymentFailer\"),\n\n\n path('trackorder/',views.trackorder,name=\"trackorder\"),\n\n ]","sub_path":"ecomm/shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"172400205","text":"'''\nCreated on 12.01.2016\n\n@author: Yingxiong\n'''\n\nfrom ibvpy.dots.dots_grid_eval import DOTSGridEval\nfrom ibvpy.fets.fets_eval import FETSEval, IFETSEval\nfrom traits.api import Int, Array, \\\n Property, cached_property, Float, List, provides\n\nimport numpy as np\nimport sympy as sp\nimport traits.api as tr\n\n\nr_ = sp.symbols('r')\n\n#=================================================\n# 8 nodes isoparametric volume element (3D)\n#=================================================\n# generate shape functions with sympy\nxi_1 = sp.symbols('xi_1')\nxi_2 = sp.symbols('xi_2')\nxi_3 = sp.symbols('xi_3')\n\n\n#=========================================================================\n# Finite element specification\n#=========================================================================\n\nN_xi_i = sp.Matrix([0.5 - xi_1 / 2., 0.5 + xi_1 / 2.], dtype=np.float_)\n\ndN_xi_ir = sp.Matrix([[-1. / 2], [1. / 2]], dtype=np.float_)\n\n\n@provides(IFETSEval)\nclass FETS1D52ULRHFatigueOld(FETSEval):\n\n '''\n Fe Bar 2 nodes, deformation\n '''\n\n vtk_expand_operator = tr.Array(np.float_, value=[[1, 0, 0]])\n\n debug_on = True\n\n# A_m = Float(100 * 8 - 9 * 1.85, desc='matrix area [mm2]')\n# A_f = Float(9 * 1.85, desc='reinforcement area [mm2]')\n# P_b = Float(9 * np.sqrt(np.pi * 4 * 1.85),\n# desc='perimeter of the bond interface [mm]')\n\n A_m = Float(1)\n A_f = Float(1)\n P_b = Float(1)\n\n # Dimensional mapping\n dim_slice = slice(0, 1)\n\n n_nodal_dofs = Int(2)\n\n dof_r = Array(value=[[-1], [1]])\n geo_r = Array(value=[[-1], [1]])\n vtk_r = Array(value=[[-1.], [1.]])\n vtk_cells = [[0, 1]]\n vtk_cell_types = 'Line'\n\n dots_class = DOTSGridEval\n\n n_dof_r = Property\n '''Number of node positions associated with degrees of freedom. \n '''\n @cached_property\n def _get_n_dof_r(self):\n return len(self.dof_r)\n\n n_e_dofs = Property\n '''Number of element degrees\n '''\n @cached_property\n def _get_n_e_dofs(self):\n return self.n_nodal_dofs * self.n_dof_r\n\n def _get_ip_coords(self):\n offset = 1e-6\n return np.array([[-1 + offset, 0., 0.], [1 - offset, 0., 0.]])\n\n def _get_ip_weights(self):\n return np.array([1., 1.], dtype=float)\n\n # Integration parameters\n #\n ngp_r = 2\n\n def get_N_geo_mtx(self, r_pnt):\n '''\n Return geometric shape functions\n @param r_pnt:\n '''\n r = r_pnt[0]\n N_mtx = np.array([[0.5 - r / 2., 0.5 + r / 2.]])\n return N_mtx\n\n def get_dNr_geo_mtx(self, r_pnt):\n '''\n Return the matrix of shape function derivatives.\n Used for the conrcution of the Jacobi matrix.\n '''\n return np.array([[-1. / 2, 1. / 2]])\n\n def get_N_mtx(self, r_pnt):\n '''\n Return shape functions\n @param r_pnt:local coordinates\n '''\n return self.get_N_geo_mtx(r_pnt)\n\n def get_dNr_mtx(self, r_pnt):\n '''\n Return the derivatives of the shape functions\n '''\n return self.get_dNr_geo_mtx(r_pnt)\n\n xi_m = Array(value=[[-1], [1]], dtype=np.float)\n r_m = Array(value=[[-1], [1]], dtype=np.float_)\n w_m = Array(value=[1, 1], dtype=np.float_)\n\n Nr_i_geo = List([(1 - r_) / 2.0,\n (1 + r_) / 2.0, ])\n\n dNr_i_geo = List([- 1.0 / 2.0,\n 1.0 / 2.0, ])\n\n Nr_i = Nr_i_geo\n dNr_i = dNr_i_geo\n\n N_mi_geo = Property()\n\n @cached_property\n def _get_N_mi_geo(self):\n return self.get_N_mi(sp.Matrix(self.Nr_i_geo, dtype=np.float_))\n\n dN_mid_geo = Property()\n\n @cached_property\n def _get_dN_mid_geo(self):\n return self.get_dN_mid(sp.Matrix(self.dNr_i_geo, dtype=np.float_))\n\n N_mi = Property()\n\n @cached_property\n def _get_N_mi(self):\n return self.get_N_mi(sp.Matrix(self.Nr_i, dtype=np.float_))\n\n dN_mid = Property()\n\n @cached_property\n def _get_dN_mid(self):\n return self.get_dN_mid(sp.Matrix(self.dNr_i, dtype=np.float_))\n\n def get_N_mi(self, Nr_i):\n return np.array([Nr_i.subs(r_, r)\n for r in self.r_m], dtype=np.float_)\n\n def get_dN_mid(self, dNr_i):\n dN_mdi = np.array([[dNr_i.subs(r_, r)]\n for r in self.r_m], dtype=np.float_)\n return np.einsum('mdi->mid', dN_mdi)\n\n n_m = Property(depends_on='w_m')\n\n @cached_property\n def _get_n_m(self):\n return len(self.w_m)\n\n A_C = Property(depends_on='A_m,A_f')\n\n @cached_property\n def _get_A_C(self):\n return np.array((self.A_f, self.P_b, self.A_m), dtype=np.float_)\n\n def get_B_EmisC(self, J_inv_Emdd):\n fets_eval = self\n\n n_dof_r = fets_eval.n_dof_r\n n_nodal_dofs = fets_eval.n_nodal_dofs\n\n n_m = fets_eval.n_gp\n n_E = J_inv_Emdd.shape[0]\n n_s = 3\n #[ d, i]\n r_ip = fets_eval.ip_coords[:, :-2].T\n # [ d, n ]\n geo_r = fets_eval.geo_r.T\n # [ d, n, i ]\n dNr_geo = geo_r[:, :, None] * np.array([1, 1]) * 0.5\n # [ i, n, d ]\n dNr_geo = np.einsum('dni->ind', dNr_geo)\n\n # shape function for the unknowns\n # [ d, n, i]\n Nr = 0.5 * (1. + geo_r[:, :, None] * r_ip[None, :])\n dNr = 0.5 * geo_r[:, :, None] * np.array([1, 1])\n\n # [ i, n, d ]\n Nr = np.einsum('dni->ind', Nr)\n dNr = np.einsum('dni->ind', dNr)\n Nx = Nr\n # [ n_e, n_ip, n_dof_r, n_dim_dof ]\n dNx = np.einsum('eidf,inf->eind', J_inv_Emdd, dNr)\n\n B = np.zeros((n_E, n_m, n_dof_r, n_s, n_nodal_dofs), dtype='f')\n B_N_n_rows, B_N_n_cols, N_idx = [1, 1], [0, 1], [0, 0]\n B_dN_n_rows, B_dN_n_cols, dN_idx = [0, 2], [0, 1], [0, 0]\n B_factors = np.array([-1, 1], dtype='float_')\n B[:, :, :, B_N_n_rows, B_N_n_cols] = (B_factors[None, None, :] *\n Nx[:, :, N_idx])\n B[:, :, :, B_dN_n_rows, B_dN_n_cols] = dNx[:, :, :, dN_idx]\n\n return B\n\n def _get_B_EimsC(self, dN_Eimd, sN_Cim):\n\n n_E, n_i, n_m, n_d = dN_Eimd.shape\n n_C, n_i, n_m = sN_Cim.shape\n n_s = 3\n B_EimsC = np.zeros(\n (n_E, n_i, n_m, n_s, n_C), dtype='f')\n B_EimsC[..., [1, 1], [0, 1]] = sN_Cim[[0, 1], :, :]\n B_EimsC[..., [0, 2], [0, 1]] = dN_Eimd[:, [0, 1], :, :]\n\n return B_EimsC\n\n shape_function_values = tr.Property(tr.Tuple)\n '''The values of the shape functions and their derivatives at the IPs\n '''\n @tr.cached_property\n def _get_shape_function_values(self):\n N_mi = np.array([N_xi_i.subs(list(zip([xi_1, xi_2, xi_3], xi)))\n for xi in self.xi_m], dtype=np.float_)\n N_im = np.einsum('mi->im', N_mi)\n dN_mir_arr = [np.array(dN_xi_ir.subs(list(zip([xi_1], xi)))).astype(np.float_)\n for xi in self.xi_m]\n dN_mir = np.array(dN_mir_arr, dtype=np.float)\n dN_nir_arr = [np.array(dN_xi_ir.subs(list(zip([xi_1], xi)))).astype(np.float_)\n for xi in self.vtk_r]\n dN_nir = np.array(dN_nir_arr, dtype=np.float)\n dN_imr = np.einsum('mir->imr', dN_mir)\n dN_inr = np.einsum('nir->inr', dN_nir)\n return (N_im, dN_imr, dN_inr)\n\n N_im = tr.Property()\n '''Shape function values in integration poindots.\n '''\n\n def _get_N_im(self):\n return self.shape_function_values[0]\n\n dN_imr = tr.Property()\n '''Shape function derivatives in integration poindots.\n '''\n\n def _get_dN_imr(self):\n return self.shape_function_values[1]\n\n dN_inr = tr.Property()\n '''Shape function derivatives in visualization poindots.\n '''\n\n def _get_dN_inr(self):\n return self.shape_function_values[2]\n\n I_sym_abcd = tr.Array(np.float)\n\n def _I_sym_abcd_default(self):\n delta = np.identity(3)\n return 0.5 * \\\n (np.einsum('ac,bd->abcd', delta, delta) +\n np.einsum('ad,bc->abcd', delta, delta))\n\n\nif __name__ == '__main__':\n fe = FETS1D52ULRHFatigue()\n print('dN_imr', fe.dN_imr)\n","sub_path":"bmcs/mats/fets1d52ulrhfatigue.py","file_name":"fets1d52ulrhfatigue.py","file_ext":"py","file_size_in_byte":8031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219370620","text":"import matplotlib.pyplot as plt \nimport matplotlib as matlib\nimport numpy as np\nimport seaborn as sns\n\n\nsns.set_context(\"poster\")\nplt.style.use('seaborn')\nplt.rc({'font.size': 20})\nfont = {'family' : 'normal',\n # 'weight' : 'bold',\n 'size' : 20}\nmatlib.rc('font', **font)\nmatlib.rcParams['xtick.labelsize'] = 10\nmatlib.rcParams.update({'font.size': 22})\n# sns.set_context(\"talk\")\n\nATI = [0.54, 1.03, 1.60, 1.9, 2.43, 2.8, 3.42] \nCamera = [0.0032, 0.0069, 0.0102, 0.0122, 0.0193, 0.0227, 0.0268]\n\nATI2 = [0.54, 1.06, 1.61, 2.06]\nCamera2 = [0.0024, 0.0062, 0.0105, 0.0155]\n\nATI3 = [0.037, 0.99, 1.52, 2.51]\nCamera3 = [0.0026, 0.0078, 0.0110, 0.0201]\n\nplt.figure(figsize=(4,3))\nplt.rc('xtick', labelsize=20) # fontsize of the tick labels\nplt.rc('ytick', labelsize=20) # fontsize of the tick labels\nplt.title(\"Quick calibration of 1D apriltag force sensor\", **font)\nax = plt.plot(1000*np.array(Camera), -np.array(ATI), label='reading 1', marker = 'o')\nplt.ylabel('ATI (Newtons)', **font)\nplt.xlabel('Camera (openCV uncalibrated mm)',**font)\nplt.plot(1000*np.array(Camera2), -np.array(ATI2), label='reading 2', marker = 'o')\nplt.plot(1000*np.array(Camera3), -np.array(ATI3), label='reading 3', marker = 'o')\nlgd = plt.legend()\nlgd.FontSize = 20;\n\n# params = {'axes.labelsize': 18,'axes.titlesize':20, 'text.fontsize': 20, 'legend.fontsize': 20, 'xtick.labelsize': 28, 'ytick.labelsize': 40}\n# matlib.rcParams.update(params)\n\n# for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\n # ax.get_xticklabels() + ax.get_yticklabels()):\n # item.set_fontsize(20)\n# plt.plot([1000*x for x in (Camera + Camera2 + Camera3)], [-1*x for x in ATI+ATI2+ATI3])\n# 0 in, 0.035 in to 0out, -3.2 out\n\n# def map(x, in_min, in_max, out_min, out_max):\n # return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\n\n# force_ish = [map(x, 0, 0.025, 0, -3.2) for x in Camera])\n# plt.plot(force_ish, -ATI, label='convert')\n\nplt.legend()\n# strtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n# ax = plt.gca()\n# plt.text(1.01, 0, 'Time: '+strtime, horizontalalignment='left', verticalalignment='bottom',\n # transform = ax.transAxes, fontsize=6)\n\nplt.show()\n\n\n# 0N = 0, 0.025 mm = -3.2N\n# scaling: input camera reading, cam * (-3.2/0.035)\n","sub_path":"python_analysis/sangbae_ATI_plot.py","file_name":"sangbae_ATI_plot.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"455276304","text":"#FAST API\n#Model Deployment\nimport pandas as pd\nimport numpy as np\nimport os\nos.chdir(r\"D:\\Data_Science\\Bank_Note_Auth\")\nprint(os.getcwd())\ndf=pd.read_csv(\"BankNote_Authentication.csv\")\nprint(df.head())\nprint(df.size)\nprint(df.shape)\nprint(df.describe())\nprint(df.info())\nprint(df.isnull().sum())\nX=df.iloc[:,0:4]\ny=df.iloc[:,4]\nprint(X.head())\nprint(y.head())\n#Train test split\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=0)\n#RF classifier\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier=RandomForestClassifier()\nclassifier.fit(X_train,y_train)\n#Prediction\ny_pred=classifier.predict(X_test)\n#Check accuracy\nfrom sklearn.metrics import accuracy_score\nscore=accuracy_score(y_test,y_pred)\nprint(score) #0.9902912621359223\n#Prediction with new data\nprint(classifier.predict([[2,3,4,1]])) #[0]\n#Create pickle file\nimport pickle\npickle_out=open(\"classifier.pkl\",\"wb\")\npickle.dump(classifier,pickle_out)\npickle_out.close()","sub_path":"restapi.py","file_name":"restapi.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"470126639","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import SIGNAL, Qt\n\nfrom interfaces_ui.frm_exportacao_manual import *\nfrom tarefas.thread_exportacao_manual import ThreadExportacaoManual\n\n\nclass form_exportacao_manual(QDialog, Ui_frm_exportacao_manual):\n def __init__(self, parent=None, conexao=None):\n super(form_exportacao_manual, self).__init__(parent)\n self.setupUi(self)\n self.frm_load()\n self.conexao = conexao\n\n def frm_load(self):\n self.btnExportar.clicked.connect(self.exportar)\n self.btnSair.clicked.connect(self.close)\n\n def exportar(self):\n if self.btnExportar.text() == \"Exportar\":\n self.btnExportar.setText(\"Parar...\")\n self.th_exportacao = ThreadExportacaoManual(self, self.conexao)\n self.connect(self.th_exportacao, SIGNAL(\"processo\"), self.lbl_processo.setText, Qt.QueuedConnection)\n self.connect(self.th_exportacao, SIGNAL(\"registro_atual\"), self.lbl_reg_atual.setText, Qt.QueuedConnection)\n self.connect(self.th_exportacao, SIGNAL(\"registro_total\"), self.lbl_reg_total.setText, Qt.QueuedConnection)\n self.connect(self.th_exportacao, SIGNAL(\"progresso_atual\"), self.pbar.setValue, Qt.QueuedConnection)\n self.connect(self.th_exportacao, SIGNAL(\"progresso_total\"), self.pbar.setMaximum, Qt.QueuedConnection)\n self.th_exportacao.start()\n else:\n self.btnExportar.setText(\"Exportar\")\n self.th_exportacao.matar()\n self.th_exportacao.terminate()\n\n def thread_finalizada(self):\n self.btnExportar.setText(\"Exportar\")\n","sub_path":"view/exportacao_manual.py","file_name":"exportacao_manual.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"162372156","text":"# Definition for a binary tree node.\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\n#Time complexity - O(n) - I am not sure\r\n#Space complexity - O(1) since we are returning true or false\r\n#Explanation - Recursively check both the nodes of the tree if they have equal values\r\n\r\nclass Solution:\r\n def isSymmetric(self, root: TreeNode) -> bool:\r\n return self.helper(root, root)\r\n def helper(self, node1, node2):\r\n if node1 == None and node2 == None:\r\n #print(node1.val)\r\n #print(node2.val)\r\n return True\r\n if node1 != None and node2 == None:\r\n return False\r\n if node1 == None and node2 != None:\r\n return False\r\n side1 = self.helper(node1.left, node2.right)\r\n side2 = self.helper(node1.right, node2.left)\r\n \r\n if side1== side2:\r\n\t\t\t#print(side1)\r\n\t\t\t#print(side2)\t\t\r\n return (node1.val == node2.val) ","sub_path":"symmetric-tree.py","file_name":"symmetric-tree.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"503887140","text":"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Implement the debugger grpc server.\"\"\"\nimport copy\nfrom functools import wraps\n\nimport mindinsight\nfrom mindinsight.debugger.common.log import LOGGER as log\nfrom mindinsight.debugger.common.utils import get_ack_reply, ServerStatus, \\\n Streams, RunLevel\nfrom mindinsight.debugger.conditionmgr.condition import TargetTypeEnum, ParamNameEnum\nfrom mindinsight.debugger.proto import debug_grpc_pb2_grpc as grpc_server_base\nfrom mindinsight.debugger.proto.ms_graph_pb2 import GraphProto\n\n\ndef debugger_wrap(func):\n \"\"\"Wrapper for catch exception.\"\"\"\n\n @wraps(func)\n def record_log(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception as err:\n log.exception(err)\n raise err\n\n return record_log\n\n\nclass DebuggerGrpcServer(grpc_server_base.EventListenerServicer):\n \"\"\"The grpc server used to interactive with grpc client.\"\"\"\n\n def __init__(self, cache_store, condition_mgr):\n \"\"\"\n Initialize.\n\n Args:\n cache_store (DebuggerCache): Debugger cache store.\n \"\"\"\n cache_store.initialize()\n self._cache_store = cache_store\n self._condition_mgr = condition_mgr\n # the next position of command queue to be queried\n self._pos = None\n # the status of grpc server, the value is in ServerStatus\n self._status = None\n # the run command cache, used to deal with left continue steps or nodes\n self._old_run_cmd = None\n # the view command cache, used to update tensor history through data queue\n self._received_view_cmd = None\n # the flag of receiving watch point hit\n self._received_hit = None\n self.init()\n\n def init(self):\n \"\"\"Init debugger grpc server.\"\"\"\n self._pos = '0'\n self._status = ServerStatus.PENDING\n self._old_run_cmd = {}\n self._received_view_cmd = {}\n self._received_hit = []\n self._cache_store.clean()\n\n @debugger_wrap\n def WaitCMD(self, request, context):\n \"\"\"Wait for a command in DebuggerCache.\"\"\"\n # check if graph have already received.\n log.info(\"Received WaitCMD at %s-th step.\", request.cur_step)\n if self._status == ServerStatus.PENDING:\n log.warning(\"No graph received before WaitCMD.\")\n reply = get_ack_reply(1)\n return reply\n\n # send graph if it has not been sent before\n self._pre_process(request)\n # deal with old command\n reply = self._deal_with_old_command()\n # wait for next command\n if reply is None:\n reply = self._wait_for_next_command()\n # check the reply\n if reply is None:\n reply = get_ack_reply(1)\n log.warning(\"Failed to get command event.\")\n else:\n log.debug(\"Reply to WaitCMD: %s\", reply)\n return reply\n\n def _pre_process(self, request):\n \"\"\"Pre-process before dealing with command.\"\"\"\n\n # check if version is mismatch, if mismatch, send mismatch info to UI\n if self._status == ServerStatus.MISMATCH:\n log.warning(\"Version of MindSpore and MindInsight are unmatched,\"\n \"waiting for user to terminate the script.\")\n metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)\n # put metadata into data queue\n metadata = metadata_stream.get(['state', 'debugger_version'])\n self._cache_store.put_data(metadata)\n return\n\n metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)\n is_new_step = metadata_stream.step < request.cur_step\n is_new_node = metadata_stream.full_name != request.cur_node\n # clean cache data at the beginning of new step or node has been changed.\n if is_new_step or is_new_node:\n self._cache_store.clean_data()\n self._cache_store.get_stream_handler(Streams.TENSOR).clean_tensors(request.cur_step)\n if is_new_step:\n self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).clean()\n # receive graph at the beginning of the training\n if self._status == ServerStatus.RECEIVE_GRAPH:\n self._send_graph_flag(metadata_stream)\n # receive new metadata\n if is_new_step or is_new_node:\n self._update_metadata(metadata_stream, request)\n self._send_received_tensor_tag()\n self._send_watchpoint_hit_flag()\n\n def _send_graph_flag(self, metadata_stream):\n \"\"\"\n Send graph and metadata to UI.\n\n Args:\n metadata_stream (MetadataHandler): Metadata handler stream.\n \"\"\"\n self._cache_store.clean_command()\n # receive graph in the beginning of the training\n self._status = ServerStatus.WAITING\n metadata_stream.state = ServerStatus.WAITING.value\n metadata = metadata_stream.get()\n res = self._cache_store.get_stream_handler(Streams.GRAPH).get()\n res.update(metadata)\n self._cache_store.put_data(res)\n log.debug(\"Put graph into data queue.\")\n\n def _update_metadata(self, metadata_stream, metadata_proto):\n \"\"\"\n Update metadata.\n\n Args:\n metadata_stream (MetadataHandler): Metadata handler stream.\n metadata_proto (MetadataProto): Metadata proto send by client.\n \"\"\"\n # put new metadata into cache\n metadata_stream.put(metadata_proto)\n # update current node name and graph name\n graph_stream = self._cache_store.get_stream_handler(Streams.GRAPH)\n full_name = metadata_proto.cur_node\n graph_name = graph_stream.get_graph_id_by_full_name(\n full_name) if full_name else metadata_stream.graph_name\n cur_node = graph_stream.get_node_name_by_full_name(full_name, graph_name)\n metadata_stream.node_name = cur_node\n metadata_stream.graph_name = graph_name\n metadata = metadata_stream.get()\n self._cache_store.put_data(metadata)\n log.debug(\"Put new metadata into data queue.\")\n\n def _send_received_tensor_tag(self):\n \"\"\"Send received_finish_tag.\"\"\"\n node_info = self._received_view_cmd.get('node_info')\n if not node_info or self._received_view_cmd.get('wait_for_tensor'):\n return\n metadata = self._cache_store.get_stream_handler(Streams.METADATA).get(['step', 'state'])\n ret = {'receive_tensor': node_info.copy()}\n ret.update(metadata)\n self._cache_store.put_data(ret)\n self._received_view_cmd.clear()\n log.debug(\"Send receive tensor flag for %s\", node_info)\n\n def _send_watchpoint_hit_flag(self):\n \"\"\"Send Watchpoint hit flag.\"\"\"\n watchpoint_hit_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT)\n if not self._received_hit:\n return\n watchpoint_hits = self._received_hit\n self._received_hit = []\n for watchpoint_hit in watchpoint_hits:\n watchpoint_hit_stream.put(watchpoint_hit)\n watchpoint_hits_info = {'receive_watchpoint_hits': True}\n self._cache_store.put_data(watchpoint_hits_info)\n log.debug(\"Send the watchpoint hits to DataQueue.\\nSend the reply.\")\n\n def _deal_with_old_command(self):\n \"\"\"Deal with old command.\"\"\"\n event = None\n while self._cache_store.has_command(self._pos) and event is None:\n event = self._get_next_command()\n log.debug(\"Deal with old %s-th command:\\n%s.\", self._pos, event)\n # deal with continue run command\n if event is None and self._old_run_cmd:\n left_step_count = self._old_run_cmd.get('left_step_count')\n node_name = self._old_run_cmd.get('node_name')\n # node_name and left_step_count should not set at the same time\n if not (left_step_count or node_name) or (left_step_count and node_name):\n log.warning(\"Invalid old run command. %s\", self._old_run_cmd)\n self._old_run_cmd.clear()\n return None\n if left_step_count:\n event = self._deal_with_left_continue_step(left_step_count)\n else:\n event = self._deal_with_left_continue_node(node_name)\n log.debug(\"Send old RunCMD.\")\n return event\n\n def _deal_with_left_continue_step(self, left_step_count):\n \"\"\"\n Construct run command with left continue step count.\n\n Args:\n left_step_count (int): The count of left steps to be executed.\n\n Returns:\n Event, the run command event.\n \"\"\"\n event = get_ack_reply()\n event.run_cmd.run_steps = 1\n event.run_cmd.run_level = 'step'\n left_step_count = left_step_count - 1 if left_step_count > 0 else -1\n if not left_step_count:\n self._old_run_cmd.clear()\n else:\n self._old_run_cmd['left_step_count'] = left_step_count\n log.debug(\"Send old step RunCMD. Left step count: %s\", left_step_count)\n return event\n\n def _deal_with_left_continue_node(self, node_name):\n \"\"\"\n Construct run command with left continue nodes.\n\n Args:\n node_name (str): The target node name.\n\n Returns:\n Union[None, Event], the run command event.\n \"\"\"\n cur_full_name = self._cache_store.get_stream_handler(Streams.METADATA).full_name\n if cur_full_name == node_name:\n log.info(\"Execute to target node: %s\", node_name)\n self._old_run_cmd.clear()\n return None\n event = get_ack_reply()\n event.run_cmd.run_level = 'node'\n event.run_cmd.node_name = ''\n log.debug(\"Send old node RunCMD, cur node: %s, target node: %s\", cur_full_name, node_name)\n return event\n\n def _wait_for_next_command(self):\n \"\"\"\n Wait for next command.\n\n Returns:\n EventReply, the command event.\n \"\"\"\n log.info(\"Start to wait for command.\")\n if self._status != ServerStatus.MISMATCH:\n self._cache_store.get_stream_handler(Streams.METADATA).state = ServerStatus.WAITING.value\n self._cache_store.put_data({'metadata': {'state': 'waiting'}})\n event = None\n while event is None and self._status not in [ServerStatus.RUNNING, ServerStatus.PENDING]:\n log.debug(\"Wait for %s-th command\", self._pos)\n event = self._get_next_command()\n return event\n\n def _get_next_command(self):\n \"\"\"Get next command.\"\"\"\n self._pos, event = self._cache_store.get_command(self._pos)\n if event is None:\n return event\n # deal with command\n metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)\n if isinstance(event, dict):\n event = self._deal_with_view_cmd(event)\n elif event.HasField('run_cmd'):\n event = self._deal_with_run_cmd(event)\n self._cache_store.put_data(metadata_stream.get())\n elif event.HasField('exit'):\n self._cache_store.clean()\n self._cache_store.put_data(metadata_stream.get())\n log.debug(\"Clean cache for exit cmd.\")\n else:\n self._cache_store.get_stream_handler(Streams.WATCHPOINT).clean_cache_set_cmd(event.set_cmd)\n log.debug(\"get set cmd.\")\n\n return event\n\n def _deal_with_view_cmd(self, event):\n \"\"\"\n Deal with view cmd.\n\n Args:\n event (dict): View command params.\n\n - view_cmd (EventReply): EventReply with view command.\n - node_name (str): The center node name for view command.\n - tensor_name (str): The center tensor name for view command.\n - graph_name (str): The graph name of center node.\n\n Returns:\n EventReply, view command to be sent to client.\n \"\"\"\n view_cmd = event.pop('view_cmd', None)\n log.debug(\"Receive view cmd for node: %s.\", event)\n if not (view_cmd and event):\n log.debug(\"Invalid view command. Ignore it.\")\n return None\n self._received_view_cmd['node_info'] = event\n self._received_view_cmd['wait_for_tensor'] = True\n return view_cmd\n\n def _deal_with_run_cmd(self, event):\n \"\"\"Deal with run cmd.\"\"\"\n metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)\n run_cmd = event.run_cmd\n # receive step command\n if run_cmd.run_level == RunLevel.STEP.value:\n # receive pause cmd\n if not run_cmd.run_steps:\n log.debug(\"Pause training and wait for next command.\")\n self._old_run_cmd.clear()\n # update metadata state from sending to waiting\n metadata_stream.state = ServerStatus.WAITING.value\n return None\n # receive step cmd\n left_steps = run_cmd.run_steps - 1\n event.run_cmd.run_steps = 1\n if left_steps:\n self._old_run_cmd['left_step_count'] = left_steps if left_steps > 0 else -1\n elif run_cmd.node_name:\n self._old_run_cmd['node_name'] = run_cmd.node_name\n run_cmd.node_name = ''\n # clean watchpoint hit cache\n if run_cmd.run_level == RunLevel.RECHECK.value:\n self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).clean()\n log.debug(\"Receive RunCMD. Clean watchpoint hit cache.\")\n # update metadata state from sending to running\n metadata_stream.state = ServerStatus.RUNNING.value\n return event\n\n @debugger_wrap\n def SendMetadata(self, request, context):\n \"\"\"Send metadata into DebuggerCache.\"\"\"\n log.info(\"Received Metadata.\")\n if self._status != ServerStatus.PENDING:\n log.info(\"Re-initialize cache store when new session comes.\")\n self.init()\n\n client_ip = context.peer().split(':', 1)[-1]\n metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)\n reply = get_ack_reply()\n if request.training_done:\n log.info(\"The training from %s has finished.\", client_ip)\n else:\n ms_version = request.ms_version\n if not ms_version:\n ms_version = '1.0.x'\n if version_match(ms_version, mindinsight.__version__) is False:\n log.info(\"Version is mismatched, mindspore is: %s, mindinsight is: %s\",\n ms_version, mindinsight.__version__)\n self._status = ServerStatus.MISMATCH\n reply.version_matched = False\n metadata_stream.state = ServerStatus.MISMATCH.value\n else:\n log.info(\"version is matched.\")\n reply.version_matched = True\n\n metadata_stream.debugger_version = {'ms': ms_version, 'mi': mindinsight.__version__}\n log.debug(\"Put ms_version from %s into cache.\", client_ip)\n\n metadata_stream.put(request)\n metadata_stream.client_ip = client_ip\n log.debug(\"Put new metadata from %s into cache.\", client_ip)\n # put metadata into data queue\n metadata = metadata_stream.get()\n self._cache_store.put_data(metadata)\n log.debug(\"Send the reply to %s.\", client_ip)\n return reply\n\n @debugger_wrap\n def SendGraph(self, request_iterator, context):\n \"\"\"Send graph into DebuggerCache.\"\"\"\n log.info(\"Received graph.\")\n reply = get_ack_reply()\n if self._status == ServerStatus.MISMATCH:\n log.info(\"Mindspore and Mindinsight is unmatched, waiting for user to terminate the service.\")\n return reply\n serial_graph = b\"\"\n for chunk in request_iterator:\n serial_graph += chunk.buffer\n graph = GraphProto.FromString(serial_graph)\n log.debug(\"Deserialize the graph %s. Receive %s nodes\", graph.name, len(graph.node))\n graph_dict = {graph.name: graph}\n self._cache_store.get_stream_handler(Streams.GRAPH).put(graph_dict)\n self._cache_store.get_stream_handler(Streams.TENSOR).put_const_vals(graph.const_vals)\n self._cache_store.get_stream_handler(Streams.METADATA).graph_name = graph.name\n self._record_parameter_names()\n self._status = ServerStatus.RECEIVE_GRAPH\n log.debug(\"Send the reply for graph.\")\n return reply\n\n @debugger_wrap\n def SendMultiGraphs(self, request_iterator, context):\n \"\"\"Send graph into DebuggerCache.\"\"\"\n log.info(\"Received multi_graphs.\")\n reply = get_ack_reply()\n if self._status == ServerStatus.MISMATCH:\n log.info(\"Mindspore and Mindinsight is unmatched, waiting for user to terminate the service.\")\n return reply\n serial_graph = b\"\"\n graph_dict = {}\n for chunk in request_iterator:\n serial_graph += chunk.buffer\n if chunk.finished:\n sub_graph = GraphProto.FromString(serial_graph)\n graph_dict[sub_graph.name] = sub_graph\n log.debug(\"Deserialize the graph %s. Receive %s nodes\", sub_graph.name,\n len(sub_graph.node))\n serial_graph = b\"\"\n self._cache_store.get_stream_handler(Streams.TENSOR).put_const_vals(\n sub_graph.const_vals)\n\n self._cache_store.get_stream_handler(Streams.GRAPH).put(graph_dict)\n self._record_parameter_names()\n self._status = ServerStatus.RECEIVE_GRAPH\n log.debug(\"Send the reply for graph.\")\n return reply\n\n def _record_parameter_names(self):\n \"\"\"Record parameter full names in tensor handler.\"\"\"\n parameter_nodes = self._cache_store.get_stream_handler(Streams.GRAPH).search_in_graph(\n pattern={'node_category': TargetTypeEnum.PARAMETER.value})\n tensor_stream = self._cache_store.get_stream_handler(Streams.TENSOR)\n for node in parameter_nodes:\n tensor_name = [node.full_name + ':0']\n tensor_stream.record_parameter_names(tensor_name)\n\n @debugger_wrap\n def SendTensors(self, request_iterator, context):\n \"\"\"Send tensors into DebuggerCache.\"\"\"\n log.info(\"Received tensor.\")\n tensor_contents = []\n tensor_stream = self._cache_store.get_stream_handler(Streams.TENSOR)\n metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)\n step = metadata_stream.step\n for tensor in request_iterator:\n tensor_contents.append(tensor.tensor_content)\n if tensor.finished:\n update_flag = tensor_stream.put(\n {'step': step, 'tensor_proto': tensor, 'tensor_contents': tensor_contents})\n if self._received_view_cmd.get('wait_for_tensor') and update_flag:\n # update_flag is used to avoid querying empty tensors again\n self._received_view_cmd['wait_for_tensor'] = False\n log.debug(\"Set wait for tensor flag to False.\")\n tensor_contents = []\n continue\n reply = get_ack_reply()\n return reply\n\n @debugger_wrap\n def SendWatchpointHits(self, request_iterator, context):\n \"\"\"Send watchpoint hits info DebuggerCache.\"\"\"\n log.info(\"Received WatchpointHits. Left run cmd %s change to emtpy.\", self._old_run_cmd)\n self._old_run_cmd.clear()\n if self._cache_store.get_stream_handler(Streams.METADATA).state == ServerStatus.RUNNING.value:\n # if the client session is running a script, all the cached command should be cleared\n # when received watchpoint_hits.\n self._cache_store.clean_command()\n\n # save the watchpoint_hits data\n watchpoint_hits = []\n watchpoint_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT)\n graph_stream = self._cache_store.get_stream_handler(Streams.GRAPH)\n for watchpoint_hit_proto in request_iterator:\n node_full_name = watchpoint_hit_proto.tensor.node_name\n graph_name = graph_stream.get_graph_id_by_full_name(node_full_name)\n if not graph_name:\n log.warning(\"Cannot find node %s in graph. Skip it.\", node_full_name)\n continue\n ui_node_name = graph_stream.get_node_name_by_full_name(node_full_name, graph_name)\n log.debug(\"Receive watch point hit: %s\", watchpoint_hit_proto)\n if not ui_node_name:\n log.info(\"Not support to show %s on graph.\", node_full_name)\n continue\n watchpoint_hit = {\n 'tensor_proto': watchpoint_hit_proto.tensor,\n 'watchpoint': copy.deepcopy(watchpoint_stream.get_watchpoint_by_id(watchpoint_hit_proto.id)),\n 'node_name': ui_node_name,\n 'graph_name': graph_name\n }\n hit_params = {}\n for param in watchpoint_hit_proto.watch_condition.params:\n if param.name not in (ParamNameEnum.RTOL.value, ParamNameEnum.RANGE_START_INCLUSIVE.value,\n ParamNameEnum.RANGE_END_INCLUSIVE.value) \\\n and watchpoint_hit_proto.error_code == 0:\n hit_params[param.name] = param.actual_value\n for i, param in enumerate(watchpoint_hit['watchpoint'].condition['params']):\n name = param['name']\n if name in hit_params.keys():\n watchpoint_hit['watchpoint'].condition['params'][i]['actual_value'] = hit_params[name]\n else:\n watchpoint_hit['watchpoint'].condition['params'][i]['actual_value'] = None\n watchpoint_hit['error_code'] = watchpoint_hit_proto.error_code\n watchpoint_hits.append(watchpoint_hit)\n self._received_hit = watchpoint_hits\n reply = get_ack_reply()\n return reply\n\n\ndef version_match(mi_version, ms_version):\n \"\"\"Judge if the version of Mindinsight and Mindspore is matched\"\"\"\n mi_major, mi_minor = mi_version.split('.')[:2]\n ms_major, ms_minor = ms_version.split('.')[:2]\n return mi_major == ms_major and mi_minor == ms_minor\n","sub_path":"mindinsight/debugger/debugger_grpc_server.py","file_name":"debugger_grpc_server.py","file_ext":"py","file_size_in_byte":22921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"350136483","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport argparse\nimport time\nimport os\nimport sys\nimport tensorflow as tf\nimport tensorflow.keras\nimport numpy as np\n#from .model import Model\nfrom . import data\nimport importlib\nimport tensorflow.keras as KK\nimport random\n\n################################\ndef train(args):\n\n #with tf.device(\"/cpu:0\"):\n #with tf.device(\"/gpu:3\"):\n if True:\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=args.CUDA_VISIBLE_DEVICES\n\n # load the model based on name and access as Model: from .model import args.model\n myimport = importlib.import_module(\"tfccs.%s\" % args.model)\n Model = myimport.Model\n\n model = Model(args)\n\n model.model.save(args.modelsave)\n with open(\"%s.model.json\" % args.modelsave,\"w\") as f:\n f.write(model.model.to_json())\n model.model.save_weights(\"%s.model.h5\" % args.modelsave)\n\n t0=time.time()\n data_loader = data.data( args.batch_size, sys.argv[2],\n inputdatName=args.inputdatName,\n outputdatName=args.outputdatName)\n t1=time.time()\n print(\"time data_loader\",str(t1-t0))\n\n # get test if there\n data_loader_test = None\n if len(sys.argv)>3:\n t0=time.time()\n data_loader_test = data.data( args.batch_size, sys.argv[3],\n inputdatName=args.inputdatName,\n outputdatName=args.outputdatName)\n t1=time.time()\n print(\"time data_loader test\",str(t1-t0))\n\n tfconfig=tf.ConfigProto()\n\n with tf.Session( config=tfconfig ) as sess:\n sess.run(tf.global_variables_initializer())\n\n if hasattr(args, \"modelrestore\"):\n\n # This doesn't work as\n # my_sparse_categorical_crossentropy is implicit\n # function and must be defined in training. TODO: I\n # can move the loss funtion to explicitly defined with\n # passed parameters\n\n # model.model = KK.models.load_model(args.modelrestore, custom_objects={\"KK\":KK, \n # \"zero_loss\": nullloss,\n # \"my_sparse_categorical_crossentropy\": nullloss })\n\n # take already loaded model and just load the weights\n print(\"about to model load_weights\", args.modelrestore)\n model.model.load_weights( args.modelrestore )\n print(\"restored model load_weights\", args.modelrestore)\n\n print(\"# args.num_epochs\", args.num_epochs, \"args.batch_size\", args.batch_size, \"num_batches\", data_loader.num_batches)\n\n testLossAvgMIN = 999.9E+99\n first=True\n for e in range(args.num_epochs):\n storeloss = []\n data_loader.reset_batch_pointer()\n for b in range(data_loader.num_batches):\n start = time.time()\n x, y = data_loader.next_batch()\n\n # train on random readNumber for this batch (not single specified:args.readNumber)\n readNumber = random.randrange(args.rows)\n readNumberArray = np.full( (x[0].shape[0],1), readNumber, dtype=np.float32)\n x.append(readNumberArray)\n y.append(readNumberArray)\n\n if first:\n first=False\n # print(\"x.shape\",x.shape)\n # print(\"y.shape\",y.shape)\n # print(\"x[4]\",x[4])\n # print(\"y[4]\",y[4])\n for ii in range(len(x)):\n print(\"ii\",ii,\"x[ii].shape\",x[ii].shape)\n for ii in range(len(y)):\n print(\"ii\",ii,\"y[ii].shape\",y[ii].shape)\n \n #myfit=model.model.fit( x, [yid,ylen], epochs=1, batch_size=1,verbose=2)\n\n myfit = model.model.train_on_batch( x, y )\n\n end = time.time()\n #print(\"epoch %d batch %d time %f\" % (e, b, end-start))\n for (kk,vv) in zip(model.model.metrics_names,[myfit]):\n print(\"epoch\",e,\"batch\",b,\"trainMetric\",kk,\" \".join([str(xx) for xx in vv]))\n if kk==\"loss\":\n if not isinstance(vv,list): vv = [vv] # only single loss\n # handle multiple inputs\n if isinstance(x,list):\n myx = x[0]\n else:\n myx=x\n storeloss.append( (vv[0],myx.shape[0]) )\n\n # compute average loss across all batches\n trainnum = 0\n trainsum = 0.0\n for xx in storeloss:\n trainsum += xx[0]*xx[1]\n trainnum += xx[1]\n train_loss = trainsum/float(trainnum)\n print(\"epoch %d trainLossAvg %f\" % (e , train_loss))\n\n #### Training ran through all the batches\n\n # if save_every or at tend then save and run validation test\n if (e % args.save_every == 0) or (e == args.num_epochs-1):\n\n model.model.save(args.modelsave)\n with open(\"%s.model.json\" % args.modelsave,\"w\") as f:\n f.write(model.model.to_json())\n model.model.save_weights(\"%s.model.h5\" % args.modelsave)\n\n # run the test set if there\n if data_loader_test is not None:\n storeloss = []\n data_loader_test.reset_batch_pointer()\n for b in range(data_loader_test.num_batches):\n x, y = data_loader_test.next_batch()\n\n # TODO: test only on single readNumber for consistency\n #readNumber = args.readNumber\n readNumber = random.randrange(args.rows)\n readNumberArray = np.full( (x[0].shape[0],1), readNumber, dtype=np.float32)\n x.append(readNumberArray)\n y.append(readNumberArray)\n\n #mytest=model.model.evaluate( x, [yid,ylen],verbose=0)\n mytest = model.model.test_on_batch( x, y )\n\n for (kk,vv) in zip(model.model.metrics_names,[mytest]):\n #print(\"epoch\",e,\"batch\",b,\"trainMetric\",kk,\"=\",vv,\"batchsize\",x.shape[0])\n if kk==\"loss\":\n if not isinstance(vv,list): vv = [vv] # only single loss\n # handle multiple inputs\n if isinstance(x,list):\n myx = x[0]\n else:\n myx=x\n storeloss.append( (vv[0],myx.shape[0]) ) # vv[0] for multiple losses\n\n # compute average loss across all batches\n testnum = 0\n testsum = 0.0\n for xx in storeloss:\n testsum += xx[0]*xx[1]\n testnum += xx[1]\n testLossAvg = testsum/float(testnum)\n print(\"epoch %d testLossAvg %f\" % (e , testLossAvg))\n if testLossAvg < testLossAvgMIN:\n testLossAvgMIN = testLossAvg\n cmd = \"mv %s %s.best\" % (args.modelsave, args.modelsave)\n print(cmd)\n os.system(cmd)\n cmd = \"mv %s.model.json %s.model.json.best\" % (args.modelsave, args.modelsave)\n print(cmd)\n os.system(cmd)\n cmd = \"mv %s.model.h5 %s.model.h5.best\" % (args.modelsave, args.modelsave)\n print(cmd)\n os.system(cmd)\n if testLossAvg > 2.0*testLossAvgMIN:\n print(\"EARLY STOPPING:\",testLossAvg,testLossAvgMIN)\n return()\n\n #sys.exit(1)\n\nif __name__ == '__main__':\n\n print(\"time begin\",str(time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(time.time()))))\n\n exec(open(sys.argv[1]).read())\n args.init_from = None\n\n for aa in sys.argv:\n if \"EXEC:\" in aa:\n toexec = aa.replace(\"EXEC:\",\"\")\n print(\"toexec\",toexec)\n exec(toexec)\n \n print(\"-------\")\n train(args)\n\n print(\"time end\",str(time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(time.time()))))\n","sub_path":"trainAllReads.py","file_name":"trainAllReads.py","file_ext":"py","file_size_in_byte":9148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"636695772","text":"import pyautogui\nimport time\nimport re\nimport sys\nimport os\n\nfrom actors.utilities.ConditionManager import ConditionManager\n\nclass Bot:\n\n # Initializing Object\n def __init__(self, info):\n self.data = info[\"zones_data\"]\n self.conditions = info[\"conditions\"]\n self.db = info[\"db\"]\n self.screenshot_helper = info[\"screenshot_helper\"]\n self.screenshot_data = info[\"screenshot_data\"]\n\n self.queue_processor = info[\"queue_processor\"]\n self.queue_processor.game_bot = None\n\n # self.run_actions = [\"single_reward\", \"multiple_rewards\"]\n # self.run_actions = [\"library\", \"single_reward\", \"multiple_rewards\"]\n # self.run_actions = [\"library\", \"single_reward\",\n # \"multiple_rewards\", \"magic_quarter\", \"campaign\", \"guild\", \"server_swap\", \"map\"]\n # self.run_actions = [\"single_reward\", \"multiple_rewards\", \"magic_quarter\", \"campaign\", \"guild\", \"map\", \"server_swap\"]\n # self.run_actions = [\"library\"]\n self.run_actions = [\"Guild\", \"Campaign\",\n \"MagicQuarter\", \"MultipleRewards\", \"SingleReward\"]\n # run_actions = [\"startup\", \"guild\", \"library\", \"campaign\", \"temple\", \"battle\"]\n # run_actions = [\"library\", \"magic_quarter\"]\n # run_actions = [\"magic_quarter\", \"guild\"]\n # run_actions = [\"campaign\", \"guild\", \"magic_quarter\"]\n # run_actions = [\"multiple_rewards\"]\n\n def click(self, point):\n pyautogui.moveTo(point[\"x\"], point[\"y\"])\n pyautogui.click(point[\"x\"], point[\"y\"])\n\n def setData(self, actors, timer):\n self.actors = actors\n self.timer = timer\n self.actions = timer.data[\"actions\"]\n\n def updateTimerActions(self):\n self.timer[\"area\"]\n\n def start(self):\n # self.setupGame()\n self.timer.startTimer()\n time.sleep(0.2)\n # self.actions[\"startup\"][\"has_ran\"] = True\n self.runAutoBuild()\n\n def setupGame(self):\n startup_action_settings = self.actions[\"startup\"][\"action_settings\"]\n self.timer.startTimer()\n time.sleep(0.2)\n\n actions = self.actions\n updated_startup_action_settings = actions[\"startup\"][\"start_function\"](\n startup_action_settings)\n self.actions[\"startup\"][\"action_settings\"] = updated_startup_action_settings\n\n def runAutoBuild(self):\n actions = self.actions\n timer = self.timer\n conditions = self.conditions\n\n while (True):\n for zone, action in actions.items():\n if (conditions.skipAction(action, zone)):\n print(\"Action ran once and is being skipped: \" + zone)\n else:\n current_time = timer.getCurrentTime()\n print(\"Zone Name: \" + zone + \". Curent Time: \" + str(current_time) + \". Rotation Time: \" +\n str(action[\"rotation_time\"] * action[\"times_performed\"]))\n if (conditions.needToPerformAction(current_time, action)):\n action_data = action[\"action_settings\"]\n new_action_data = action[\"start_function\"](action_data)\n\n print(\"Action has been processed: \" + zone)\n self.actions[zone][\"times_performed\"] = actions[zone][\"times_performed\"] + 1\n self.actions[zone][\"action_settings\"] = new_action_data\n\n def assignSeverSwap(self, server_swap):\n self.server_swap = server_swap\n\n\n# --------------------------------------------\n# --------------------------------------------\n# --------------------------------------------\n# --------------------------------------------\n# --------------------------------------------\n# --------------------------------------------\n\n def startQueue(self):\n print(\"I've started running\")\n actions = self.queue_processor.actions\n run_actions = self.run_actions\n while True:\n for item in actions:\n if item in run_actions:\n print(\"Processing action: \" + item)\n actions[item]()\n print(\"Action finished processing: \" + item)\n else:\n print(\"Not processing action: \" + item)\n break\n\n def test(self):\n print(\"testing bot 123\")\n","sub_path":"Firestone/actors/Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":4336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"125184662","text":"#!/usr/bin/env python\n# encoding: utf-8\n# author: xiaofangliu\nimport os\nimport logging\n\nfrom logging_conf import log_init\n\nlog_init()\n\nlogger = logging.getLogger(__file__)\n\nif __name__ == '__main__':\n def os_execute_command(path, command):\n print(path, command)\n result = False\n if command != '' and path != '':\n try:\n os.chdir(path)\n command_result = os.popen(command)\n result = command_result.read()\n # print(result)\n except Exception as e:\n print(e)\n logger.error(e.__str__())\n _pwd = os.getcwd()\n logger.error(u'您的项目路径为 %s, 当前路径为 %s, 当前命令为 %s; '\n '请确认 Git的执行路径是否正确。。。' % (\n path, _pwd, command))\n print(u'您的项目路径为 %s, 当前路径为 %s, 当前命令为 %s; '\n '请确认 Git的执行路径是否正确。。。' % (\n path, _pwd, command))\n\n else:\n logger.error(u'参数不能为空。。。')\n print(u'参数不能为空。。。')\n\n return result\n all_branch = 'git branch -a'\n all_branch_list = os_execute_command('/tmp/xiaofangl/.repo/manifests',\n all_branch)\n res = {}\n for one_branch in all_branch_list.split('\\n'):\n if one_branch:\n print('++++' * 20)\n logger.debug(\"this branch is %s\" % one_branch)\n if one_branch.split()[-1].split(')')[0]:\n print(one_branch, one_branch.split()[-1].split(')')[0])\n get_manifests = (\"git log %s --pretty=oneline | \"\n \"grep 'Daily_build:save' | \"\n \"awk '{print $3}'\" % (\n one_branch.split()[-1].split(')')[0]))\n os_execute_command('/tmp/xiaofangl/.repo/manifests',\n 'git checkout %s' %\n one_branch.split()[-1].split(')')[0])\n\n _build = os_execute_command('/tmp/xiaofangl/.repo/manifests',\n get_manifests)\n if not _build:\n logger.warning('this branch not daily_build ===>>> %s' %\n one_branch)\n else:\n build_list = _build.split('\\n')\n logger.info('this branch have daily_build ===>>>'\n ' %s; the manifest is %s' %\n (one_branch, build_list[0]))\n res[one_branch.split()[-1].split(')')[0]] = _build\n print(res)\n","sub_path":"change_log_utils/branch_check.py","file_name":"branch_check.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"262176160","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# This file is part of the minifold project.\n# https://github.com/nokia/minifold\n\n__author__ = \"Marc-Olivier Buob, Fabien Mathieu\"\n__maintainer__ = \"Marc-Olivier Buob\"\n__email__ = \"marc-olivier.buob@nokia-bell-labs.com, fabien.mathieu@nokia-bell-labs.com\"\n__copyright__ = \"Copyright (C) 2018, Nokia\"\n__license__ = \"BSD-3\"\n\nimport requests\nfrom .log import Log\nfrom .singleton import Singleton\n\nclass Proxy(dict, metaclass=Singleton):\n pass\n\ndef proxy_enable(host :str, port :int, protocols :list = [\"http\", \"https\"]):\n proxy = Proxy()\n for protocol in protocols:\n url = \"%s://%s:%s\" % (protocol, host, port)\n proxy[protocol] = url\n\ndef proxy_disable():\n proxy = Proxy()\n proxy.clear()\n\ndef make_session() -> requests.Session:\n session = requests.Session()\n proxy = Proxy()\n if proxy:\n Log.info(\"Setting proxy = %s\" % proxy)\n session.proxies.update(proxy)\n return session\n\n#---------------------------------------------------------------\n# Example to use a local proxy\n#---------------------------------------------------------------\n\nPROXY_LOCALHOST_IP = \"127.0.0.1\"\nPROXY_LOCALHOST_PORT = 8080\n\ndef proxy_enable_localhost():\n proxy_enable(PROXY_LOCALHOST_IP, PROXY_LOCALHOST_PORT)\n","sub_path":"src/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"454660331","text":"# ライブラリのインポート\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import ConvLSTM2D\n\n# Encoder層を実装する\nEncoder = Sequential()\nEncoder.add(ConvLSTM2D(\n filters=20, kernel_size=(3, 3), padding='same', return_sequences=____,\n activation='tanh', recurrent_activation='sigmoid',\n input_shape=(24, 33, 25, 1)))\n\n# Decoder層を実装する\nDecoder = Sequential()\nDecoder.add(ConvLSTM2D(\n filters=20, kernel_size=(3, 3), padding='same', return_sequences=____,\n activation='tanh', recurrent_activation='sigmoid',\n input_shape=(24, 33, 25, 20)))\n\n\nprint(Encoder.summary())\nprint(Decoder.summary())\n\n# ライブラリのインポート\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Lambda\n\ndef repeat_last_status(x):\n \n # 1. 時系列方向の次元を復活させる\n x = tf.reshape(x, (-1, 1, 33, 25, 20))\n \n # tf.Tensor型のデータをコピーし、新しいオブジェクトとして生成する\n copied_x = tf.identity(x)\n \n # 時系列方向を軸とした連結を23回繰り返す\n for _ in range(23):\n \n x = tf.concat([x, copied_x], axis=1)\n \n return x\n\n# Sequentialのインスタンスを生成することで、モデルの雛形とする\nmodel = Sequential()\n# Lambda層を実装する\nmodel.add(Lambda(repeat_last_status))\n\n\n# 次元数が4の配列xを生成\nx = tf.ones((10, 33, 25, 20))\n\n# ライブラリのインポート\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import TimeDistributed, Conv2D\n\n# Sequentialのインスタンスを生成することで、モデルの雛形とする\nmodel = Sequential()\n\n# TimeDistributedでラップされたConv2Dを実装する\nmodel.add(TimeDistributed(Conv2D(filters=1, kernel_size=(1, 1), activation='sigmoid'),\n input_shape=(24, 33, 25, 20)))\n\nmodel = Sequential()\n\n# Encoder\nmodel.add(ConvLSTM2D(\n filters=20, kernel_size=(3, 3), \n padding='same', return_sequences=False,\n activation='tanh', recurrent_activation='sigmoid',\n input_shape=(24, 33, 25, 1)))\n\n# EncoderとDecoderをつなぐ中間部分\ndef repeat_last_status(x):\n x = tf.reshape(x, (-1, 1, 33, 25, 20))\n copied_x = tf.identity(x)\n for _ in range(23):\n x = tf.concat([x, copied_x], axis=1) \n return x\nmodel.add(Lambda(repeat_last_status))\n\n# Decoder\nmodel.add(ConvLSTM2D(\n filters=20, kernel_size=(3, 3),\n padding='same', return_sequences=True,\n activation='tanh', recurrent_activation='sigmoid')) \n\n# 出力層\nmodel.add(TimeDistributed(Conv2D(filters=1, kernel_size=(1, 1), activation='sigmoid')))\n \n\n# モデルをコンパイルする\nmodel.compile(loss='mae', optimizer='adam')\n\n# EarlyStoppingのインポート\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n# EarlyStoppingのインスタンスを生成する\ne_stopping = EarlyStopping(monitor='val_loss', patience=10)\n\n# ModelCheckpointのインポート\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n\n# ModelCheckpointのインスタンスを生成する\ncheckpoint = ModelCheckpoint(filepath='my_model_Epoch{epoch}_loss{loss:.4f}_valloss{val_loss:.4f}.h5',\n monitor='val_loss', save_best_only=True, save_weights_only=True)\n\n# 検証用データをタプルにまとめる\nvalidation_data = (X_val, Y_val)\n\n# EarlyStoppingの設定\ne_stopping = EarlyStopping(monitor='val_loss', patience=30)\n\n# Checkpointの設定\ncheckpoint = ModelCheckpoint(filepath='my_model_Epoch{epoch}_loss{loss:.4f}_valloss{val_loss:.4f}.h5',\n monitor='val_loss', save_best_only=True, save_weights_only=True)\n \n# callbacksをリストにまとめる\ncallbacks = [e_stopping, checkpoint]\n\n# 学習を実行する\nmodel.fit(x=X_train, y=Y_train, batch_size=16, epochs=1,\n validation_data=validation_data, callbacks=callbacks)\n\n# 学習済みのパラメータを読み込む\nmodel.load_weights('my_params.h5')\n\n# 推論を実行し、テスト用データの予測値を生成する\nY_pred = model.predict(X_test)\n","sub_path":"model_pytorch/model_pytorch_image_list/model_pytorch_image_convlstm.py","file_name":"model_pytorch_image_convlstm.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433270646","text":"\nclass Gym(object):\n def __init__(self):\n self.allMyCustomers = []\n self.elementDic = {'gender': 1, 'age': 2,\n 'sales': 3, 'bmi': 4, 'income': 5}\n\n def add(self, myID, gender, age, mySales, BMI, income):\n \"\"\"TestCase for add\n >>> aGym = Gym()\n >>> aGym.add(\"A057\", \"M\", \"32\", \"001\", \"Obesity\", \"86\")\n >>> print(aGym.allMyCustomers[0].id)\n A057\n >>> print(aGym.allMyCustomers[0].gender)\n M\n >>> print(aGym.allMyCustomers[0].age)\n 32\n >>> print(aGym.allMyCustomers[0].sales)\n 001\n >>> print(aGym.allMyCustomers[0].bmi)\n Obesity\n >>> print(aGym.allMyCustomers[0].income)\n 86\n \"\"\"\n newCustomer = Person(myID, gender, age, mySales, BMI, income)\n self.allMyCustomers.append(newCustomer)\n\n def print(self):\n result = ''\n for person in self.allMyCustomers:\n result += str(person) + \"\\n\"\n return result\n\n def get(self, arg):\n \"\"\"TestCase for get\n >>> aGym = Gym()\n >>> aGym.add(\"A057\", \"M\", \"32\", \"001\", \"Obesity\", \"86\")\n >>> aGym.add(\"A057\", \"F\", \"32\", \"001\", \"Obesity\", \"86\")\n >>> aGym.get('gender')\n {'M': 1, 'F': 1}\n \"\"\"\n for key in self.elementDic:\n if (arg == key):\n n = self.elementDic[key]\n d = {}\n for person in self.allMyCustomers:\n c = person.get()[n].upper()\n if c not in d.keys():\n d[c] = 1\n else:\n d[c] += 1\n return d\n\n\nclass Person(object):\n def __init__(self, myID, gender, age, mySales, BMI, income):\n self.id = myID\n self.gender = gender\n self.age = age\n self.sales = mySales\n self.bmi = BMI\n self.income = income\n\n def get(self):\n \"\"\"TestCase for get\n >>> aPerson = Person(\"A057\", \"M\", \"32\", \"001\", \"Obesity\", \"86\")\n >>> aPerson.get()\n ['A057', 'M', '32', '001', 'Obesity', '86']\n \"\"\"\n return [self.id, self.gender, self.age,\n self.sales, self.bmi, self.income]\n\n def __str__(self):\n return self.id + self.gender +\\\n self.age + self.sales + self.bmi + self.income\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod(verbose=True)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"77046310","text":"# ----------------\nprint(\"\\n-----\\n\")\n# ----------------\n\nprint(\n \"ex_153: \\\nDéfinissez une classe Domino() qui permette d'instancier des objets simulant \\\nles pièces d'un jeu de dominos. Le constructeur de cette classe initialisera \\\nles valeurs des points présents sur les deux faces A et B du domino (valeurs \\\npar défaut = 0). \\\nDeux autres méthodes seront définies : \\\nune méthode affiche_points() qui affiche les points présents sur les deux faces\\\nune méthode valeur() qui renvoie la somme des points présents sur les 2 faces.\\n\"\n)\n\n\nclass Domino:\n\n def __init__(self, pa, pb):\n self.pa, self.pb = pa, pb\n\n def affiche_points(self):\n print('Face A : ', self.pa)\n print('Face B : ', self.pb)\n\n def valeur(self):\n return self.pa + self.pb\n\n# Programme de test :\n\n\nd1 = Domino(2, 6)\nd2 = Domino(4, 3)\n\nd1.affiche_points()\nd2.affiche_points()\n\nprint(\"Total des points : \", d1.valeur() + d2.valeur())\n\nliste_domino = []\nfor i in range(7):\n liste_domino.append(Domino(6, i))\n\nvt = 0\nfor i in range(7):\n liste_domino[i].affiche_points()\n vt = vt + liste_domino[i].valeur()\n\nprint(\"valeur totale des points\", vt)\n\n# ----------------\nprint(\"\\n-----\\n\")\n# ----------------\n\nprint(\n \"ex_155: \\\nDéfinissez une classe Voiture() qui permette d'instancier des objets \\\nreproduisant le comportement de voitures automobiles. Le constructeur de cette \\\nclasse initialisera les attributs d'instance suivants, avec les valeurs par \\\ndéfaut indiquées : \\\nmarque = 'Ford', couleur = 'rouge', pilote = 'personne', vitesse = 0. \\\nLorsque l'on instanciera un nouvel objet Voiture(), on pourra choisir sa \\\nmarque et sa couleur, mais pas sa vitesse, ni le nom de son conducteur. \\\nLes méthodes suivantes seront définies : \\\n- choix_conducteur(nom) permettra de désigner (ou changer) le nom du conducteur\\\n- accelerer(taux, duree) permettra de faire varier la vitesse de la voiture. La\\\nvariation de vitesse obtenue sera égale au produit : taux x duree. Par exemple,\\\nsi la voiture accélère au taux de 1,3 m/s2 pendant 20 secondes, son gain de \\\nvitesse doit être égal à 26 m/s. Des taux négatifs seront acceptés (ce qui \\\npermettra de décélérer). La variation de vitesse ne sera pas autorisée si le \\\nconducteur est 'personne'. \\\n- affiche_tout() permettra de faire apparaître les propriétés présentes de la \\\nvoiture, c'est-àdire sa marque, sa couleur, le nom de son conducteur, sa \\\nvitesse.\\n\"\n)\n\n\nclass Voiture:\n def __init__(self, marque='Ford', couleur='rouge'):\n self.marque = marque\n self.couleur = couleur\n self.pilote = 'personne'\n self.vitesse = 0\n\n def accelerer(self, taux, duree):\n if self.pilote == 'personne':\n print(\"Cette voiture n'a pas de conducteur !\")\n else:\n self.vitesse = self.vitesse + taux * duree\n\n def choix_conducteur(self, nom):\n self.pilote = nom\n\n def affiche_tout(self):\n print(\"{} {} pilotée par {}, vitesse = {} m/s\".format(self.marque,\n self.couleur,\n self.pilote,\n self.vitesse))\n\n\na1 = Voiture('Peugeot', 'bleue')\na2 = Voiture(couleur='verte')\na3 = Voiture('Mercedes')\na1.choix_conducteur('Roméo')\na2.choix_conducteur('Juliette')\na2.accelerer(1.8, 12)\na3.accelerer(1.9, 11)\na2.affiche_tout()\na3.affiche_tout()\n\n# ----------------\nprint(\"\\n-----\\n\")\n# ----------------\n\nprint(\n \"ex_156: \\\nDéfinissez une classe Satellite() qui permette d'instancier des objets \\\nsimulant des satellites artificiels lancés dans l'espace, autour de la terre. \\\nLe constructeur de cette classe initialisera les attributs d'instance suivants,\\\navec les valeurs par défaut indiquées : masse = 100, vitesse = 0. \\\nLorsque l'on instanciera un nouvel objet Satellite(), on pourra choisir son \\\nnom, sa masse et sa vitesse. \\\nLes méthodes suivantes seront définies : \\\n- impulsion(force, duree) permettra de faire varier la vitesse du satellite. \\\nPour savoir comment, rappelez-vous votre cours de physique. \\\nPar exemple : un satellite de 300 kg qui subit une force de 600 Newtons \\\npendant 10 secondes voit sa vitesse augmenter (ou diminuer) de 20 m/s. \\\n- affiche_vitesse() affichera le nom du satellite et sa vitesse courante. \\\n- energie() renverra au programme appelant la valeur de l'énergie cinétique du \\\nsatellite.\\n\"\n)\n\n\nclass Satellite:\n def __init__(self, nom, masse=100, vitesse=0):\n self.nom = nom\n self.masse = masse\n self.vitesse = vitesse\n\n def impulsion(self, force, duree):\n self.vitesse = self.vitesse + force * duree / self.masse\n\n def energie(self):\n return self.masse * self.vitesse**2 / 2\n\n def affiche_vitesse(self):\n print(\"Vitesse du satellite {} = {} m/s\".format(self.nom, self.vitesse))\n\n# Programme de test :\n\n\ns1 = Satellite('Zoé', masse=250, vitesse=10)\ns1.impulsion(500, 15)\ns1.affiche_vitesse()\nprint(s1.energie())\ns1.impulsion(500, 15)\ns1.affiche_vitesse()\nprint(s1.energie())\n\n# ----------------\nprint(\"\\n-----\\n\")\n# ----------------\n\nprint(\n \"ex_157: \\\nDéfinissez une classe Cercle(). Les objets construits à partir de cette classe\\\nseront des cercles de tailles variées. En plus de la méthode constructeur \\\n(qui utilisera donc un paramètre rayon), vous définirez une méthode surface(),\\\nqui devra renvoyer la surface du cercle. Définissez ensuite une classe \\\nCylindre() dérivée de la précédente. Le constructeur de cette nouvelle classe \\\ncomportera les deux paramètres rayon et hauteur. Vous y ajouterez une méthode \\\nvolume() qui devra renvoyer le volume du cylindre. (Rappel : Volume d'un \\\ncylindre = surface de section x hauteur).\\n\"\n \"ex_158: \\\nComplétez l'exercice précédent en lui ajoutant encore une classe Cone(), qui \\\ndevra dériver cette fois de la classe Cylindre(), et dont le constructeur \\\ncomportera lui aussi les deux paramètres rayon et hauteur. Cette nouvelle \\\nclasse possédera sa propre méthode volume(), laquelle devra renvoyer le volume\\\ndu cône. (Rappel : Volume d'un cône = volume du cylindre correspondant divisé \\\npar 3).\\n\"\n)\n\n\n# Classes dérivées - polymorphisme\nclass Cercle:\n def __init__(self, rayon):\n self.rayon = rayon\n\n def surface(self):\n return 3.1416 * self.rayon**2\n\n\nclass Cylindre(Cercle):\n def __init__(self, rayon, hauteur):\n Cercle.__init__(self, rayon)\n self.hauteur = hauteur\n\n def volume(self):\n # la méthode surface() est héritée de la classe parente\n return self.surface() * self.hauteur\n\n\nclass Cone(Cylindre):\n def __init__(self, rayon, hauteur):\n Cylindre.__init__(self, rayon, hauteur)\n\n def volume(self):\n # cette nouvelle méthode volume() remplace celle que\n # l'on a héritée de la classe parente (exemple de polymorphisme)\n return Cylindre.volume(self) / 3\n\n\ncyl = Cylindre(5, 7)\nprint(cyl.surface())\nprint(cyl.volume())\nco = Cone(5, 7)\nprint(co.surface())\nprint(co.volume())\n\n# ----------------\nprint(\"\\n-----\\n\")\n# ----------------\n\nprint(\n \"ex_159: \\\nDéfinissez une classe JeuDeCartes() permettant d'instancier des objets « jeu \\\nde cartes » dont le comportement soit similaire à celui d'un vrai jeu de \\\ncartes. La classe devra comporter au moins les trois méthodes suivantes : \\\n- méthode constructeur : création et remplissage d'une liste de 52 éléments, \\\nqui sont euxmêmes des tuples de 2 éléments contenant les caractéristiques de \\\nchacune des 52 cartes. \\\nPour chacune d'elles, il faut en effet mémoriser séparément un nombre entier \\\nindiquant la valeur (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, les 4 \\\ndernières valeurs étant celles des valet, dame, roi et as), et un autre nombre\\\nentier indiquant la couleur de la carte (c'est-à-dire 3,2,1,0 pour Cœur, \\\nCarreau, Trèfle & Pique). \\\nDans une telle liste, l'élément (11,2) désigne donc le valet de Trèfle, et la \\\nliste terminée doit être du type : [(2, 0), (3,0), (3,0), (4,0), ... ... \\\n(12,3), (13,3), (14,3)] \\\n- méthode nom_carte() : cette méthode renvoie sous la forme d'une chaîne \\\nl'identité d'une carte quelconque, dont on lui a fourni le tuple descripteur \\\nen argument. Par exemple, l'instruction : \\\nprint jeu.nom_carte((14, 3)) doit provoquer l'affichage de : As de pique \\\n- méthode battre() : comme chacun sait, battre les cartes consiste à les \\\nmélanger. Cette méthode sert donc à mélanger les éléments de la liste \\\ncontenant les cartes, quel qu'en soit le nombre. \\\n- méthode tirer() : lorsque cette méthode est invoquée, une carte est retirée \\\ndu jeu. Le tuple contenant sa valeur et sa couleur est renvoyé au programme \\\nappelant. On retire toujours la première carte de la liste. Si cette méthode \\\nest invoquée alors qu'il ne reste plus aucune carte dans la liste, il faut \\\nalors renvoyer l'objet spécial None au programme appelant.\\n\"\n)\n# Tirage de cartes\nfrom random import randrange\n\n\nclass JeuDeCartes():\n \"\"\"Jeu de cartes\"\"\"\n # attributs de classe (communs à toutes les instances) :\n couleur = ('Pique', 'Trèfle', 'Carreau', 'Coeur')\n valeur = (0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'valet', 'dame', 'roi', 'as')\n\n def __init__(self):\n \"\"\"Construction de la liste des 52 cartes\"\"\"\n self.carte = []\n for coul in range(4):\n for val in range(13):\n # la valeur commence à 2\n self.carte.append((val + 2, coul))\n\n def nom_carte(self, c):\n \"\"\"Renvoi du nom de la carte c, en clair\"\"\"\n return \"{} de {}\".format(self.valeur[c[0]], self.couleur[c[1]])\n\n def battre(self):\n \"\"\"Mélange des cartes\"\"\"\n # nombre de cartes restantes\n t = len(self.carte)\n # pour mélanger, on procède à un nombre d'échanges équivalent :\n for i in range(t):\n # tirage au hasard de 2 emplacements dans la liste :\n h1, h2 = randrange(t), randrange(t)\n # échange des cartes situées à ces emplacements :\n self.carte[h1], self.carte[h2] = self.carte[h2], self.carte[h1]\n\n def tirer(self):\n \"\"\"Tirage de la première carte de la pile\"\"\"\n # vérifier qu'il reste des cartes\n t = len(self.carte)\n if t > 0:\n # choisir la première carte du jeu\n carte = self.carte[0]\n # la retirer du jeu\n del(self.carte[0])\n # en renvoyer copie au prog. appelant\n return carte\n else:\n # facultatif\n return None\n\n\n# Programme test :\nif __name__ == '__main__':\n # instanciation d'un objet\n jeu = JeuDeCartes()\n # mélange des cartes\n jeu.battre()\n # tirage des 52 cartes :\n for n in range(53):\n c = jeu.tirer()\n # il ne reste aucune carte dans la liste\n if c is None:\n print('Terminé !')\n else:\n # valeur et couleur de la carte\n print(jeu.nom_carte(c))\n\n# ----------------\nprint(\"\\n-----\\n\")\n# ----------------\n\nprint(\n \"ex_160: \\\nComplément de l'exercice précédent : Définir deux joueurs A et B. Instancier \\\ndeux jeux de cartes (un pour chaque joueur) et les mélanger. Ensuite, à l'aide\\\nd'une boucle, tirer 52 fois une carte de chacun des deux jeux et comparer \\\nleurs valeurs. Si c'est la première des 2 qui a la valeur la plus élevée, on \\\najoute un point au joueur A. Si la situation contraire se présente, on ajoute \\\nun point au joueur B. Si les deux valeurs sont égales, on passe au tirage \\\nsuivant. Auterme de la boucle, comparer les comptes de A et B pour déterminer \\\nle gagnant.\\n\"\n)\n# On supposera que l'exercice précédent a été sauvegardé sous le nom cartes.py\n# Bataille de de cartes\nfrom cartes import JeuDeCartes\n\n# instanciation du premier jeu\njeuA = JeuDeCartes()\n# instanciation du second jeu\njeuB = JeuDeCartes()\n# mélange de chacun\njeuA.battre()\njeuB.battre()\n# compteurs de points des joueurs A et B\npA, pB = 0, 0\n\n# tirer 52 fois une carte de chaque jeu :\nfor n in range(52):\n cA, cB = jeuA.tirer(), jeuB.tirer()\n # valeurs de ces cartes\n vA, vB = cA[0], cB[0]\n if vA > vB:\n pA += 1\n elif vB > vA:\n pB += 1\n # (rien ne se passe si vA = vB)\n # affichage des points successifs et des cartes tirées :\n print(\"{} * {} ==> {} * {}\".format(jeuA.nom_carte(cA), jeuB.nom_carte(cB),\n pA, pB))\n\nprint(\"le joueur A obtient {} points, le joueur B en obtient {}.\".format(pA,\n pB))\n","sub_path":"pyNutz/001_Apprendre_a_programmer_avec_Python/Chapitre 12 - Classes_méthodes_héritage/classes_methodes_heritage.py","file_name":"classes_methodes_heritage.py","file_ext":"py","file_size_in_byte":12666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203981732","text":"import logging, gensim, bz2\n\n\ndef train_from_data():\n\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n # load id->word mapping (the dictionary), one of the results of step 2 above\n id2word = gensim.corpora.Dictionary.load_from_text('./ML/data/Sample/2017-6_wordids.txt')\n # load corpus iterator\n mm = gensim.corpora.MmCorpus('./ML/data/Sample/2017-6_tfidf.mm')\n # mm = gensim.corpora.MmCorpus(bz2.BZ2File('wiki_en_tfidf.mm.bz2')) # use this if you compressed the TFIDF output\n print(mm)\n lsi = gensim.models.lsimodel.LsiModel(corpus=mm, id2word=id2word, num_topics=400)\n lsi.print_topics(10)\n lsi.save('./ML/data/model/model')\n\nif __name__ == '__main__':\n train_from_data()","sub_path":"ML/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52574827","text":"import os\nfrom datetime import datetime\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask import (\n Flask,\n url_for,\n render_template,\n redirect,\n request,\n flash\n)\n\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URL'] = os.environ.get('DATABASE_URL')\n\ndb = SQLAlchemy(app)\n\n\n@app.route('/')\ndef home():\n return render_template('application.html')\n\n@app.route('/apply', methods=['GET','POST'])\ndef apply():\n if request.method == 'POST':\n hacker = Hacker.from_forms(request.form)\n return str(hacker)\n else:\n return render_template('apply.html')\n\n\n@app.route('/faq')\ndef faq():\n return render_template('faq.html')\n\n@app.route('/teach')\ndef teach():\n if request.method == 'GET':\n return render_template('teach.html')\n else:\n pass\n\n\n# Models, models.\nclass Hacker(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n\n # Personal.\n nickname = db.Column(db.String(100), unique=True, nullable=False)\n email = db.Column(db.String, unique=True, nullable=False)\n phone = db.Column(db.String, unique=True, nullable=False)\n\n # Social.\n github = db.Column(db.String(100), unique=True)\n twitter = db.Column(db.String(100), unique=True)\n linkedin = db.Column(db.String, unique=True)\n\n # Bio and extras.\n ambition = db.Column(db.Text, nullable=False)\n program = db.Column(db.Text, nullable=False)\n expectation = db.Column(db.Text, nullable=False)\n\n created_at = db.Column(db.DateTime, default=datetime.utcnow)\n\n\n def __init__(self, nickname, email, github, twitter=None, linkedin=None):\n self.nickname = nickname\n self.email = email\n self.github = github\n\n\n @classmethod\n def from_forms(cls, form):\n # Create a new hacker from the form data.\n pass\n\n def __repr__(self): return '' % self.github\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"621168847","text":"import re\r\nclass Solution(object):\r\n def lengthOfLastWord(self, s):\r\n \"\"\"\r\n :type s: str\r\n :rtype: int\r\n \"\"\"\r\n string = s\r\n\r\n strList = s.split()\r\n n = len(strList)\r\n listN = []\r\n for i in range(0, n):\r\n listN.append(len(strList[i]))\r\n \r\n return listN[-1]\r\n \r\n\r\nMy = Solution()\r\nstr = u\"Hello World a \"\r\nstr1 = u\"a \"\r\nprint(My.lengthOfLastWord(str1))\r\n","sub_path":"src/LengthofLastWord/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112075646","text":"import numpy as np\nimport itertools as it\n\nfrom scene import Scene\nfrom graphs import *\n\nfrom mobject import *\nfrom animation import *\nfrom region import *\nfrom constants import *\nfrom helpers import *\n\nclass RearrangeEquation(Scene):\n def construct(\n self, \n start_terms, \n end_terms, \n index_map,\n size = None,\n path = counterclockwise_path,\n start_transform = None,\n end_transform = None,\n leave_start_terms = False,\n transform_kwargs = {},\n ):\n transform_kwargs[\"interpolation_function\"] = path\n start_mobs, end_mobs = self.get_mobs_from_terms(\n start_terms, end_terms, size\n )\n if start_transform:\n start_mobs = start_transform(CompoundMobject(*start_mobs)).split()\n if end_transform:\n end_mobs = end_transform(CompoundMobject(*end_mobs)).split()\n unmatched_start_indices = set(range(len(start_mobs)))\n unmatched_end_indices = set(range(len(end_mobs)))\n unmatched_start_indices.difference_update(\n [n%len(start_mobs) for n in index_map]\n )\n unmatched_end_indices.difference_update(\n [n%len(end_mobs) for n in index_map.values()]\n )\n mobject_pairs = [\n (start_mobs[a], end_mobs[b])\n for a, b in index_map.iteritems()\n ]+ [\n (Point(end_mobs[b].get_center()), end_mobs[b])\n for b in unmatched_end_indices\n ]\n if not leave_start_terms:\n mobject_pairs += [\n (start_mobs[a], Point(start_mobs[a].get_center()))\n for a in unmatched_start_indices\n ] \n\n self.add(*start_mobs)\n if leave_start_terms:\n self.add(CompoundMobject(*start_mobs))\n self.dither()\n self.animate(*[\n Transform(*pair, **transform_kwargs)\n for pair in mobject_pairs\n ])\n self.dither()\n\n\n def get_mobs_from_terms(self, start_terms, end_terms, size):\n \"\"\"\n Need to ensure that all image mobjects for a tex expression\n stemming from the same string are point-for-point copies of one\n and other. This makes transitions much smoother, and not look\n like point-clouds.\n \"\"\"\n num_start_terms = len(start_terms)\n all_mobs = np.array(\n tex_mobject(start_terms, size = size).split() + \\\n tex_mobject(end_terms, size = size).split()\n )\n all_terms = np.array(start_terms+end_terms)\n for term in set(all_terms):\n matches = all_terms == term\n if sum(matches) > 1:\n base_mob = all_mobs[list(all_terms).index(term)]\n all_mobs[matches] = [\n deepcopy(base_mob).replace(target_mob)\n for target_mob in all_mobs[matches]\n ]\n return all_mobs[:num_start_terms], all_mobs[num_start_terms:]\n\n\n\n\n\n\n","sub_path":"scene/arithmetic_scenes.py","file_name":"arithmetic_scenes.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496858312","text":"import turtle\n\ndef draw_circle():\n window=turtle.Screen()\n window.bgcolor(\"yellow\")\n\n pan=turtle.Turtle()\n\n a=60\n\n pan.color(\"red\")\n pan.pensize(1)\n \n\n for n in range(1,11):\n \n pan.forward(100)\n pan.left(105)\n pan.forward(50)\n pan.right(75)\n pan.backward(100)\n pan.left(45)\n\n pan.right(120)\n pan.forward(200)\n \n window.exitonclick()\n\ndraw_circle()\n","sub_path":"paint4.py","file_name":"paint4.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"244505284","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.datasets import make_classification\nfrom sklearn.cross_validation import train_test_split\n\n#Variables\nTEST_SIZE = 0.1\nNUMBER_OF_SAMPLES_CV = 90\nNUMBER_OF_FEATURES_CV = 100\nNUMBER_OF_CLASSES_CV = 3\n\n# import data\ndef import_data():\n data=pd.read_table('Complied-Data.txt', sep='\\t', delimiter=None, delim_whitespace=False, header=0, index_col=0)\n X = (data.iloc[0:100, 1:-1])\n y = data.iloc[0:100,0]\n return(X,y)\n\n# returns train and test set\ndef split_data():\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TEST_SIZE, random_state=0)\n return(X_train, X_test, y_train, y_test)\n \ndef SVC_crossvalidation(X,y):\n # Build a classification task using 3 informative features\n X, y = make_classification(n_samples=NUMBER_OF_SAMPLES_CV, n_features=NUMBER_OF_FEATURES_CV, n_informative=3,\n n_redundant=2, n_repeated=0, n_classes=NUMBER_OF_CLASSES_CV,\n n_clusters_per_class=1, random_state=0)\n # Create the RFE object and compute a cross-validated score.\n svc = SVC(kernel=\"linear\")\n # The \"accuracy\" scoring is proportional to the number of correct\n # classifications\n rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(2), scoring='accuracy')\n rfecv.fit(X, y)\n print(\"Optimal number of features : %d\" % rfecv.n_features_)\n # Plot number of features VS. cross-validation scores\n plt.figure()\n plt.xlabel(\"Number of features selected\")\n plt.ylabel(\"Cross validation score (nb of correct classifications)\")\n plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)\n plt.show()\n\n# main\nX,y = import_data()\nX_train, X_test, y_train, y_test = split_data()\nSVC_crossvalidation(X_train, y_train)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"525619786","text":"import os\nfrom typing import TypeVar\nfrom notebook.utils import url_path_join\nfrom notebook.base.handlers import IPythonHandler\nfrom ament_index_python.packages import get_package_prefix\nfrom jupyros import _version\n\n# Used for documentation purposes only\nNotebookWebApplicationType = TypeVar('NotebookWebApplicationType')\n\n__version__ = _version.__version__\n\n\nclass ROSStaticHandler(IPythonHandler):\n \"\"\" ROS Static Handler \"\"\"\n def get(self, *args, **kwargs) -> None:\n if not args:\n self.write(\"Error - no argument supplied\")\n argslist = args[0].split('/')\n package, rest = argslist[0], '/'.join(argslist[1:])\n\n file = os.path.join(get_package_prefix(package), rest)\n try:\n with open(file, 'rb') as f:\n data = f.read()\n self.write(data)\n except FileNotFoundError:\n self.write(\"Error opening file %s\" % file)\n\n self.finish()\n\n\ndef load_jupyter_server_extension(\n nb_server_app: NotebookWebApplicationType) -> None:\n \"\"\"\n Called when the extension is loaded.\n\n Args:\n nb_server_app (NotebookWebApplication): handle to the Notebook webserver\n instance.\n \"\"\"\n web_app = nb_server_app.web_app\n host_pattern = '.*$'\n route_pattern = url_path_join(web_app.settings['base_url'], '/rospkg/(.*)')\n web_app.add_handlers(host_pattern, [(route_pattern, ROSStaticHandler)])\n","sub_path":"jupyros/server_extension.py","file_name":"server_extension.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513709410","text":"# https://www.acmicpc.net/problem/14888\n\nN = int(input())\nA_list = list(map(int, input().split()))\nplus, minus, mul, div = map(int, input().split())\n\nmax_num = -float(\"inf\")\nmin_num = float(\"inf\")\n\n\ndef dfs(sums, pl, mi, mu, di, cnt):\n global min_num, max_num\n if cnt == N:\n min_num = min(min_num, sums)\n max_num = max(max_num, sums)\n return\n\n if pl:\n dfs(sums + A_list[cnt], pl - 1, mi, mu, di, cnt + 1)\n if mi:\n dfs(sums - A_list[cnt], pl, mi - 1, mu, di, cnt + 1)\n if mu:\n dfs(sums * A_list[cnt], pl, mi, mu - 1, di, cnt + 1)\n if di:\n if sums < 0:\n tmp = -sums // A_list[cnt]\n dfs(-tmp, pl, mi, mu, di - 1, cnt + 1)\n else:\n dfs(sums // A_list[cnt], pl, mi, mu, di - 1, cnt + 1)\n\n\ndfs(A_list[0], plus, minus, mul, div, 1)\n\nprint(max_num)\nprint(min_num)\n","sub_path":"BOJ/graph/14888.py","file_name":"14888.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"476176913","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 7 18:37:54 2018\r\n\r\n@author: Lenovo\r\n\"\"\"\r\n\r\nclass Game:\r\n \r\n def __init__(self, character, level):\r\n self.ch = character\r\n self.lvl = level\r\n self.lvlbk = level.create_level_surface()\r\n self.chr = self.ch.ch[0].get_rect()\r\n self.lvlr = self.lvlbk.get_rect()\r\n self.size = width, height = 640, 640\r\n self.bk_grid = [[x,y] for y in range(0, self.lvlr.height, self.chr.width) \r\n for x in range(0, self.lvlr.width, self.chr.height)]\r\n self.tnb = [[x,y] for x in range(0, self.lvlr.width, self.chr.width) \r\n for y in range(0, int(self.size[1]/2) + self.chr.height, self.chr.height)]\r\n self.b = [[x,y] for x in range(0, self.lvlr.width, self.chr.width) \r\n for y in range(self.lvlr.height-int(self.size[1]/2)-self.chr.height, self.lvlr.height, self.chr.height)]\r\n self.tnb += self.b\r\n#print(tnb)\r\n self.lnr = [[x,y] for x in range(0, int(self.size[0]/2), self.chr.width) \r\n for y in range(0, self.lvlr.height, self.chr.height)]\r\n self.r= [[x,y] for x in range(self.lvlr.width - int(self.size[0]/2)-self.chr.height, self.lvlr.width, self.chr.width) \r\n for y in range(0, self.lvlr.height, self.chr.height)]\r\n self.lnr += self.r\r\n self.indy = 0\r\n self.solid_positions = []\r\n\r\n\r\n for i, layer in enumerate(self.lvl.tmx_bk.layers):\r\n try:\r\n if layer.properties['solid']=='true':\r\n for x, y, _ in layer.tiles():\r\n print('yes')\r\n self.solid_positions.append([x*self.chr.width, y*self.chr.width])\r\n except:\r\n pass\r\n#want character rect to be set on start item in item layer 'start_pos' is object \r\n \r\n def blit_level(self):\r\n #finds a x,y value for top corner of levelsurface based on start_pos so map\r\n #is centered properly\r\n lvlx = (self.size[0]/2 - max(self.size[0]/2, min(self.lvl.size[0] - \r\n self.size[0]/2, self.lvl.start_pos[0])))\r\n \r\n lvly = self.size[1]/2 - max(self.size[1]/2, min( self.lvl.size[1] - \r\n self.size[1]/2, self.lvl.start_pos[1]))\r\n \r\n #sets character start positions to half way across and down screen\r\n startx = self.size[0]/2\r\n starty = self.size[1]/2\r\n \r\n #if the screen is at edge, changes character start positions to actual position.\r\n if -lvlx == 0.0 or -lvlx == (self.lvl.size[0] - self.size[0]):\r\n startx = self.lvl.start_pos[0]\r\n if -lvly == 0.0 or -lvly == (self.lvl.size[1] - self.size[1]):\r\n starty = self.lvl.start_pos[1]\r\n \r\n\r\n \r\n screen.blit(self.lvlbk, (lvlx, lvly))\r\n self.lvlr = self.lvlr.move(lvlx, lvly)\r\n \r\n screen.blit(self.ch.ch[0], (startx, starty))\r\n self.chr = self.chr.move(startx, starty) \r\n\r\n pygame.display.update()\r\n print(\"startx: \", startx, \"starty: \", starty)\r\n print(lvlx,lvly)\r\n \r\n #function to set screen position, set character within screen.\r\n #assume co-ordinates are legit.\r\n #if within level_height + or - screen height. blit background, else if \r\n # greter than zero but less than height blit character\r\n \r\n def test(self):\r\n '''returns True when the background should be blitted becasue the charcter \r\n is not in the border'''\r\n combx = self.chr.left-self.lvlr.left\r\n comby = self.chr.top - self.lvlr.top\r\n #if combx + self.ch.width_guy > self.lvlr.width or comby + width_guy > self.lvlr.height:\r\n #return False\r\n #if if combx < 0 or comby < 0:\r\n #return False\r\n if combx < self.lvlr.width- width/2 +self.ch.width_guy and combx > width/2 - self.ch.width_guy:\r\n if comby < self.lvlr.height - height/2 +self.ch.width_guy and comby > height/2 +self.ch.width_guy:\r\n return True\r\n \r\n return False\r\n \r\n def cum_distance(self):\r\n combx = self.chr.left-self.lvlr.left\r\n comby = self.chr.top - self.lvlr.top\r\n return (combx, comby)\r\n \r\n def general_position(self, rect):\r\n combx = rect.left-self.lvlr.left\r\n comby = rect.top - self.lvlr.top\r\n return (combx, comby)","sub_path":"Game/testanim.py","file_name":"testanim.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287464049","text":"\"\"\"copied code since previous script has interpreter issues\"\"\"\n'''\nCreated on Feb 27, 2018\nAuthor: fremorti\n'''\n\nimport random as rnd\nimport numpy as np\nimport os\nimport time\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom mpl_toolkits.mplot3d import Axes3D\n\nplt.style.use('seaborn-talk')\ndefault_path = os.getcwd()\n\n\nclass Individual:\n '''Class that defines an individual as an object'''\n\n def __init__(self,\n x,\n y):\n # Initialization\n self.x = x # location (x, y)\n self.y = y\n\n def move(self, connection, max_x, max_y):\n '''the individual moves'''\n # an individual moves\n i = rnd.choice(*np.where(connection[self.x * max_y + self.y]))\n self.x, self.y = i // max_y, i % max_y\n\n\nclass Metapopulation:\n '''Contains the whole population, regulates daily affairs'''\n\n def __init__(self,\n max_x,\n max_y,\n lambd,\n K,\n d,\n m):\n \"\"\"Initialization\"\"\"\n self.max_x = max_x # number of grid cells along the first dimension of the landscape\n self.max_y = max_y # number of grid cells along the second dimension of the landscape\n self.lambd = lambd # Local optimal growth rate/optimal fecundity\n self.K = K # Local Carrying capacity\n self.d = d # dispersal propensity\n self.m = m # dispersal mortality\n self.population = [] #population object: container for all individuals\n self.localsize = np.zeros((self.max_x, self.max_y)) #keeps track of locl population sizes in all patches\n self.immi = np.zeros((self.max_x, self.max_y)) #keeps track of the number of immigrant into every patch\n self.initialize_pop()\n self.connection_matrix()\n\n def initialize_pop(self):\n '''Initialize starting population'''\n startpop = 0.5 * self.max_x * self.max_y * K # initial metapopulation size\n\n for _ in range(int(startpop)):\n x, y = rnd.randint(0, (self.max_x - 1)), rnd.randint(0, (self.max_y - 1))\n self.population.append(Individual(x, y))\n self.localsize[x, y] += 1\n\n def connection_matrix(self):\n '''defines the connections in the network of patches'''\n self.connection = []\n for x in range(self.max_x):\n for y in range(self.max_y):\n conn = [self.max_y * g + h for g in (x - 1, x, x + 1) for h in (y - 1, y, y + 1) if\n (g, h) != (x, y) and 0 <= g < self.max_x and 0 <= h < self.max_y]\n\n self.connection.append([(i in conn) for i in range(self.max_x * self.max_y)])\n self.connection = np.array(self.connection)\n\n def lifecycle(self):\n '''all actions for all individuals during one time step (1 generation)'''\n\n self.oldpop = self.population[:] #make a copy of the population\n self.oldlocalsize = self.localsize[:]\n self.immi = np.zeros((self.max_x, self.max_y)) # to record immigrants\n\n rnd.shuffle(self.oldpop)\n\n self.new = []\n self.newsize = np.zeros((self.max_x, self.max_y)) # to record local population sizes\n # new generation of population\n self.population = [] #empty this copy of the population to, then, add indivduals of the next generation\n self.localsize = np.zeros((self.max_x, self.max_y))\n\n for ind in self.oldpop:\n # reproduce\n exp_off = r * (1 + (self.oldlocalsize[ind.x, ind.y] * (r - 1)) / a) ** -b # Hassell\n for _ in range(np.random.poisson(max(0, exp_off))):\n new = Individual(ind.x, ind.y)\n # offspring moves\n if self.d > rnd.random():\n new.move(self.connection, self.max_x, self.max_y)\n # dispersal mortality\n if rnd.random() > self.m:\n self.population.append(new)\n self.localsize[new.x, new.y] += 1\n self.immi[new.x, new.y] += 1\n else:\n self.population.append(new)\n self.localsize[new.x, new.y] += 1\n\n\nclass Datacollector:\n '''extracts data during the metapopulation runs, calculates derived metrics and plots'''\n def __init__(self, maxtime, max_x, max_y):\n self.mt = maxtime\n self.max_x = max_x\n self.max_y = max_y\n self.sizesintime = np.zeros((maxtime, max_x, max_y))\n\n def collect(self, time, localsize):\n #collect the array that stores local population size for every time step of a run\n self.sizesintime[time] = localsize\n\n def plotlocal(self):\n '''plots local population sizes in time for every patch'''\n fig, axes = plt.subplots(self.max_x, self.max_y)\n for i, ax in enumerate(axes.flatten()):\n ax.plot(self.sizesintime[:, i // self.max_y, i % self.max_y])\n ax.set_xlabel('time')\n ax.set_title(i)\n\n fig.suptitle('local population sizes')\n plt.tight_layout(rect=[0, 0, 1, 0.97])\n plt.show()\n\n def variabilities(self, extent):\n '''returns alpha, beta and gamma variabilities from the localpopulation sizes per time step for a given window (extent)\n the extent enables to exclude dynamics that occur before stability in the system'''\n reshaped_sizes = np.reshape(self.sizesintime, (self.mt, self.max_x * self.max_y))[int(self.mt - extent):]\n total = np.sum(reshaped_sizes, axis=1)\n total_mean = np.mean(total)\n total_var = np.var(total) / total_mean ** 2\n covars = np.cov(np.transpose(reshaped_sizes))\n alpha = (np.sum(np.diag(covars) ** 0.5) / total_mean) ** 2\n gamma = np.sum(covars) / (total_mean ** 2)\n beta = alpha - gamma\n beta_ = alpha / gamma\n s_corner = np.mean(reshaped_sizes[:,(0,2,6,8)], axis = 0)\n s_side = np.mean(reshaped_sizes[:,(1,3,5, 7)], axis=0)\n s_center = np.mean(reshaped_sizes[:, 4] , axis=0)\n alpha_corner = np.sum(np.std(reshaped_sizes[:, (0, 2, 6, 8)], axis=0) / s_corner)\n alpha_side = np.sum(np.std(reshaped_sizes[:, (1, 3, 5, 7)], axis=0) / s_side)\n alpha_center = np.std(reshaped_sizes[:, 4]) / s_center\n\n return alpha, gamma, beta, beta_, alpha_corner, alpha_side, alpha_center, np.mean(s_corner), np.mean(s_side), np.mean(s_center)\n\n\ndef run(r, K, d, m):\n '''one simulated landscape/metapopulation that returns the datacollector object'''\n meta = Metapopulation(max_x, max_y, r, K, d, m)\n data = Datacollector(maxtime, max_x, max_y)\n # simulate MAXTIME timesteps (print generation time and metapopulation size for quickly checking during runs)\n for timer in range(maxtime):\n meta.lifecycle()\n data.collect(timer, meta.localsize)\n \"\"\"print(meta.localsize)\n unique = np.unique([ind.y+max_y*ind.x for ind in meta.population], return_counts = 1)\n print(np.reshape(unique[1], (max_x, max_y)))\"\"\"\n # print('generation ',timer)\n # print(\"popsize: {}\\n\".format(len(meta.population)))\n # print(f'{meta.localsize[0, 0]}, {meta.localsize[0, 1]}')\n # print(str(time.clock()))\n # data.plotlocal()\n # data.plottotal()\n print(meta.immi)\n return data\n\ndef varplot(data, data_mean, x, y):\n '''plot a variation metric conditional o treatment in the virtual experiment'''\n fig, ax = plt.subplots()\n plot1 = ax.scatter(data[x], data[y])\n plot1_1 = ax.plot(data_mean[x], data_mean[y])\n plt.savefig(f'Hassell/{x}/{y}.png')\n\ndef partplot(data, data_mean, x, y):\n '''plot local metric conditional on the type of position in the landscape (center, side or corner)'''\n disp = {'alphavar': r'$\\alpha$-variation', 'size': 'population size'}\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True)\n ax1.set_title(f'{disp[y]} corner')\n ax2.set_title(f'{disp[y]} side')\n ax3.set_title(f'{disp[y]} center')\n\n ax1.scatter(data[x], data[f'{y} corner'])\n ax1.plot(data_mean[x], data_mean[f'{y} corner'])\n ax2.scatter(data[x], data[f'{y} side'])\n ax2.plot(data_mean[x], data_mean[f'{y} side'])\n ax3.scatter(data[x], data[f'{y} center'])\n ax3.plot(data_mean[x], data_mean[f'{y} center'])\n plt.savefig(f'Hassell/{x}/{y}part.png')\n\ndef replicate_runs(n, v):\n '''define replicated virtual experiment for one of the parameters (dispersal propensity or dispersal mortality)'''\n x_s = []\n y_s = []\n a_s = []\n g_s = []\n b_s = []\n b__s = []\n a_cos = []\n a_sis = []\n a_ces = []\n s_cos = []\n s_sis = []\n s_ces = []\n #virtual treatment levels\n for var in np.arange(0.05, 0.85, 0.05) if v == 'disp_mort' else np.arange(0.05, 1, 0.05):\n #replication\n for i in range(n):\n x_s += [var]\n #start one simulation\n data = run(r, K, var if v == 'disp_prop' else d, var if v == 'disp_mort' else m)\n alph, gam, bet, bet_, a_corner, a_side, a_center, s_corner, s_side, s_center = data.variabilities(maxtime//2)\n a_s += [alph]\n g_s += [gam]\n b_s += [bet]\n b__s += [bet_]\n a_cos += [a_corner]\n a_sis += [a_side]\n a_ces += [a_center]\n s_cos += [s_corner]\n s_sis += [s_side]\n s_ces += [s_center]\n\n print(f'{var}, replicate {i}')\n #construct an easy-to-analyze dataframe\n data = pd.DataFrame({v: x_s,\n 'alphavar': a_s,\n 'gammavar': g_s,\n 'betavar': b_s,\n 'betavar_': b__s,\n 'alphavar corner' : a_cos,\n 'alphavar side' : a_sis,\n 'alphavar center' : a_ces,\n 'size corner' : s_cos,\n 'size side' : s_sis,\n 'size center' : s_ces})\n data_mean = data.groupby(v).mean().reset_index()\n print(data_mean)\n #save an output file\n data.to_csv('var_sims')\n #plots\n varplot(data, data_mean, v, 'alphavar')\n varplot(data, data_mean, v, 'gammavar')\n varplot(data, data_mean, v, 'betavar_')\n partplot(data, data_mean, v, 'size')\n partplot(data, data_mean, v, 'alphavar')\n\n\n\n\n\n##############\n# Parameters #\n##############\nmaxtime = 500\nr, K = 2, 100\nb = 2\na = K * (r - 1) / (r ** (1 / b) - 1)\nd = 0.25\nm = 0.25\nmax_x, max_y = 3, 3\n\n#replicated model runs varied in a gradient of either dispersal ('disp_prop') or dispersal mortality ('disp_mort')\nreplicate_runs(20, 'disp_mort')\n","sub_path":"simulations_output/Metapopulation_variability_model.py","file_name":"Metapopulation_variability_model.py","file_ext":"py","file_size_in_byte":10617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605911311","text":"import unittest\n\nfrom MY_PKG_NAME import *\n\nclass TestClasses(unittest.TestCase):\n \"\"\"\n Tests class X.\n \"\"\"\n def setUp(self):\n \"\"\"\n Initialize test objects.\n \"\"\"\n self.object = MY_CLASS()\n\n def TEST_NAME(self):\n \"\"\"\n Tests `NAME` function.\n \"\"\"\n a=0\n self.assertEqual(0, a)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"517843513","text":"import re\r\nimport random\r\nimport time\r\n#I AM SHAELIN NAIDOO 218003390. I AM THE ORIGINAL ATHOR OF THIS CODE. GITHUB REPOSITORY https://github.com/ShaelinN/PRACS-year-3 , FOLDER NLP_ASSIGNMENT.\r\n\r\ndef toMod():\r\n x = random.randrange(0, 100)\r\n return (x <= 98)\r\ndef timingAllowance(timer,instances):\r\n for i in range(0,5):\r\n time.sleep(timer)\r\n print(\".\",end = '')\r\n print()\r\n \r\n\r\ndef modifier(inputs):\r\n x = inputs.upper()\r\n # pronoun conversion\r\n # second person to place holder\r\n x = re.sub(r\"\\bYOU ARE\\b\", \"2pyou_are\", x)\r\n x = re.sub(r\"\\bYOU'RE\\b\", \"2pyou_re\", x)\r\n x = re.sub(r\"\\bYOU\\b\", \"2pme\", x)\r\n x = re.sub(r\"\\bYOUR\\b\", \"2pmy\", x)\r\n x = re.sub(r\"\\bYOURS\\b\", \"2pmine\", x)\r\n\r\n # first person to seond person\r\n x = re.sub(r\"\\bME\\b\", \"YOU\", x)\r\n x = re.sub(r\"\\bMY\\b\", \"YOUR\", x)\r\n x = re.sub(r\"\\bI\\b\", \"YOU\", x)\r\n x = re.sub(r\"\\bWE\\b\", \"YOU\", x)\r\n\r\n x = re.sub(r\"'M\", \" ARE\", x)\r\n x = re.sub(r\"\\bAM\\b\", \"ARE\", x)\r\n\r\n # place holder to first person\r\n x = re.sub(r\"2pme\", \"ME\", x)\r\n x = re.sub(r\"2pmy\\b\", \"MY\", x)\r\n x = re.sub(r\"2pmine\", \"MINE\", x)\r\n x = re.sub(r\"2pyou_are\", \"I AM\", x)\r\n x = re.sub(r\"2pyou_re\", \"I'M\", x)\r\n \r\n #remove well from beginning sentences\r\n x = re.sub(r\"\\AWELL\\b, \",\"\",x)\r\n \r\n \r\n # keywords\r\n keywords = [\r\n r\"(?:\\bALL\\b)\",\r\n r\"(?:\\bALWAYS\\b)\",\r\n r\"(?:\\bDEPRESSED\\b)|(?:\\bSAD\\b)\",\r\n r\"(?:\\bUNHAPPY\\b)\",\r\n r\"(?:\\bYOU\\b(?: (?:(?:\\bJUST\\b)|(?:\\bREALLY\\b)))* \\bNEED\\b) ([A-Z 0-9_]*)\",\r\n\r\n r\"\\A(?:\\bYOUR\\b (?:(?:\\bMOTHER\\b)|(?:\\bFATHER\\b)) )([^.]+)\",\r\n\r\n r\"(?:\\bYOUR\\b (\\bMOTHER\\b|\\bFATHER\\b)\\.)\"\r\n\r\n ]\r\n\r\n substitutions = [\r\n (\"IN WHAT WAY?\", \"HOW SO?\"),\r\n (\"CAN YOU THINK OF A SPECIFIC EXAMPLE?\",\"CAN YOU GIVE ME AN EXAMPLE OF SOMETHING THAT MAKES YOU FEEL THIS WAY?\"),\r\n (\"I AM SORRY TO HEAR THAT YOU ARE {}.\", \"{} YOU SAY? I'M SORRY TO HEAR THAT.\"),\r\n (\"DO YOU THINK THAT COMING HERE WILL HELP YOU NOT BE {}?\",\r\n \"DO YOU BELIEVE THAT COMING HERE CAN HELP OVERCOME BEING {}?\"),\r\n (\"WHAT WOULD IT MEAN IF YOU COULD GET {}?\", \"IF YOU WERE TO GET{},WHAT DO YOU THINK WILL HAPPEN?\"),\r\n\r\n (\"WHO ELSE {}?\", \"IS THERE ANYBODY ELSE WHO {}?\"),\r\n\r\n (\"TELL ME MORE ABOUT YOUR FAMILY.\", \"WHAT ELSE CAN YOU TELL ME ABOUT YOUR FAMILY?\")\r\n ]\r\n\r\n for i in range(0, len(keywords)):\r\n pattern = keywords[i]\r\n # print(\"___________________________________________debugging: pattern is \"+pattern)\r\n match = re.findall(pattern, x)\r\n # print(\"___________________________________________debugging: full match is \"+ str(match))\r\n\r\n # random chance to use a substitution on this match\r\n useSubstitution = toMod()\r\n\r\n if match and useSubstitution:\r\n # pick a match group from groups in the full match\r\n match = random.choice(match)\r\n # print(\"___________________________________________debugging: match group is \"+ match)\r\n # print(\"___________________________________________debugging: sub options are \"+ str(substitutions[i]))\r\n x = random.choice(substitutions[i]).format(match)\r\n break\r\n return x\r\n\r\n\r\n# main\r\ninputs = 0\r\nprint(\"HI. I AM ELIZA\")\r\ntimingAllowance(0.2,3)\r\nprint(\"I WILL BE YOUR THERAPIST TODAY.\")\r\ntimingAllowance(0.2,3)\r\nprint(\"WHAT SEEMS TO BE THE PROBLEM?\")\r\n\r\nwhile input != \".\":\r\n inputs = input()\r\n output = modifier(inputs)\r\n timingAllowance(0.35,4)\r\n if(input == \".\"):\r\n print(\"!\")\r\n break\r\n print(output)\r\n","sub_path":"NLP_ASSIGNMENT/NLP_Assignment_1_Q2.py","file_name":"NLP_Assignment_1_Q2.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"591188259","text":"__author__ = 'pavel'\n\nfrom django.db import models\nfrom purchase import Purchase\n\n\nclass TPPOLevel(models.Model):\n name = models.TextField()\n class Meta:\n db_table = 'geography_PPOLevel'\n app_label = 'data_crawler'\n\n\n\n\nclass PPO(models.Model):\n name = models.TextField()\n level_fk = models.ForeignKey(TPPOLevel)\n\n class Meta:\n db_table = 'geography_PPOName'\n app_label = 'data_crawler'\n\n\nclass TLegalEntityType(models.Model):\n description = models.TextField()\n class Meta:\n db_table = 'codes_tLegalEntityType'\n app_label = 'data_crawler'\n\n\nclass Organization(models.Model):\n name = models.TextField()\n url = models.TextField()\n INN = models.TextField()\n KPP = models.TextField()\n tentityType_fk = models.ForeignKey(TLegalEntityType)\n PPO_fk = models.ForeignKey(PPO, null=True)\n\n class Meta:\n db_table = 'subjects_organization'\n app_label = 'data_crawler'\n\n\nclass Person(models.Model):\n FIO = models.TextField(null=True)\n email = models.EmailField(null=True)\n telephone = models.TextField(null=True)\n fax = models.TextField(null=True)\n #organization_fk = models.ForeignKey(Organization)\n\n class Meta:\n db_table = 'subjects_person'\n app_label = 'data_crawler'\n\n\nclass Staff(models.Model):\n organization_fk = models.ForeignKey(Organization)\n person_fk = models.ForeignKey(Person)\n\n class Meta:\n db_table = 'connections_staff'\n app_label = 'data_crawler'\n\n\nclass PurchaseStaff(models.Model):\n purchase_fk = models.ForeignKey(Purchase)\n staff_fk = models.ForeignKey(Staff)\n\n class Meta:\n db_table = 'connections_purchaseStaff'\n app_label = 'data_crawler'","sub_path":"goszak/data_crawler/parsers/models/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"361044456","text":"\nfrom ...testing import raises, VScriptTestCase\nfrom ... import errors\nfrom ...subtypes import mismatch, empty, null, integer, string, double, \\\n\tboolean, error, binary, date, array, dictionary, generic, nothing, \\\n\tnan, infinity, true, false, v_mismatch, v_empty, v_null, v_nothing\n\n\nclass TestDictionaries(VScriptTestCase):\n\n\tdef test_dictionary_enumeration(self):\n\t\tassert self.execute(\"\"\"\n\t\t\tmydictionary=dictionary(1, \"a\", 2, \"b\", 3, \"c\")\n\t\t\tfor each item in mydictionary\n\t\t\t\tresult=result+item\n\t\t\tnext\"\"\").is_integer(6)\n","sub_path":"sources/vscript/tests/features/test_dictionaries.py","file_name":"test_dictionaries.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"295785423","text":"from tkinter import *\r\nfrom PIL import ImageTk,Image\r\nfrom tkinter import messagebox\r\n\r\nfrom tkinter import filedialog\r\nimport sqlite3\r\nroot = Tk()\r\nroot.title('Library Management System')\r\nroot.iconbitmap(\"D:\\li.ico\")\r\nroot.geometry(\"900x650+300+150\")\r\nroot.resizable(0, 0)\r\n\r\n#Databases\r\n# Create a databases or connect to one\r\nconn = sqlite3.connect('LBS.db')\r\n\r\n# Create cursor\r\nc = conn.cursor()\r\nconn.commit()\r\n#c.execute(\"\"\" CREATE TABLE books(\r\n #userid integer,\r\n #title text,\r\n #author text,\r\n #edition integer,\r\n #price integer\r\n #) \"\"\")\r\n# Create table\r\n\r\n\r\n\r\n\r\n#Creating an update function\r\ndef update():\r\n # Create a databases or connect to one\r\n conn = sqlite3.connect('LBS.db')\r\n # Create cursor\r\n c = conn.cursor()\r\n record_id = delete_box.get()\r\n c.execute(\"\"\" UPDATE books SET\r\n userid = :id,\r\n title = :tit,\r\n author = :auth,\r\n edition = :edi,\r\n price = :pri\r\n WHERE userid = :userid \"\"\",\r\n {'id': userid_editor.get(),\r\n 'tit': title_editor.get(),\r\n 'auth': author_editor.get(),\r\n 'edi': edition_editor.get(),\r\n 'pri': price_editor.get(),\r\n 'userid': record_id\r\n }\r\n )\r\n conn.commit()\r\n conn.close()\r\n\r\n #Destroying all the data and closing window\r\n editor.destroy()\r\n\r\n\r\n# Create submit button for databases\r\ndef submit():\r\n # Create a databases or connect to one\r\n conn = sqlite3.connect('LBS.db')\r\n # Create cursor\r\n c = conn.cursor()\r\n # Insert into table\r\n c.execute(\"INSERT INTO books VALUES (:userid, :title, :author, :edition, :price)\",{\r\n 'userid':u_id.get(),\r\n 'title':btitle.get(),\r\n 'author':bauthor.get(),\r\n 'edition':bedition.get(),\r\n 'price':bprice.get()\r\n\r\n })\r\n\r\n # showinfo messagebox\r\n messagebox.showinfo(\"Books\", \"Inserted Successfully\")\r\n conn.commit()\r\n conn.close()\r\n # clear the text boxes\r\n u_id.delete(0,END)\r\n btitle.delete(0,END)\r\n bauthor.delete(0,END)\r\n bedition.delete(0, END)\r\n bprice.delete(0, END)\r\n\r\ntestf=LabelFrame(root,text=\"LIBRARY MANAGMENT SYSTEM\",bg='light blue',width=470,height=50,\r\n font=('NEW TIMES ROMAN',20))\r\ntestf.place(x=230,y=30)\r\n\r\n\r\n#frame for textbox\r\ntframe=Frame(root,bg='black',width=900,height=390)\r\ntframe.place(x=0,y=110)\r\n\r\n#shows all book record function\r\ndef b_all_records():\r\n # Create a databases or connect to one\r\n conn = sqlite3.connect('LBS.db')\r\n\r\n # Create cursor\r\n c = conn.cursor()\r\n\r\n # query of the database\r\n c.execute(\"SELECT *, userid FROM books\")\r\n records = c.fetchall()\r\n\r\n # print(records)\r\n # Loop through the results\r\n print_record=''\r\n for record in records:\r\n #str(record[6]) added for displaying the id\r\n print_record +=\"ID:- \" +str(record[0]) + '\\t'+\" Title:- \"+ str(record[1]) + '\\t' +\"Author:- \"+ str(record[2]) + '\\t'\\\r\n +\"Edition:- \"+ str(record[3]) + '\\t'+\"Price Rs:- \" + str(record[4])+ \"\\t\" \"\\n\"\r\n\r\n label=LabelFrame(tframe,text=\"ALL BOOKS DETAILS\",width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\n label.place(x=550, y=0, height=20,width=155)\r\n query_label = Label(tframe, text=print_record)\r\n query_label.place(x=380,y=20,height=100)\r\n\r\n conn.commit()\r\n conn.close()\r\n\r\n\r\n# Creating a function to delete a record\r\ndef delete():\r\n # create database\r\n conn = sqlite3.connect('LBS.db')\r\n #create cursor\r\n c = conn.cursor()\r\n #delete a record\r\n c.execute(\"DELETE from books WHERE userid = \" + delete_box.get())\r\n print('Deleted Successfully')\r\n # query of the database\r\n c.execute(\"SELECT *, userid FROM books\")\r\n records = c.fetchall()\r\n # print(records)\r\n # Loop through the results\r\n\r\n\r\n conn.commit()\r\n conn.close()\r\n\r\n\r\n\r\n# Create edit function to update a record\r\ndef edit():\r\n global editor\r\n editor = Tk()\r\n editor.title('Update Books')\r\n editor.iconbitmap(\"D:\\li.ico\")\r\n editor.geometry('400x300')\r\n editor.resizable(0, 0)\r\n\r\n # frame for edit/update\r\n eframe = Frame(editor, bg='#a7e66c', width=1200, height=600)\r\n eframe.place(x=0, y=0)\r\n\r\n # Create a databases or connect to one\r\n conn = sqlite3.connect('LBS.db')\r\n # Create cursor\r\n c = conn.cursor()\r\n record_id = delete_box.get()\r\n # query of the database\r\n c.execute(\"SELECT * FROM books WHERE userid =\" + record_id)\r\n records = c.fetchall()\r\n # print(records)\r\n\r\n #Creating global variable for all text boxes\r\n global userid_editor\r\n global title_editor\r\n global author_editor\r\n global edition_editor\r\n global price_editor\r\n\r\n # Create text boxes of update books\r\n userid_editor = Entry(eframe,width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\n userid_editor.place(x=120, y=20)\r\n title_editor = Entry(eframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\n title_editor.place(x=120, y=60)\r\n author_editor = Entry(eframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\n author_editor.place(x=120, y=100)\r\n edition_editor = Entry(eframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\n edition_editor.place(x=120, y=140)\r\n price_editor = Entry(eframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\n price_editor.place(x=120, y=180)\r\n\r\n # Create textbox labels of update books\r\n id_label = Label(eframe, text=\"User ID\",fg='black',font=('Arial',13))\r\n id_label.place(x=20, y=20)\r\n Title_label = Label(eframe, text=\"Title\", fg='black', font=('Arial', 13,))\r\n Title_label.place(x=20, y=60)\r\n Author_label = Label(eframe, text=\"Author\", fg='black', font=('Arial', 13,))\r\n Author_label.place(x=20, y=100)\r\n Edition_label = Label(eframe, text=\"Edition\",fg='black',font=('Arial',13,))\r\n Edition_label.place(x=20, y=140)\r\n Price_label = Label(eframe, text=\"Price\",fg='black',font=('Arial',13,))\r\n Price_label.place(x=20, y=180)\r\n\r\n # loop through the results\r\n for record in records:\r\n userid_editor.insert(0, record[0])\r\n title_editor.insert(0, record[1])\r\n author_editor.insert(0, record[2])\r\n edition_editor.insert(0, record[3])\r\n price_editor.insert(0, record[4])\r\n\r\n\r\n # Create a update button\r\n edit_btn = Button(eframe, text=\" UPDATE \", command=update,activeforeground='#ecf022'\r\n ,width=20,height=2, fg='black', bg='#ecf022', font=('Arial', 10, 'bold'))\r\n edit_btn.place(x=140,y=230)\r\n\r\n\r\n# Create text boxes\r\nu_id = Entry(tframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\nu_id.place(x=130,y=20)\r\nbtitle = Entry(tframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\nbtitle.place(x=130,y=50)\r\nbauthor = Entry(tframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\nbauthor.place(x=130,y=80)\r\nbedition = Entry(tframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\nbedition.place(x=130,y=110)\r\nbprice = Entry(tframe, width=30,bd=4,relief='groove',font=('arial',10,'bold'))\r\nbprice.place(x=130,y=140)\r\n\r\n# Create textbox labels\r\nid_label = Label(tframe, text=\"ID\",fg='black',bg='silver',font=('Arial',13,'bold'))\r\nid_label.place(x=50,y=20)\r\ntitle_label = Label(tframe, text=\"Title\",fg='black',bg='silver',font=('Arial',13,'bold'))\r\ntitle_label.place(x=50,y=50)\r\nauthor_label = Label(tframe, text=\"Author\",fg='black',bg='silver',font=('Arial',13,'bold'))\r\nauthor_label.place(x=50,y=80)\r\nedition_label = Label(tframe, text=\"Edition\",fg='black',bg='silver',font=('Arial',13,'bold'))\r\nedition_label.place(x=50,y=110)\r\nprice_label = Label(tframe, text=\"Price\",fg='black',bg='silver',font=('Arial',13,'bold'))\r\nprice_label.place(x=50,y=140)\r\n\r\n#frame for button\r\nf1=Frame(root,bg='black',width=900,height=1920)\r\nf1.place(x=0,y=300)\r\n\r\n#open the image\r\nbg=Image.open('D:\\img2.jpg')\r\n\r\n#resize the image\r\nresized=bg.resize((450,347),Image.ANTIALIAS)\r\nnewpic=ImageTk.PhotoImage(resized)\r\n\r\n#bg=PhotoImage(file= 'D:\\LBS\\download.png')\r\nmy_label= Label(f1,image=newpic)\r\nmy_label.place(x=440,y=0)\r\n\r\n# ENTRY BOX FOR DELETE BOX\r\ndelete_box = Entry(f1,width=40,bg=\"light blue\" )\r\ndelete_box.place(x=150, y=125,height=35)\r\n\r\ndelete_box_label = Label(f1, text=\"USER ID\",font=('Arial', 15, 'bold'),fg='black',bg=\"#fff\",\r\n width=7,height=0,bd=8,relief='flat',cursor='hand2')\r\ndelete_box_label.place(x=40, y=120)\r\n\r\n\r\n# Create submit button\r\nsubmit_btn = Button(f1, text=\"Add Books\",fg='black',bg='#ecf022',font=('Arial',15,'bold'),width=15,\r\n height=0,bd=7,relief='flat',command=submit,cursor='hand2')\r\nsubmit_btn.place(x=40,y=40)\r\n\r\n# Create query button\r\nquery_btn = Button(f1, text=\"Show Books\",fg='black', bg='#ecf022', font=('Arial', 15, 'bold'),\r\n width=10,height=0, bd=7,relief='flat', command=b_all_records,cursor='hand2')\r\nquery_btn.place(x=250, y=40)\r\n\r\n# Create a delete button\r\ndelete_btn = Button(f1, text=\"Delete\", command=delete, fg='black', bg='#ecf022', font=('Arial', 15, 'bold'),\r\n width=10,height=0,bd=7,relief='flat',cursor='hand2')\r\ndelete_btn.place(x=40, y=200)\r\n\r\n# Create a update button\r\nedit_btn = Button(f1, text=\"Update\", command=edit, fg='black', bg='#ecf022', font=('Arial ', 15, 'bold'),\r\n width=15,height=0,bd=7, relief='flat',cursor='hand2')\r\nedit_btn.place(x=190, y=200)\r\n\r\n\r\n# commit change\r\nconn.commit()\r\n# close connection\r\nconn.close()\r\n\r\nmainloop()","sub_path":"LMS.py","file_name":"LMS.py","file_ext":"py","file_size_in_byte":9495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"532979928","text":"\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index,name = \"index-page\"),\n path('contact/', views.contact,name = \"contactus\"),\n path('send-courier/', views.send_courier,name = \"send-courier\"),\n path('about/', views.about,name = \"about-page\"),\n path('track/', views.track,name = \"track-page\"),\n path('login/', views.login,name = \"login-page\"), \n\n]\n","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"583907874","text":"#!/usr/bin/python\n\nimport base64\nimport json\nimport sys\n\n\ndef decode(s):\n print('----------------result----------------')\n sz = \"\".join([chr(ord(i) ^ 0x2f) for i in base64.decodestring(s)])\n js = json.loads(sz, encoding='utf-8')\n goods = js.get('goods', {})\n lego_card = goods.get('lego_card', '')\n if lego_card:\n goods['lego_card'] = json.loads(lego_card, encoding='utf-8')\n print(json.dumps(js, encoding='utf-8', ensure_ascii=False, indent=4).encode('utf-8'))\n\n\nif __name__ == '__main__':\n decode(sys.argv[1])\n","sub_path":"bin/decode_fc_ads.py","file_name":"decode_fc_ads.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"560129169","text":"from flask.ext.script import Command\n\nfrom .github import github\nfrom .models import db, User, Project\n\n\nclass SyncProjects(Command):\n \"Syncs Jazzband projects on GitHub with database\"\n\n def run(self):\n projects_data = github.get_projects()\n Project.sync(projects_data)\n\n\nclass SyncMembers(Command):\n \"Syncs Jazzband members on GitHub with database\"\n\n def run(self):\n members_data = github.get_members()\n User.sync(members_data)\n\n stored_ids = set(user.id for user in User.query.all())\n fetched_ids = set(m['id'] for m in members_data)\n stale_ids = stored_ids - fetched_ids\n if stale_ids:\n User.query.filter(\n User.id.in_(stale_ids)\n ).update({'is_member': False}, 'fetch')\n db.session.commit()\n","sub_path":"jazzband/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"314154340","text":"from __future__ import absolute_import\n\nfrom sentry.models import GroupHash\nfrom sentry.testutils import TestCase\n\n\nclass GroupTest(TestCase):\n def test_fetch_and_record_last_processed_event_id(self):\n group = self.group\n\n grouphash = GroupHash.objects.create(\n project=group.project,\n group=group,\n hash='xyz',\n )\n\n GroupHash.record_last_processed_event_id(\n grouphash.project_id,\n [grouphash.id],\n 'event',\n )\n\n assert GroupHash.fetch_last_processed_event_id(\n grouphash.project_id,\n [grouphash.id, -1],\n ) == ['event', None]\n","sub_path":"tests/sentry/models/test_grouphash.py","file_name":"test_grouphash.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378893019","text":"from tkinter import *\nroot = Tk()\nroot.title(\"Label Example\")\nroot.geometry(\"500x500\")\nroot.wm_minsize(width=300, height=300)\n\n#creating and placing a label\nl1 = Label(root, text=\"First\")\nl1.place(x=10, y=10)\n\n# set size, fg, bg, font, text, size, bold\nl2 = Label(root, text=\"Second\", fg=\"lightblue\", bg=\"navy\")\nl2.config(width=10, height=3, font=(\"calibri\", 16, \"bold\"))\nl2.place(x=100, y=10)\n\n# pic = PhotoImage(\"path\")\n# l3 = Label(root, text=\"Third\", image=pic)\n\n\nroot.mainloop()","sub_path":"label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67531248","text":"from twilio.rest import TwilioRestClient\nimport datetime\naccount_sid = \"AC94c74aa44a8f2b2b66ebed6510c2bd24\"\nauth_token = \"55ac08e73fc9aaedae7ec8057aae774f\"\nclient = TwilioRestClient(account_sid, auth_token)\n\ndef sendsms(status):\n\ttime = datetime.datetime.now()\n\tmessage = client.messages.create(to=\"+16476062679\", from_=\"+12044001907\",\n\t body=status + str(time)+\"... Done\")\n\n#def main():\n#\tsendsms(\"Done\", str(datetime.datetime.now()))\n\n#main()","sub_path":"sendsms.py","file_name":"sendsms.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"154839171","text":"import datetime as dt\r\nimport xlsxwriter\r\n\r\nclass Time():\r\n\r\n def __init__(self):\r\n pass\r\n\r\n def addMinutes(self, tm, minutes):\r\n fulldate = dt.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)\r\n fulldate = fulldate + dt.timedelta(minutes=minutes)\r\n return fulldate\r\n\r\n def timestamps(self, start, end, minutes):\r\n start_t = dt.datetime.strptime(start, '%H:%M')\r\n end_t = dt.datetime.strptime(end, '%H:%M')\r\n diff = (end_t - start_t).total_seconds()\r\n nb_intervals = int(diff/(minutes*60)) + 1\r\n timetable = [self.addMinutes(start_t, i*minutes).time() for i in range(nb_intervals)]\r\n return timetable\r\n\r\n def displayTimestamps(self, timestamps):\r\n for ts in timestamps:\r\n print(ts)\r\n\r\ndays = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimache']\r\n\r\nworkbook = xlsxwriter.Workbook('calendar.xlsx')\r\nworksheet = workbook.add_worksheet('book1')\r\n\r\nformat = {'bold': 0, 'border': 1, 'align': 'center', 'valign': 'vcenter', 'fg_color': 'white' }\r\ncell_format = workbook.add_format(format)\r\n\r\n# print week days\r\nrow, col = 0, 1\r\nfor d in days:\r\n worksheet.write(row, col, d, cell_format)\r\n col += 1\r\n\r\n# print hours\r\nrow, col = 1, 0\r\ntimestamps = Time().timestamps('6:00', '22:00', 15)\r\nfor ts in timestamps:\r\n worksheet.merge_range('A{}:A{}'.format(row, row+1), ts.strftime('%H:%M'), workbook.add_format({'bold': 0,\r\n 'right': 1,\r\n 'align': 'center',\r\n 'valign': 'vcenter'}))\r\n row += 2\r\n\r\n# print inside borders\r\ninside_bottom_border = {'bottom': 1}\r\ninside_left_border = {'bottom': 1, 'right':1}\r\ninside_bottom_border_format = workbook.add_format(inside_bottom_border)\r\ninside_left_border_format = workbook.add_format(inside_left_border)\r\n\r\nn = len(timestamps)\r\nfor row in range(2, 2*n, 2):\r\n for col in range(7):\r\n format = inside_bottom_border_format\r\n if col == 7:\r\n format = inside_left_border_format\r\n worksheet.write(row, col+1, '', format)\r\n\r\nworkbook.close()\r\n","sub_path":"calendrier.py","file_name":"calendrier.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"94837867","text":"from django.urls import path,include\nfrom .views import (\n index_view,\n lecture_create_view,\n lecture_signup_view,\n detail_view,\n LectureViewSet,\n lecture_draw_view\n )\n\n\napp_name = 'lecture'\nurlpatterns = [\n path('', index_view, name='index'),\n path('/', detail_view,name='detail'),\n path('create',lecture_create_view,name='create'),\n path('/signup/', lecture_signup_view,name='signup'),\n path('/draw', lecture_draw_view, name='draw')\n]\n","sub_path":"src/lecture/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"630614325","text":"class LinkedList():\n def __init__(self):\n self.head = None\n\n def add(self, data):\n if not self.head:\n self.head = Node(data)\n node = self.head\n while(node.next):\n node = node.next\n node.next = Node(data)\n\n def midpoint(self):\n slow = self.head\n fast = slow\n\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n\nclass Node:\n def __init__(self, data = None):\n self.data = data\n self.next = None\n\nif __name__ == \"__main__\":\n lis = LinkedList()\n lis.add(1)\n lis.add(2)\n lis.add(3)\n lis.add(4)\n lis.add(5)\n lis.add(6)\n lis.add(7)\n lis.add(8)\n lis.add(9)\n lis.add(9)\n\n print(lis.midpoint().data)","sub_path":"codes/job_interview/linkedlist.py","file_name":"linkedlist.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"140892946","text":"#!/usr/bin/python3\n\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport urllib\n\nsuc = 0\nidd = int(input(\"Please put your ID: \"))\ntimes = int(input(\"How many votes do you want?: \"))\nurl = \"http://158.69.76.135/level1.php\"\nprint(\"\\nWorking... Please wait some time, even if this is slow, i'm\\\n faster than you.\")\nfor i in range(0, times):\n cokie = requests.session()\n tmp = cokie.get(url)\n content = tmp.content\n web = BeautifulSoup(content, 'html.parser')\n hml = web.find_all('input')\n for l in hml:\n if l.get('name') == \"key\":\n key = l.get('value')\n form = {'id': idd, 'key': key, 'holdthedoor': 'Submit'}\n req = cokie.post(url, data=form)\n if req.status_code == 200:\n suc += 1\n del cokie\nprint(\"Successful requests: {:d}\".format(suc))\n","sub_path":"level_1/4096.py","file_name":"4096.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526223449","text":"\"\"\"\nSSH functionality\n\nPlease use the contact information below for bug reports/feature requests.\n\nAuthor : Shane Bueschel\nEmail : sbueschel@vmware.com\nSkype : shane.bueschel\nCreated : 04/08/2016 05:41 PM\n\"\"\"\n# --- [ TODO ] -------------------------------------------------------------- #\n# --- [ IMPORTS ] ----------------------------------------------------------- #\n# ------ [ Standard library ] ----------------------------------------------- #\nimport re\nfrom collections import namedtuple as NT\nfrom time import sleep\nfrom ast import literal_eval\n# ------ [ Third party ] ---------------------------------------------------- #\nimport paramiko\nfrom paramiko.ssh_exception import SSHException as pSSHException\n# ------ [ Custom ] --------------------------------------------------------- #\nfrom common.vault import Creds\nfrom common.exceptions import OverlordError\n# --- [ GLOBAL VARS ] ------------------------------------------------------- #\n\n\n# --- [ FUNCTIONS ] --------------------------------------------------------- #\n\n\n# --- [ EXCEPTION CLASSES ] ------------------------------------------------- #\nclass ParamikoError(pSSHException):\n pass\n\n\nclass SSHException(OverlordError, ParamikoError):\n pass\n\n\nclass SessionAlreadyClosedError(SSHException):\n pass\n\n\nclass ParserError(SSHException):\n pass\n\n\n# --- [ TOP LEVEL CLASSES ] ------------------------------------------------- #\n\n\n# --- [ CLASSES ] ----------------------------------------------------------- #\nclass Blank(object):\n \"\"\"\n A blank class meant to hold mutable attributes. Accepts an arbitrary set of\n initialization attributes.\n \"\"\"\n\n\nclass Status(Blank):\n\n def __init__(self, **kwargs):\n for k in kwargs:\n setattr(self, k, kwargs[k])\n\n def __str__(self):\n return 'Status(status={}, exit={})'.format(self.status, self.exit)\n\n def __repr__(self):\n return str(self)\n\n\nclass SSH(object):\n \"\"\"\n Wrapper object for the paramiko SSH library. Credentials required for\n object initialization:\n\n - hostname -- str - The hostname or IP address of the target to which\n an SSH session should be created.\n - creds -- str, Creds - Either a username or an already initialized\n Creds object. If a string is provided, a Creds object will be created\n and a prompt for a password will appear.\n - port -- int - The port over which to connect via SSH. Default: 22\n \"\"\"\n\n def __init__(self, hostname, creds, port=22):\n if not isinstance(hostname, str):\n raise TypeError('SSH.__init__() - hostname must be of str type')\n self._host = hostname\n if not isinstance(port, int):\n raise TypeError('SSH.__init__() - port must be of int type')\n self._port = port\n if isinstance(creds, str):\n self._creds = Creds(creds)\n elif not isinstance(creds, Creds):\n _e = ('SSH.__init__() - creds must be either a username or an '\n 'initialized vault.Creds object.')\n raise TypeError(_e)\n else:\n self._creds = creds\n self.__sessions__ = {0: None}\n self._CmdNT_ = NT('session', ['stdin', 'stdout', 'stderr'])\n self._cmd_states_ = ['init', 'init_failure', 'running',\n 'success', 'failure']\n\n @staticmethod\n def __new_client__():\n return paramiko.SSHClient()\n\n def connect(self, timeout=30):\n \"\"\"\n Attempts to initiate an SSH connection to the hostname provided during\n SSH object initialization. The connection is wrapped in a Session\n class, which has additional methods and connection checks.\n\n Returns: Session\n \"\"\"\n _id = max(self.__sessions__) + 1\n ssh = self.__new_client__()\n ssh.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())\n try:\n ssh.connect(hostname=self._host, username=self._creds.un(),\n password=self._creds.pw(), look_for_keys=False,\n timeout=timeout)\n self.__sessions__[_id] = ssh\n session = Session(manager=self, session=ssh, session_id=_id)\n return session\n except (pSSHException, TimeoutError, OSError):\n return False\n\n def close(self, session_id, active=True):\n \"\"\"\n Closes an SSH session and/or deletes it from the Session registry.\n \"\"\"\n if active:\n self.__sessions__[session_id].close()\n del self.__sessions__[session_id]\n\n\nclass Session(object):\n \"\"\"Class containing methods for interacting with an SSH session.\"\"\"\n\n def __init__(self, manager=None, session=None, session_id=None):\n self._Manager = manager\n self._ssh = session\n self._id = session_id\n self.closed = False\n self.__cmds__ = {0: None}\n self.__shells__ = {0: None}\n self.__running__ = {0: None}\n\n def active(self):\n \"\"\"\n Returns True if the connection appears to be open, otherwise False.\n \"\"\"\n if self.closed:\n return False\n if not self._ssh._transport:\n return False\n if not self._ssh._transport.is_active():\n return False\n if not self._ssh._transport.is_alive():\n return False\n return True\n\n def cmd(self, command, blocking=False, expect=0):\n \"\"\"\n Execute a command on the remote system. By default, all blocking is\n turned off; passing True to the blocking argument will turn it back on.\n\n - expect -- The status code or codes which should be considered\n as successful. Default: 0\n \"\"\"\n if self.closed:\n raise SessionAlreadyClosedError()\n if not isinstance(expect, (int, list, tuple, range)):\n _e = 'cmd() - expect must be an int, list, tuple or range'\n raise TypeError(_e)\n elif isinstance(expect, (list, tuple)):\n try:\n [int(i) for i in expect]\n except ValueError:\n raise TypeError('cmd() - all status codes must be of int type')\n elif isinstance(expect, int):\n expect = [expect]\n if not self.active():\n # self._Manager.close(self._id, active=False)\n _e = 'Session ID {} is no longer active'.format(self._id)\n raise SSHException(_e)\n cmd_id = max(self.__cmds__)\n _NT = self._Manager._CmdNT_\n chans = _NT._make(self._ssh.exec_command(command))\n if not blocking:\n [x.channel.setblocking(0) for x in chans]\n cmd = Command(session=self, channels=chans,\n cmd_id=cmd_id, expect=expect)\n self.__cmds__[cmd_id] = cmd\n self.__running__[cmd_id] = Status(status='init', exit=-1)\n return cmd\n\n def shell(self, term='xterm', width=240, height=48, bash=True):\n \"\"\"\n Creates an interactive shell with the SSH target. If drop_cmd is\n True, then any lines which end with the command which was sent over\n stdin will be dropped when performing Shell.get()\n \"\"\"\n if self.closed:\n raise SessionAlreadyClosedError()\n pshell = self._ssh.invoke_shell(term=term, width=width, height=height)\n _shell_id = max(self.__shells__) + 1\n _shell = Shell(self, shell=pshell, shell_id=_shell_id,\n bash=bash)\n pshell.setblocking(0)\n self.__shells__[_shell_id] = _shell\n return _shell\n\n def status(self, cmd_id, status=None, exit=None):\n \"\"\"\n Set or get the status and exit code of a Command identified by cmd_id.\n When setting an exit code, a status must be provided. Acceptable\n statuses:\n\n - init -- The SSH command has been initialized and sent to the\n remote system, but has not yet been polled via the done() method\n - init_failure -- The SSH command has failed to initialize\n - running -- Indicates the SSH command is still running\n - success -- Indicates the SSH command has finished with an exit\n code of 0.\n - failure -- Indicates the SSH command has finished with a non-zero\n exit code.\n \"\"\"\n if not isinstance(cmd_id, int):\n raise TypeError('status() - cmd_id must be of int type')\n if not isinstance(exit, (int, type(None))):\n raise TypeError('status() - exit must be of int type')\n stat_obj = self.__running__[cmd_id]\n if not status:\n return stat_obj\n status = status.lower()\n if status not in self._Manager._cmd_states_:\n _e = 'status() - Invalid status provided: \\'{}\\''.format(status)\n raise ValueError(_e)\n stat_obj.status = status\n if isinstance(exit, int):\n stat_obj.exit = exit\n\n def close(self):\n if self.closed:\n raise SessionAlreadyClosedError()\n self.closed = True\n self._Manager.close(self._id)\n\n\nclass Command(object):\n \"\"\"\n Class containing methods for interacting with commands and their returns.\n \"\"\"\n\n def __init__(self, session=None, channels=None, cmd_id=None, expect=None):\n self._Session = session\n self.stdin = channels.stdin\n self.stdout = channels.stdout\n self.stderr = channels.stderr\n self.__status_set__ = False\n self._expect_ = expect\n self._id = cmd_id\n\n def done(self):\n \"\"\"\n Returns True if the command has finished executing, otherwise False.\n \"\"\"\n if self.stdout.channel.exit_status_ready():\n if not self.__status_set__:\n exit_code = self.stdout.channel.exit_status\n if exit_code in self._expect_:\n status = 'success'\n else:\n status = 'failure'\n self._Session.status(self._id, status=status, exit=exit_code)\n self.__status_set__ = True\n return True\n return False\n\n def send(self, string):\n \"\"\"\n Sends a response over standard input. Returns True if the provided\n string was sent, otherwise False. NOTE: The line break representing\n Enter is automatically included.\n \"\"\"\n if not self._Session.active():\n return False\n if self.done():\n return False\n string = '{}\\n'.format(string)\n if self.stdin.channel.send_ready():\n self.stdin.channel.send(string)\n return True\n return False\n\n def get(self, kind='stdout'):\n \"\"\"\n Retrieve the contents of standard ouput. Returns a list of lines which\n have already been decoded from bytes format. Returns False if there is\n nothing in the buffer.\n \"\"\"\n if kind == 'exit':\n if self.done():\n return self.stdout.channel.exit_status\n return False\n stream = getattr(self, kind)\n if stream.channel.recv_ready():\n _buffer = ''.encode()\n while stream.channel.recv_ready():\n _buffer += stream.channel.recv(8192)\n else:\n return None\n ret = [i for i in _buffer.decode().rstrip().split('\\n')]\n ret = [i.replace('\\r', '') for i in ret]\n return ret\n\n def status(self):\n \"\"\"\n Makes a call to the Session to return the status of this Command object\n \"\"\"\n return self._Session.status(self._id)\n\n\nclass Shell(object):\n \"\"\"\n Methods for interacting with an SSH Shell object.\n \"\"\"\n\n def __init__(self, session=None, shell=None, shell_id=None, bash=None):\n self._Session = session\n self.shell = shell\n self._id = shell_id\n self._hist = []\n self.bash = bash\n self.prompt = None\n if self.bash:\n self.set_prompt()\n\n def set_prompt(self, prompt='__SSH_SHELL__: '):\n \"\"\"\n Attempts to set the command prompt (PS1); this should only be used if\n the presence of the PS1 variable or a Bash environment is guaranteed.\n \"\"\"\n self.send('PS1=\\'{}\\''.format(prompt))\n self.prompt = prompt\n self._prompt_re = re.compile('{}[ ]?$'.format(prompt.rstrip()))\n while not self.get():\n sleep(0.25)\n\n def active(self):\n \"\"\"Returns True if the Shell appears to be active, otherwise False.\"\"\"\n if self.shell.closed:\n return False\n return True\n\n def get(self, kind='stdout'):\n \"\"\"\n Retrieve the contents of standard ouput. Returns a list of lines which\n have already been decoded from bytes format. Returns False if there is\n nothing in the buffer.\n \"\"\"\n if kind == 'stdout':\n if self.shell.recv_ready():\n _buffer = ''.encode()\n while self.shell.recv_ready():\n _buffer += self.shell.recv(8192)\n else:\n return None\n elif kind == 'stderr':\n if self.shell.recv_stderr_ready():\n _buffer = ''.encode()\n while self.shell.recv_stderr_ready():\n _buffer += self.shell.recv_stderr(8192)\n else:\n return None\n else:\n return None\n ret = [i for i in _buffer.decode().rstrip().split('\\n')]\n ret = [i.replace('\\r', '') for i in ret]\n if self.drop_cmd and self._hist:\n for cmd in self._hist:\n cmd_str = '{}{}'.format(self.prompt, cmd)\n while cmd_str in ret:\n ret.remove(cmd_str)\n while cmd in ret:\n ret.remove(cmd)\n if self._prompt_re.search(ret[-1]):\n if len(ret) == 1:\n return None\n ret = ret[:-1]\n return ret\n\n def cmd(self, string):\n \"\"\"\n Send a command to the remote system. The final new-line character is\n automatically included. This is almost identical to the send() method,\n except that any commands sent through this method will be appended to\n the command history and dropped if drop_cmd is True.\n \"\"\"\n if not self.active():\n return False\n self._hist.append(string)\n string = '{}\\n'.format(string)\n if self.shell.send_ready():\n self.shell.send(string)\n return True\n return False\n\n def send(self, string):\n \"\"\"\n Sends a response over standard input. Returns True if the provided\n string was sent, otherwise False. NOTE: The line break representing\n Enter is automatically included.\n \"\"\"\n if not self.active():\n return False\n string = '{}\\n'.format(string)\n if self.shell.send_ready():\n self.shell.send(string)\n return True\n return False\n\n\nclass Parser(object):\n \"\"\"\n A class which contains methods for parsing and sorting output retrieved\n from SSH commands.\n \"\"\"\n\n def sectionize(self, section_re, lines):\n \"\"\"\n Separates the contents of a list, presumably from SSH/stdout buffers,\n into a dictionary. The section_re which is provided must be a compiled\n RegExp from re.compile(expr). Example return:\n\n {0: ['Section_one__line_one', 'Section_one__line_two'],\n 1: ['Section_two__line_one', 'Section_two__line_two']}\n \"\"\"\n lines.append('') # this method requires a slight pad\n l_range = range(len(lines))\n bounds = [l_range[0], l_range[-1]]\n sections = []\n ret = {-1: None}\n hits = [i for i in l_range if section_re.search(lines[i])]\n for hit in hits:\n if hit not in bounds:\n bounds.append(hit)\n bounds.sort()\n bound_range = range(len(bounds))\n for i in bound_range:\n if i < bound_range[-1]:\n sections.append(range(bounds[i], bounds[i + 1]))\n for section_def in sections:\n sct = [lines[i] for i in section_def if lines[i] and i not in hits]\n if sct:\n ret[max(ret) + 1] = sct\n del ret[-1]\n return ret\n\n\nclass Output(Parser):\n \"\"\"\n Accepts a list object as input and provides methods for easily cleaning\n and scrubbing the contents of the list. The list is meant to be return from\n the Shell.get() and Command.get() functions and may behave unpredictably if\n used outside of this context.\n \"\"\"\n\n def __init__(self, output, sectionize=False, pattern=False):\n if isinstance(output, (list, tuple)):\n if sectionize:\n self.sections = self.sectionize(pattern, output)\n self.content = None\n else:\n self.content = output\n self.sections = None\n elif isinstance(output, (dict)):\n self.content = None\n self.sections = output\n\n @staticmethod\n def line_scrubber(spl, line, join):\n line = [i.rstrip().lstrip() for i in line.split(spl) if i]\n if join and isinstance(join, str):\n line = line.join(join)\n return line\n\n def clean(self, spl, scrub=None, join=None, section=None, persist=False):\n \"\"\"\n Iterates over the lines within the 'content' attribute and splits each\n line. The resulting list is then scrubbed. Parameters:\n\n - spl -- split the line on the specified string\n - scrub -- Remove elements containing the provided RegEx from\n the resulting list. This is ran against the line prior to the\n line being split.\n - join -- Join the resulting list on the string specified here\n \"\"\"\n if not isinstance(scrub, type(None)):\n if not isinstance(scrub, (list, tuple)):\n scrub = [scrub]\n _ret = []\n contents = False\n if isinstance(section, int):\n if section in self.sections:\n contents = self.sections[section]\n else:\n contents = self.content\n if not contents or not isinstance(contents, list):\n _e = 'Output.clean() - Unable to retrieve valid content list'\n raise ParserError(_e)\n for content in contents:\n if scrub:\n exclude = False\n line = False\n for scrubber in scrub:\n if scrubber.search(content):\n exclude = True\n break\n if not exclude:\n line = self.line_scrubber(spl, content, join)\n else:\n line = self.line_scrubber(spl, content, join)\n if line:\n _ret.append(line)\n if persist:\n self.sections[section] = _ret\n else:\n return _ret\n\n def columnize(self, list_obj, fields=None, start=0, discard=None):\n \"\"\"\n Takes a list or tuple object and returns a dictionary object with the\n following structure:\n {'fields': ['field_one', 'field_two'],\n 'values': [['row_one_col_one, 'row_one_col_two'],\n ['row_two_col_one, 'row_two_col_two'],\n ...]}\n If no fields are provided, then the list index[0] is assumed to hold\n the field names. It is highly recommended to run the list through the\n clean() method prior to columnizing it.\n \"\"\"\n if not fields:\n fields = list_obj[start]\n list_obj = list_obj[start + 1:]\n else:\n list_obj = list_obj[start:]\n field_ct = len(fields)\n values = []\n for line in list_obj:\n line_vals = []\n for i in line[:field_ct]:\n if not i:\n line_vals.append(None)\n elif i.lower() in ['true', 'false']:\n line_vals.append(literal_eval(i.lower().capitalize()))\n else:\n try:\n non_str_obj = literal_eval(i)\n line_vals.append(non_str_obj)\n except (ValueError, SyntaxError):\n line_vals.append(i)\n values.append(line_vals)\n return {'fields': fields, 'values': values}\n\n def zipify(self, sections=None):\n \"\"\"\n Transforms the provided section indexes into one dictionary. Any data\n which is longer than 2 indices will be truncated on return!\n \"\"\"\n if isinstance(sections, int):\n sections = [sections]\n keys = []\n values = []\n for section in sections:\n section_data = self.sections[section]\n for line in section_data:\n keys.append(line[0])\n values.append(line[1])\n return dict(zip(keys, values))\n\n# --- [ DIRECT EXECUTION ] -------------------------------------------------- #\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"common/ssh.py","file_name":"ssh.py","file_ext":"py","file_size_in_byte":21072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219749829","text":"#!/usr/bin/env python \n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport warnings\nwarnings.filterwarnings(\"ignore\",\".*GUI is implemented.*\")\n\nimport rospy\nfrom autlab3.msg import ArrayXY\n\n\ndef plot_xy(msg):\n plt.plot(msg.x, msg.y, 'b.')\n plt.xlabel('x')\n plt.ylabel('y')\n plt.grid()\n plt.axis(\"equal\")\n plt.draw()\n plt.pause(0.001)\n plt.hold(False)\n\n \nif __name__ == '__main__':\n rospy.init_node(\"plotter_xy\")\n rospy.Subscriber(\"lidar_xy\", ArrayXY, plot_xy)\n plt.show()\n rospy.spin()\n\n","sub_path":"autlab3/src/plot_lidar.py","file_name":"plot_lidar.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618104656","text":"\"\"\"Plays files from the local filesystem.\"\"\"\n\nimport functools\nimport logging\nimport urllib.parse\nfrom http.server import HTTPServer\nfrom ipaddress import IPv4Address, IPv4Network\nfrom os import chdir, path\nfrom queue import Empty\nfrom socketserver import ThreadingMixIn\nfrom sys import version_info as pyversion\nfrom threading import Thread\n\nimport ifaddr\nfrom RangeHTTPServer import RangeRequestHandler\n\nfrom soco_cli.utils import (\n error_and_exit,\n event_unsubscribe,\n set_sigterm,\n set_speaker_playing_local_file,\n)\n\n# The HTTP server port range to use\nPORT_START = 54000\nPORT_END = 54099\n\nSUPPORTED_TYPES = [\"MP3\", \"M4A\", \"MP4\", \"FLAC\", \"OGG\", \"WMA\", \"WAV\", \"AAC\"]\n\nPY37PLUS = True if pyversion.major >= 3 and pyversion.minor >= 7 else False\n\n\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n \"\"\"Handle requests in separate threads.\n\n Use the MixIn approach instead of the core ThreadingHTTPServer\n class for backwards compatibility with Python 3.5+\n \"\"\"\n\n\nclass MyHTTPHandler(RangeRequestHandler):\n # Handle the change to the SimpleHTTPRequestHandler __init__() in Python 3.7+\n if PY37PLUS:\n\n def __init__(self, *args, filename=None, speaker_ips=None, **kwargs):\n self.filename = filename\n self.speaker_ips = speaker_ips\n super().__init__(*args, **kwargs)\n\n else:\n\n def __init__(\n self, *args, filename=None, speaker_ips=None, directory=\"\", **kwargs\n ):\n self.filename = filename\n self.speaker_ips = speaker_ips\n try:\n chdir(directory)\n except:\n pass\n super().__init__(*args, **kwargs)\n\n def do_GET(self):\n logging.info(\"Get request received by HTTP server\")\n\n # Only serve the specific file requested on the command line,\n # and only to Sonos speakers in the Sonos system\n error = False\n if self.path.replace(\"/\", \"\") != self.filename:\n logging.info(\"Access to file '{}' forbidden\".format(self.path))\n error = True\n if self.client_address[0] not in self.speaker_ips:\n logging.info(\"Access from IP '{}' forbidden\".format(self.client_address[0]))\n error = True\n if error:\n RangeRequestHandler.send_error(\n self, code=403, message=\"SoCo-CLI HTTP Server: Access forbidden\"\n )\n return\n\n # Forward the GET request\n try:\n super().do_GET()\n except Exception as e:\n # It's normal to hit some exceptions with Sonos.\n logging.info(\"Exception ignored: {}\".format(e))\n pass\n\n def log_message(self, format, *args):\n # Suppress HTTP logging\n return\n\n\ndef http_server(server_ip, directory, filename, speaker_ips):\n # Set the directory from which to serve files, in the handler\n # Set the specific filename and client IP that are authorised\n handler = functools.partial(\n MyHTTPHandler, filename=filename, speaker_ips=speaker_ips, directory=directory\n )\n\n # For possible future use: set up MIME types\n # MyHTTPHandler.extensions_map[\".m4a\"] = \"audio/x-m4a\"\n # MyHTTPHandler.extensions_map[\".aac\"] = \"audio/aac\"\n\n # Find an available port by trying ports in sequence\n for port in range(PORT_START, PORT_END + 1):\n try:\n httpd = ThreadedHTTPServer((server_ip, port), handler)\n logging.info(\"Using {}:{} for web server\".format(server_ip, port))\n httpd_thread = Thread(target=httpd.serve_forever, daemon=True)\n httpd_thread.start()\n logging.info(\"Web server started\")\n return httpd\n except OSError:\n # Assume this means that the port is in use\n continue\n else:\n return None\n\n\ndef get_server_ip(speaker):\n # Get a suitable IP address to use as a server address for Sonos\n # on this host\n adapters = ifaddr.get_adapters()\n for adapter in adapters:\n for ip in adapter.ips:\n if ip.is_IPv4:\n network = IPv4Network(\n ip.ip + \"/\" + str(ip.network_prefix), strict=False\n )\n if IPv4Address(speaker.ip_address) in network:\n return ip.ip\n else:\n return None\n\n\ndef wait_until_stopped(speaker, uri, aac_file=False):\n sub = speaker.avTransport.subscribe(auto_renew=True)\n # Includes a hack for AAC files, which would be played in a repeat loop.\n # The speaker never goes into a 'STOPPED' state, so we have\n # to detect the shift into a 'TRANSITIONING' state after playback\n has_played = False\n while True:\n try:\n event = sub.events.get(timeout=1.0)\n logging.info(\n \"Transport event: State = '{}'\".format(\n event.variables[\"transport_state\"]\n )\n )\n\n # In case there's no STOPPED state event, check that the expected URI\n # is still playing\n try:\n current_uri = event.variables[\"current_track_meta_data\"].get_uri()\n except:\n # Can only call get_uri() on certain datatypes\n current_uri = \"\"\n if current_uri != uri:\n logging.info(\"Playback URI changed: exit event wait loop\")\n event_unsubscribe(sub)\n return True\n\n # Special case for AAC files\n if aac_file:\n if event.variables[\"transport_state\"] == \"TRANSITIONING\":\n logging.info(\"Transitioning event received\")\n if has_played:\n logging.info(\"AAC: transition event indicating end of track\")\n event_unsubscribe(sub)\n speaker.stop()\n return True\n else:\n logging.info(\"AAC: transition event before playback\")\n if event.variables[\"transport_state\"] == \"PLAYING\":\n has_played = True\n logging.info(\"AAC: has_played set to True\")\n\n # General case for other file types. Note that pausing (PAUSED_PLAYBACK)\n # does not terminate the loop, to allow playback to be resumed\n if event.variables[\"transport_state\"] == \"STOPPED\":\n event_unsubscribe(sub)\n return True\n\n except Empty:\n pass\n\n\ndef is_supported_type(filename):\n file_upper = filename.upper()\n for type in SUPPORTED_TYPES:\n if file_upper.endswith(\".\" + type):\n # Supported file type\n return True\n else:\n return False\n\n\ndef play_local_file(speaker, pathname):\n # speaker is a SoCo instance\n # pathname is the local file to be played\n\n if not path.exists(pathname):\n error_and_exit(\"File '{}' not found\".format(pathname))\n return False\n\n directory, filename = path.split(pathname)\n\n if not is_supported_type(filename):\n error_and_exit(\n \"Unsupported file type; must be one of: {}\".format(SUPPORTED_TYPES)\n )\n return False\n\n # Make filename compatible with URL naming\n url_filename = urllib.parse.quote(filename)\n\n server_ip = get_server_ip(speaker)\n if not server_ip:\n error_and_exit(\"Can't determine an IP address for web server\")\n return False\n logging.info(\"Using server IP address: {}\".format(server_ip))\n\n # Start the webserver (runs in a daemon thread)\n speaker_ips = []\n for zone in speaker.all_zones:\n speaker_ips.append(zone.ip_address)\n httpd = http_server(server_ip, directory, url_filename, speaker_ips)\n if not httpd:\n error_and_exit(\"Cannot create HTTP server\")\n return False\n\n # This ensures that other running invocations of 'play_file'\n # receive their stop events, and terminate.\n logging.info(\"Stopping speaker '{}'\".format(speaker.player_name))\n speaker.stop()\n\n # Assemble the URI\n uri = \"http://\" + server_ip + \":\" + str(httpd.server_port) + \"/\" + url_filename\n logging.info(\"Playing file '{}' from directory '{}'\".format(filename, directory))\n logging.info(\"Playback URI: {}\".format(uri))\n\n # Send the URI to the speaker for playback\n # A special hack is required for AAC files, which have to be treated like radio.\n if filename.lower().endswith(\".aac\"):\n aac_file = True\n # speaker.play_uri(uri, force_radio=True)\n speaker.play_uri(uri)\n else:\n aac_file = False\n speaker.play_uri(uri)\n\n logging.info(\"Setting flag to stop playback on CTRL-C\")\n set_speaker_playing_local_file(speaker)\n\n logging.info(\"Waiting for playback to stop\")\n # SIGTERM enablement experiment for AAC files only\n # Also needed for Python < 3.7\n if aac_file or not PY37PLUS:\n set_sigterm(True)\n wait_until_stopped(speaker, uri, aac_file=aac_file)\n set_sigterm(False)\n else:\n wait_until_stopped(speaker, uri, aac_file=aac_file)\n\n logging.info(\"Playback stopped ... terminating web server\")\n httpd.shutdown()\n\n logging.info(\"Web server terminated\")\n set_speaker_playing_local_file(None)\n\n return True\n","sub_path":"soco_cli/play_local_file.py","file_name":"play_local_file.py","file_ext":"py","file_size_in_byte":9243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132941078","text":"import torch\r\n\r\ndata=torch.tensor([[3,4],[5,6],[7,8],[9,8],[6,5]])\r\nlabel=torch.tensor([0,0,1,0,1])\r\n\r\ncenter=torch.tensor([[1,1],[2,2]])\r\ncenter_exp=center.index_select(dim=0,index=label.long())\r\n\r\ncount=torch.histc(label.float(),bins=2,min=0,max=1)\r\ncount_exp=count.index_select(dim=0,index=label.long())\r\n\r\nprint(count_exp)\r\ncenter_loss=torch.sum(torch.div(torch.sqrt(torch.sum(torch.pow(data-center_exp,2),dim=1)),count_exp))\r\nprint(center_loss)","sub_path":"Day006/python/MTCNN/face_recog/center_test.py","file_name":"center_test.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51010202","text":"#!/usr/bin/python2\n# OpenPOWER Automated Test Project\n#\n# Contributors Listed Below - COPYRIGHT 2018\n# [+] International Business Machines Corp.\n#\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n'''\nMultithreaded library\n---------------------\nThis adds a new multithreaded library with having different\nvariants of thread based SSH/SOL session runs, each thread logs\nto a different log file.\n'''\n\nimport random\nimport unittest\nimport time\nimport threading\nimport pexpect\nimport os\n\nimport OpTestConfiguration\nfrom OpTestSystem import OpSystemState\nfrom Exceptions import CommandFailed\nfrom OpTestIPMI import IPMIConsoleState\n\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport OpTestLogger\nlog = OpTestLogger.optest_logger_glob.get_logger(__name__)\n\n\nclass OpSOLMonitorThread(threading.Thread):\n '''\n This thread just monitors the SOL console for any failures when tests are running\n on other SSH threads\n '''\n def __init__(self, threadID, name, execution_time=None):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.execution_time = execution_time\n conf = OpTestConfiguration.conf\n self.system = conf.system()\n self.system.goto_state(OpSystemState.OS)\n logfile = os.path.join(conf.output, \"console.log\")\n self.sol_logger(logfile)\n self.c = self.system.console.get_console(logger=self.logger)\n self.c_terminate = False;\n\n def run(self):\n log.debug(\"Starting %s\" % self.name)\n if self.execution_time:\n self.timeout_run()\n else:\n self.nontimeout_run()\n log.debug(\"Exiting %s\" % self.name)\n\n def timeout_run(self):\n execution_time = time.time() + 60 * self.execution_time\n log.debug(\"Starting %s for new SOL thread\" % self.name)\n while True:\n try:\n self.c.expect(\"\\n\", timeout=60)\n except pexpect.TIMEOUT:\n pass\n except pexpect.EOF:\n self.c.close()\n self.c = self.system.console.get_console()\n if time.time() > execution_time:\n break\n log.debug(\"Thread exiting after run for desired time\")\n\n def nontimeout_run(self):\n log.debug(\"Starting %s for new SOL thread\" % self.name)\n while True:\n try:\n self.c.expect(\"\\n\", timeout=60)\n except pexpect.TIMEOUT:\n pass\n except pexpect.EOF:\n self.c.close()\n self.c = self.system.console.get_console()\n\n if self.c_terminate:\n break\n log.debug(\"Terminating SOL monitoring thread\")\n\n def console_terminate(self):\n self.c_terminate = True\n\n def sol_logger(self, logfile):\n '''\n\tNon fomated console log.\n '''\n self.logger = logging.getLogger(\"sol-thread\")\n self.logger.setLevel(logging.DEBUG)\n file_handler = RotatingFileHandler(logfile, maxBytes=2000000, backupCount=10)\n self.logger.addHandler(file_handler)\n\nclass OpSOLMonitorThreadVM(threading.Thread):\n '''\n This thread just monitors the SOL console for any failures when tests are running\n on other SSH threads. This thread can be terminated by just calling console_terminate\n from parent process.\n '''\n def __init__(self):\n threading.Thread.__init__(self)\n conf = OpTestConfiguration.conf\n self.system = conf.system()\n self.hmc = self.system.hmc\n self.hmc.poweron_lpar()\n self.c = self.hmc.get_console()\n self.c_terminate = False\n\n def run(self):\n log.info(\"Starting PowerVM console monitoring thread\")\n while True:\n try:\n rc = self.c.expect([\"\\n\", \"Connection has closed\"], timeout=60)\n if rc == 1:\n log.info(\"LPAR console is gone\")\n while True:\n if self.hmc.check_vterm():\n time.sleep(5)\n log.debug(\"Waiting for console\")\n else:\n self.c = self.hmc.get_console()\n break\n except pexpect.TIMEOUT:\n pass\n except pexpect.EOF:\n log.info(\"LPAR console is gone\")\n while True:\n if self.hmc.check_vterm():\n time.sleep(5)\n log.debug(\"Waiting for console\")\n else:\n self.c = self.hmc.get_console()\n break\n\n if self.c_terminate:\n break\n log.debug(\"Terminating SOL monitoring thread\")\n\n def console_terminate(self):\n self.hmc.close_console(self.c)\n self.c_terminate = True\n","sub_path":"common/OpTestSOL.py","file_name":"OpTestSOL.py","file_ext":"py","file_size_in_byte":5359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"210579326","text":"\"\"\"\nBinary search trees are a data structure that enforce an ordering over\nthe data they store. That ordering in turn makes it a lot more efficient\nat searching for a particular piece of data in the tree.\n\nThis part of the project comprises two days:\n1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`\n on the BSTNode class.\n2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods\n on the BSTNode class.\n\"\"\"\n\n\nclass BSTNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n # Insert the given value into the tree\n def insert(self, value):\n # if value < Node's value\n if value < self.value:\n # we need to go left\n # if we see that there is no left child,\n if self.left is None:\n # then we can wrap the value in a BSTNode and park it\n self.left = BSTNode(value)\n # otherwise there is a child\n else:\n # call the left child's `insert` method\n self.left.insert(value)\n # otherwise, value >= Node's value\n else:\n # we need to go right\n # if we see there is no right child,\n if self.right is None:\n # then we can wrap the value in a BSTNode and park it\n self.right = BSTNode(value)\n # otherwise there is a child\n else:\n # call the right child's `insert` method\n self.right.insert(value)\n\n # Return True if the tree contains the value\n # False if it does not\n def contains(self, target):\n # check if target value is equal to value\n if self.value == target:\n return True\n # if target is not equal to value check if we have a left or right\n # child and compare target to value to see which path to take\n # if target is < value take the left path\n elif self.left and target < self.value:\n return self.left.contains(target)\n # if target is > value take the right path\n elif self.right and target > self.value:\n return self.right.contains(target)\n # if there are no children and target != value then return False\n else:\n return False\n\n # Return the maximum value found in the tree\n def get_max(self):\n # check if node has a right child\n if self.right:\n # if there is a right child execute that node's get_max\n return self.right.get_max()\n # if no right child, this node is the greatest value in the BST\n return self.value\n \"\"\" # create a variable to store the current node\n current = self\n\n # if the current node has a right child\n # set current to the right child\n while current.right is not None:\n current = current.right\n\n # once we reach the right most leaf it will have\n # the greatest value that exists in the tree.\n # return that node's value\n return current.value \"\"\"\n\n # Call the function `fn` on the value of each node\n def for_each(self, fn):\n # execute callback fn on self\n fn(self.value)\n\n # if left child exisits...\n if self.left is not None:\n # pass the callback to the child\n self.left.for_each(fn)\n\n # if right child exisits...\n if self.right is not None:\n # pass the callback to the child\n self.right.for_each(fn)\n\n # Part 2 -----------------------\n\n # 1\n # \\\n # 8\n # /\n # 5\n # / \\\n # 3 7\n # / \\ /\n # 2 4 6\n\n # Print all the values in order from low to high\n # Hint: Use a recursive, depth first traversal\n def in_order_print(self, node):\n # left -> node -> right\n\n # dive down to the left most leaf\n # this will be the smallest value\n if node.left:\n node.left.in_order_print(node.left)\n\n # if no other left children exist this means\n # the current node is now the smallest value\n # that hasn't yet been handled. print the value\n print(node.value)\n\n # if the node has a right child then we have values\n # that are greater than the current node. print that value\n if node.right:\n node.right.in_order_print(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative breadth first traversal\n def bft_print(self, node):\n # node -> left -> right\n from collections import deque\n\n # create a queue and pass it the first node\n queue = deque()\n queue.append(node)\n\n # continue to traverse while there are nodes in the queue\n while len(queue) > 0:\n current = queue.popleft()\n\n # if the next level has a left node...\n if current.left:\n # add to queue\n queue.append(current.left)\n\n # if the next level has a right node...\n if current.right:\n # add to queue\n queue.append(current.right)\n\n # print the current node's value\n print(current.value)\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n def dft_print(self, node):\n # node -> left -> right OR node -> right -> left\n from collections import deque\n\n # create a queue and pass it the first node\n queue = deque()\n queue.append(node)\n\n # continue to traverse while there are nodes in the queue\n while len(queue) > 0:\n # get first node in queue\n current = queue.popleft()\n\n # print current node's value\n print(current.value)\n\n # if current node has a left child,\n # execute that child's dft_print()\n if(current.left):\n current.left.dft_print(current.left)\n\n # if current node has a right child,\n # execute that child's dft_print()\n if(current.right):\n current.right.dft_print(current.right)\n\n # Stretch Goals -------------------------\n # Note: Research may be required\n\n # Print Pre-order recursive DFT\n def pre_order_dft(self, node):\n # node -> left -> right\n self.dft_print(node)\n\n # Print Post-order recursive DFT\n def post_order_dft(self, node):\n # left -> right -> node\n\n # if node has a left child,\n # execute that child's post_order_dft()\n if(node.left):\n node.left.post_order_dft(node.left)\n\n # if node node has a right child,\n # execute that child's post_order_dft()\n if(node.right):\n node.right.post_order_dft(node.right)\n\n # print node's value\n print(node.value)\n","sub_path":"names/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":6913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69140038","text":"from defs import *\nimport random\n\nrandimg = Blueprint('randimg', __name__, template_folder='views')\n\n@randimg.route('/randimg')\ndef randimg_route():\n num_images = get_num_results()\n imageid = random.randint(1, num_images)\n return redirect(\"/image?id=\"+str(imageid))\n","sub_path":"controllers/randimg.py","file_name":"randimg.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"572240200","text":"\nimport numpy as np\n\nfrom gator import predict, init\n\n\ndef test_basic(n_samples=1, n_objects=10):\n \n # force init w/ given num objects returned (init happens on first call otherwise)\n init(n_objects=n_objects)\n \n # should return a list of dicts with one dict per sample and n_objects per dict as {obj_name: score} key, value pairs\n images_array = np.random.randint(0, 255, size=(n_samples, 299, 299, 3))\n objs = predict(images_array)\n assert isinstance(objs, list) and len(objs) == n_samples\n # assert isinstance(objs[0], dict) and len(objs[0]) == n_objects\n assert isinstance(list(objs[0].keys())[0], str)\n assert isinstance(list(objs[0].values())[0], np.float32)\n","sub_path":"tests/test_all.py","file_name":"test_all.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"531953098","text":"#!/usr/env/bin python\n\nfrom google.appengine.ext import db\n\n\nclass Post(db.Model):\n title = db.StringProperty(required=True)\n html_text = db.TextProperty(required=True)\n markdown_text = db.TextProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n last_modified = db.DateTimeProperty(auto_now=True)\n slug = db.StringProperty(required=False)\n\n @classmethod\n def by_id(cls, post_id):\n return Post.get_by_id(post_id, parent=None)\n\n @classmethod\n def by_slug(cls, post_slug):\n return Post.all().filter('slug =', post_slug).get()\n\n\nclass Tag(db.Model):\n name = db.StringProperty(required=True)\n slug = db.StringProperty(required=True)\n description = db.TextProperty()\n\n\nclass PostTags(db.Model):\n post = db.ReferenceProperty(Post, collection_name='tags')\n name = db.StringListProperty() # stores a list of one or more tags\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"212236808","text":"import webapp2\nimport jinja2\nimport os\nimport Models\n\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\n\njinja_environment = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))\n\nclass Dashboard(webapp2.RequestHandler):\n def get(self):\n \n user = users.get_current_user() \n \n if user:\n \n pasyer_users = db.GqlQuery(\"SELECT * \"\n \"FROM Site_User \"\n \"WHERE userid = :1 \",\n user.user_id())\n \n current_user = False\n for pasyer_user in pasyer_users:\n current_user = pasyer_user\n\n if not current_user:\n self.redirect(\"/settings\")\n else:\n \n payslips = db.GqlQuery(\"SELECT * \"\n \"FROM Payslip \"\n \"WHERE ANCESTOR IS :1 \",\n Models.payslip_key(user.user_id()))\n \n income = 0\n tax = 0\n payslip_count = 0 \n for payslip in payslips:\n income+= payslip.income\n tax += payslip.tax\n payslip_count += 1\n \n files = db.GqlQuery(\"SELECT * \"\n \"FROM File \"\n \"WHERE ANCESTOR IS :1 \",\n Models.file_key(user.user_id()))\n file_count = 0 \n for file in files:\n file_count += 1\n \n \n #set stylesheets needed per page \n specific_urls = \"\"\"\n \n \"\"\"\n \n dashboard_template_values = {\n 'name': current_user.name,\n 'email': current_user.email,\n 'account_type': current_user.account_type,\n 'payslip_quantity': payslip_count,\n 'file_quantity': file_count,\n 'income': income,\n 'tax': tax,\n 'net': income - tax\n }\n \n template = jinja_environment.get_template('Page_Content/dashboard.html')\n dashboard_template = template.render(dashboard_template_values)\n \n url = users.create_logout_url(self.request.uri)\n nav = \"\"\"\n \n \"\"\" % url\n \n \n template_values = {\n 'specific_urls':specific_urls,\n 'nav': nav,\n 'content': dashboard_template\n }\n \n template = jinja_environment.get_template('index.html')\n self.response.out.write(template.render(template_values))\n else:\n self.redirect('/')\n\napp = webapp2.WSGIApplication([('/dashboard', Dashboard)], debug=True)\n","sub_path":"src/Dashboard.py","file_name":"Dashboard.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403269986","text":"\n### Prepare imports\nfrom scripts_pipeline.PathsManagement import Var, PathsManagement as Paths\nfrom scripts_pipeline.Experiment import Experiment\nfrom scripts_pipeline.ClassifyNewData import ClassifyNewContestDataAfterExperiment\nimport itertools\n\ndef combinations_any_length(l):\n comb = []\n for i in range(len(l)):\n comb += itertools.combinations(l,i+1)\n return comb\n\ndef experiment_name(num_experiment, dataset_name, features, classifier, normalize_data, class_weight, use_grid_search, epochs, batch):\n return \"experiment\" + str(num_experiment) + Paths.util_names_separator(dataset_name, '_'.join(features), classifier,\n \"normalize\" + normalize_data,\n \"weight\" + str(class_weight),\n \"use_grid_search\" + str(use_grid_search),\n \"epochs\" + str(epochs),\n \"batch\" + str(batch))\n\n##############\n# offenseval experiment\n#############\n\nFOLDS = 10\nnew_data_path = \"/Users/paulafortuna/PycharmProjects/HatEval/original_datasets/OffensEval/testset-taska.tsv\"\n\nexperiment_id = \"extract_LSTMFeatures\"\ndataset = \"offenseval\"\n\n\nexp = Experiment(experiment_name=experiment_id,\n dataset_name=dataset, # hateval_es hateval_en test hateval_en_my_division zeerak\n apply_data_preprocessing=[],\n features_to_extract=[Var.glove_twitter_200_en], # Var.sentiment_vader, Var.hatebase, Var.glove_twitter_25_en[]\n features_to_use=[Var.glove_twitter_200_en],\n normalize_data=Var.none, # Var.min_max, Var.normalize_gaussian , Var.normalize_linear_algebra\n classifier_name=Var.LSTMFeatures, # Var.LSTMFeatures Var.linear_svm, Var.CVgridSearchLSTM, Var.xgBoost, Var.LogisticRegressionClassifier, Var.RandomForest\n consider_class_weight=False,\n folds_cross_validation=FOLDS,\n use_grid_search=False,\n epochs=10,\n batch=128\n )\nexp.start_experiment()\n\nexperiment_id = \"other_features\"\nexp = Experiment(experiment_name=experiment_id,\n dataset_name=dataset, # hateval_es hateval_en test hateval_en_my_division zeerak\n apply_data_preprocessing=[],\n features_to_extract=[Var.hatebase, Var.sentiment_vader], # Var.sentiment_vader, Var.hatebase, Var.glove_twitter_25_en[]\n features_to_use=[Var.hatebase, Var.sentiment_vader],\n normalize_data=Var.none, # Var.min_max, Var.normalize_gaussian , Var.normalize_linear_algebra\n classifier_name=Var.xgBoost, # Var.LSTMFeatures Var.linear_svm, Var.CVgridSearchLSTM, Var.xgBoost, Var.LogisticRegressionClassifier, Var.RandomForest\n consider_class_weight=False,\n folds_cross_validation=FOLDS,\n use_grid_search=False,\n epochs=10,\n batch=128\n )\nexp.start_experiment()\n\n\ndef make_experiments():\n num_experiment = 0\n datasets_to_use = [dataset]\n for dataset_name in datasets_to_use:\n print(dataset_name)\n if num_experiment <20000:\n for features in combinations_any_length([Var.LSTMFeatures, Var.hatebase, Var.sentiment_vader]):\n for classifier in [Var.xgBoost]:\n for normalize_data in [Var.none]:\n for class_weight in [False]:\n for use_grid_search in [True]:\n num_experiment += 1\n epochs = 10\n batch = 128\n exp_name = experiment_name(num_experiment, dataset_name, features, classifier, normalize_data,\n class_weight, use_grid_search, epochs, batch)\n print(exp_name)\n exp = Experiment(experiment_name=exp_name,\n dataset_name=dataset_name,\n apply_data_preprocessing=[],\n features_to_extract=[],\n features_to_use=features,\n normalize_data=normalize_data,\n classifier_name=classifier,\n consider_class_weight=class_weight,\n folds_cross_validation=FOLDS,\n use_grid_search=use_grid_search,\n epochs=epochs,\n batch=batch\n )\n exp.start_experiment()\n\n\nexperiments_to_use = [\"extract_LSTMFeatures\",\n \"experiment5offenseval_LSTMFeatures_sentiment_vader_xgBoost_normalizenone_weightFalse_use_grid_searchTrue_epochs10_batch128\",\n \"experiment7offenseval_LSTMFeatures_hatebase_sentiment_vader_xgBoost_normalizenone_weightFalse_use_grid_searchTrue_epochs10_batch128\",\n \"experiment1offenseval_LSTMFeatures_xgBoost_normalizenone_weightFalse_use_grid_searchTrue_epochs10_batch128\"\n ]\nfor experiment_id in experiments_to_use:\n classify_new_data = ClassifyNewContestDataAfterExperiment(experiment_id)\n classify_new_data.start_classification(new_data_path, \"test_new_data_offenseval\", True, \"id\")","sub_path":"main_offenseval_a.py","file_name":"main_offenseval_a.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"230525040","text":"from openerp.osv import osv, fields\n\nclass base_config_settings(osv.TransientModel):\n _inherit = 'base.config.settings'\n\n _columns = {\n 'signup_template_user_id': fields.many2one('res.users', 'Template user for new users created through signup')\n }\n\n def get_default_signup(self, cr, uid, fields, context=None):\n icp = self.pool.get('ir.config_parameter')\n return {\n 'signup_template_user_id': icp.get_param(cr, uid, 'signup.template_user_id', 0) or False\n }\n\n def set_signup(self, cr, uid, ids, context=None):\n config = self.browse(cr, uid, ids[0], context=context)\n icp = self.pool.get('ir.config_parameter')\n icp.set_param(cr, uid, 'signup.template_user_id', config.signup_user_template_id.id)\n\n","sub_path":"signup/res_config.py","file_name":"res_config.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"644056230","text":"import sys\nimport os\nimport fcntl\nimport requests\nimport logging\nimport time\nimport json\nimport glob\n\nconfiguration = json.load(open(\"configuration.json\"))\ninstances = json.load(open(\"instances.json\"))\n\nlogger = None\n\ndef set_safe_locale():\n \"\"\"Make sure we have a safe and unproblematic locale setting\"\"\"\n\n for name in os.environ.keys():\n if name.startswith(\"LC_\"):\n del os.environ[name]\n\n if \"LANGUAGE\" in os.environ:\n del os.environ[\"LANGUAGE\"]\n\n os.environ[\"LANG\"] = \"C\"\n\ndef configure_logging():\n global logger\n\n logging.basicConfig(format=\"%(asctime)-15s | %(levelname)-7s | %(message)s\",\n stream=sys.stdout)\n\n logger = logging.getLogger(\"critic\")\n logger.setLevel(logging.DEBUG)\n\n return logger\n\ndef locked_directory(path):\n class LockFile(object):\n def __init__(self, filename):\n self.filename = filename\n self.lock_file = open(filename, \"w\")\n fcntl.flock(self.lock_file, fcntl.LOCK_EX)\n self.lock_file.write(\"%d\\n\" % os.getpid())\n def __enter__(self):\n return self\n def __exit__(self, *args):\n self.lock_file.close()\n return False\n\n return LockFile(os.path.join(path, \".lock\"))\n\nclass Semaphore(object):\n def __init__(self, path, limit, name):\n self.path = path\n self.limit = limit\n self.name = name\n\n def __enter__(self):\n pid_filename = os.path.join(self.path, self.name + \".pid\")\n while True:\n with locked_directory(self.path):\n if os.path.exists(pid_filename):\n raise Exception(\"Am I already running?!?\")\n count = len(glob.glob(os.path.join(self.path, \"*.pid\")))\n if count < self.limit:\n with open(pid_filename, \"w\") as pid_file:\n print >>pid_file, str(os.getpid())\n break\n time.sleep(0.1)\n return self\n\n def __exit__(self, *args):\n pid_filename = os.path.join(self.path, self.name + \".pid\")\n if os.path.exists(pid_filename):\n os.unlink(pid_filename)\n\nclass Critic(object):\n def __init__(self):\n self.session = None\n configure_logging()\n\n def initialize(self):\n while True:\n try:\n self.session = requests.Session()\n self.session.post(\n \"%s/validatelogin\" % configuration[\"critic-url\"],\n data=json.dumps({\n \"fields\": {\n \"username\": configuration[\"critic-username\"],\n \"password\": configuration[\"critic-password\"]\n }\n }))\n except Exception:\n logger.exception(\"login failed\")\n time.sleep(1)\n else:\n break\n\n def operation(self, path, data):\n while True:\n if self.session is None:\n self.initialize()\n try:\n response = self.session.post(\n \"%s/%s\" % (configuration[\"critic-url\"], path),\n data=json.dumps(data))\n if response.status_code == 500:\n logger.error(\"Operation failed:\\n\" + response.text)\n response.raise_for_status()\n return response.json()\n except Exception:\n self.reset()\n logger.exception(\"operation failed\")\n time.sleep(1)\n\n def reset(self):\n self.session = None\n","sub_path":"client/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16207370","text":"import config\nimport os\nfrom logging import getLogger, INFO, FileHandler, Formatter, StreamHandler\nimport random\nimport numpy as np\nimport torch\n\ndef init_logger(log_name = 'train'):\n log_file = f'{config.LOG_DIR}{log_name}.csv'\n logger = getLogger(__name__)\n logger.setLevel(INFO)\n handler1 = StreamHandler()\n handler1.setFormatter(Formatter(\"%(message)s\"))\n handler2 = FileHandler(filename=log_file)\n handler2.setFormatter(Formatter(\"%(message)s\"))\n logger.addHandler(handler1)\n logger.addHandler(handler2)\n return logger\n\ndef seed_torch(seed = config.SEED):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n","sub_path":"backup/seedandlog.py","file_name":"seedandlog.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550258212","text":"import pytest\nimport logging\nimport time\nimport os\n\nfrom sovrin_client.test.agent.bulldog_helper import bulldogLogger\nfrom sovrin_common.config import agentLoggingLevel\n\n\ndef testLoggerLevelSuccess(tdir):\n logger = bulldogLogger\n filePath = '{}/bulldog_test.log'.format(tdir)\n formatter = logging.Formatter('%(asctime)s %(message)s')\n if not os.path.exists(tdir):\n os.makedirs(tdir)\n fileHandler = logging.FileHandler(filePath, mode='a')\n fileHandler.setLevel(agentLoggingLevel)\n fileHandler.setFormatter(formatter)\n logger.addHandler(fileHandler)\n logger.warn(\"warning\")\n logger.debug(\"debug_logs_are_off\")\n time.sleep(2)\n file = open(filePath, 'r')\n txt = file.read()\n arr = txt.split(\" \")\n if any(\"debug_logs_are_off\" in word for word in arr):\n assert False\n else:\n assert True\n\n\ndef testLoggerLevelError(tdir):\n logger = bulldogLogger\n logger.setLevel(logging.DEBUG)\n filePath = '{}/bulldog_test_fail.log'.format(tdir)\n formatter = logging.Formatter('%(asctime)s %(message)s')\n if not os.path.exists(tdir):\n os.makedirs(tdir)\n fileHandler = logging.FileHandler(filePath, mode='a')\n fileHandler.setLevel(logging.DEBUG)\n fileHandler.setFormatter(formatter)\n logger.addHandler(fileHandler)\n logger.debug(\"debug_logs_are_on\")\n logger.warn(\"warning\")\n file = open(filePath, 'r')\n txt = file.read()\n arr = txt.split(\" \")\n if any(\"debug_logs_are_on\" in word for word in arr):\n assert True\n else:\n assert False\n","sub_path":"sovrin_client/test/agent/test_helper.py","file_name":"test_helper.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468716912","text":"import futu as ft\nimport time\nquote_ctx = ft.OpenQuoteContext(host=\"122.152.220.151\", port=65111)\n\n\ncode = 'SH.600000'\ncode_list = ['SH.600000']\n\ndef get_now_price():\n quote_ctx.subscribe(code_list, [ft.SubType.QUOTE])\n data = quote_ctx.get_stock_quote(code_list)\n # print(data)\n # title = list(data[-1])\n # print(title)\n print(list(data[-1].iloc[:, 8]))\n # print([i for i in list(data)])\n # print(data)\n\ndef get_max_volume():\n quote_ctx.subscribe(code_list, [ft.SubType.RT_DATA])\n for i in code_list:\n data = quote_ctx.get_rt_data(i)\n # index = list(data)\n print(data)\n # print(max(list(quote_ctx.get_rt_data(i)[-1].iloc[:, 7])))\n # print(index)\n\n# 上下文控制\nquote_ctx.start() # 开启异步数据接收\nquote_ctx.set_handler(ft.TickerHandlerBase()) # 设置用于异步处理数据的回调对象(可派生支持自定义)\n\nn=10\nwhile n:\n get_now_price()\n # get_now_price()\n n-=1\n time.sleep(10)\n\n# 停止异步数据接收\nquote_ctx.stop()\n\n# 关闭对象\nquote_ctx.close()","sub_path":"python/futuapi/futuapi.py","file_name":"futuapi.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"590112966","text":"'''\n画图\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport math\nimport json\n\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Function\n\n#本项目的import\nfrom logger import Logger\n\nif __name__ == \"__main__\":\n # 这一段代码需要根据作图来修改!!\n PATH1 = '../alexnet-10epoch/log'\n PATH2 = '../qalexnet_22epoch/log'\n PATH3 = '../baseline_mobilenet_result/log'\n log1,log2,log3 = Logger(),Logger(),Logger()\n log1.load_logger(PATH1)\n log2.load_logger(PATH2)\n log3.load_logger(PATH3)\n\n logs = [log3]\n legend = ['mobilenet']\n\n #=================================\n\n # 通用代码\n # 取出训练误差,由于要画在一张图上,所以截断\n train_list_length,test_list_length = len(logs[0].train_counter),len(logs[0].test_counter)\n for i in range(1,len(logs)):\n if len(logs[i].train_counter) < train_list_length:\n train_list_length = len(logs[i].train_counter)\n if len(logs[i].test_counter) < test_list_length:\n test_list_length = len(logs[i].test_counter)\n\n # 取出训练误差、预测精度\n train_losses,train_counters,test_accs,test_counters = [],[],[],[]\n for i in range(0,len(logs)):\n train_losses.append(logs[i].train_loss[0:train_list_length])\n test_accs.append(logs[i].test_accuracy[0:test_list_length])\n train_counters.append(logs[i].train_counter[0:train_list_length])\n test_counters.append(logs[i].test_counter[0:test_list_length])\n\n # 下面开始画图\n fig = plt.figure(dpi=1000)\n train_plot = fig.add_subplot(2,1,1)\n for i in range(0,len(logs)):\n train_plot.plot(train_counters[i],train_losses[i])\n train_plot.legend(legend,loc='upper right')\n train_plot.set_xlabel('number of training examples')\n train_plot.set_ylabel('cross entropy loss')\n\n test_plot = fig.add_subplot(2,1,2)\n for i in range(0,len(logs)):\n test_plot.plot(test_counters[i],test_accs[i])\n test_plot.legend(legend,loc='best')\n test_plot.set_xlabel('epochs')\n test_plot.set_ylabel('accuracy')\n \n plt.tight_layout() # 自动调整子图间距\n plt.savefig('对比baseline和bitG=16')\n # plt.show()","sub_path":"exp0629/log_print/figure.py","file_name":"figure.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"401372791","text":"'''\n Training code\n @author: Elyor Kodirov\n @date: 19/02/2019\n'''\n\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics.pairwise import pairwise_distances\n\nimport torch\nimport torch.optim\nimport torch.utils.data\nimport torch.nn.parallel\n\nfrom rn import ResNet50_pytorch\n\n\ndef read_img(path):\n img = plt.imread(path) / 255.0\n img = cv2.resize(img, (128, 384))\n return img\n\ndef main():\n load_weight_path = './ckpt/reidnet_smtr62_wfc_31.80379746835443.pth'\n model = ResNet50_pytorch()\n model = torch.nn.DataParallel(model).cuda()\n\n # use pretrained model\n\n model_dict = model.state_dict()\n # pretrained = torch.load('./baseline/resnet34_lm_pt3_v2_129_4_10.0_wofc.pth')\n pretrained = torch.load(load_weight_path)\n pretrained_dict = pretrained['state_dict']\n\n # 1. filter out unnecessary keys\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n # 2. overwrite entries in the existing state dict\n model_dict.update(pretrained_dict)\n # 3. load the new state dict\n model.load_state_dict(model_dict)\n model.eval()\n print('==> Pretrained model is loaded.')\n\n # read image [RGB] and change scale to [0, 1]\n anchor = read_img(path='images/anchor.jpg')\n positive = read_img(path='images/positive.jpg')\n negative = read_img(path='images/negative.jpg')\n\n # transpose such that [1xCxHxW]\n anchor = torch.from_numpy(np.transpose(anchor, (2, 0, 1))[np.newaxis])\n positive = torch.from_numpy(np.transpose(positive, (2, 0, 1))[np.newaxis])\n negative = torch.from_numpy(np.transpose(negative, (2, 0, 1))[np.newaxis])\n\n # extract features\n anchor_fea = model(anchor.float().cuda()).cpu().detach().numpy()\n positive_fea = model(positive.float().cuda()).cpu().detach().numpy()\n negative_fea = model(negative.float().cuda()).cpu().detach().numpy()\n\n # calculate distance\n emb_size = 2048\n sim_a_and_p = 1 - pairwise_distances(np.reshape(anchor_fea, (1, emb_size)), np.reshape(positive_fea, (1, emb_size)), 'cosine')\n sim_a_and_n = 1 - pairwise_distances(np.reshape(anchor_fea, (1, emb_size)), np.reshape(negative_fea, (1, emb_size)), 'cosine')\n\n print('Similarity for [anchor, positive]: {:0.2f} \\nSimilarity for [anchor, negative]: {:0.2f}'.format(\n sim_a_and_p[0][0], sim_a_and_n[0][0]))\n\n print(\"Ok\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"demo/demo_rn50.py","file_name":"demo_rn50.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"478420871","text":"words=[]\nfileOriginName='word_'\nindex=1\nmaxCount=0\n\nwordsFilePath = 'TOEFL_words'\t#在此输入文件路径\n\n#计算 1 中的行数\nlineCount = len(open(wordsFilePath,'rU').readlines())\n\n#先将单词全部放入列表words中\nwith open(wordsFilePath) as data:\n\tfor i in range(lineCount):\n\t\ts = data.readline();\n\t\twords.append(s);\n\n#找到单词中重复最多的单词数\nfor word in words:\n\tif words.count(word)>maxCount:\n\t\tmaxCount=words.count(word)\n\nindex = maxCount\n\nfor i in range(maxCount+1):\n\twords.append('\\n')\t\t#为了在输出过程中不输出'\\n',先在列表中计入 重复最多单词数+1 的'\\n'\n\nwhile (index>0):\n\tif index>15 or index<0: break;\t#安全措施\n\tif index<10:\n\t\tfileName=fileOriginName+str(0)+str(index); # 10 以内变成 01,02...这样的格式\n\telse:\n\t\tfileName=fileOriginName+str(index); # word_index 是单词出现index次的文件名\n\twith open(fileName,'w') as wordFile:\n\t\tfor word in words:\n\t\t\tif words.count(word)==index:\n\t\t\t\tprint(word,file=wordFile,end='')\n\t\t\t\twords.remove(word)\n\t\t\t\twords.insert(0,'\\n')\t#如果不在第一位补位,则不会遍历所有的word\n\tindex = index-1\n","sub_path":"words_classify/words_classify.py","file_name":"words_classify.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610838014","text":"#可以对str使用for循环\nname_str = \"liuwei\"\nfor i in name_str:\n print(i)\n#对list也能用\nname_list = list(name_str)\nfor i in name_list:\n print(i)\n#set还可以用\nname_set = set(name_str)\nfor i in name_set:\n print(i)\n#tuple也能呀\nname_tuple = tuple(name_str)\nfor i in name_tuple:\n print(i)\n#dict也不例外\nname_dict={\"name\":\"liuwei\",\"lang\":\"python\",\"website\":\"waleslau.github.io\"}\nfor i in name_dict:\n print(i,\"-->\",name_dict[i])\n\n#除了上面的数据类型之外,对文件也能够用for\n\nf = open(\"131.txt\",\"r\")\nfor line in f:\n print(line)\n\n\n#for在list解析中,用途也不可小觑","sub_path":"python/多使用for循环代替while循环.py","file_name":"多使用for循环代替while循环.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"495983882","text":"from __future__ import print_function\nfrom __future__ import absolute_import\n\nimport os\nimport pandas as pds\n# python 2/3 compatibility\ntry:\n basestring\nexcept NameError:\n basestring = str\n \nfrom pysat import DataFrame, Series\n\nclass Meta(object):\n \"\"\"\n Stores metadata for Instrument instance, similar to CF-1.6 netCDFdata standard.\n \n Parameters\n ----------\n metadata : pandas.DataFrame \n DataFrame should be indexed by variable name that contains at minimum the \n standard_name (name), units, and long_name for the data stored in the associated \n pysat Instrument object.\n \n Attributes\n ----------\n data : pandas.DataFrame\n index is variable standard name, 'units' and 'long_name' are also stored along\n with additional user provided labels.\n \n \"\"\"\n def __init__(self, metadata=None):\n self.replace(metadata=metadata)\n self.ho_data = {}\n\n def __eq__(self, other):\n if type(other) is type(self):\n return self.__dict__ == other.__dict__\n else:\n return False\n\n def __contains__(self, other):\n if other in self.data.index:\n return True\n if other in self.ho_data.keys():\n return True\n return False\n\n def __repr__(self):\n # cover 1D parameters\n output_str = 'Metadata for 1D parameters\\n'\n # print('Metadata for 1D parameters')\n # print(self.data)\n output_str += self.data.__repr__()\n output_str += '\\n'\n for item_name in self.ho_data.keys():\n output_str += '\\n\\n'\n output_str += 'Metadata for '+item_name+'\\n'\n # print(self.ho_data[item_name].data)\n output_str += self.ho_data[item_name].data.__repr__()\n return output_str\n\n def copy(self):\n from copy import deepcopy as deepcopy\n \"\"\"Deep copy of the meta object.\"\"\"\n return deepcopy(self) \n \n def __setitem__(self, name, value):\n \"\"\"Convenience method for adding metadata.\n \n Examples\n --------\n ::\n \n meta = pysat.Meta()\n meta['name'] = {'long_name':string, 'units':string}\n # update 'units' to new value\n meta['name'] = {'units':string}\n # update 'long_name' to new value\n meta['name'] = {'long_name':string}\n # attach new info with partial information, 'long_name' set to 'name2'\n meta['name2'] = {'units':string}\n # units are set to '' by default\n meta['name3'] = {'long_name':string}\n \n \"\"\"\n \n if isinstance(value,dict):\n # check if dict empty\n if value.keys() == []:\n if name in self:\n return\n # otherwise, continue on and set defaults\n\n # if not passed an iterable, make it one\n if isinstance(name, basestring):\n name = [name]\n for key in value.keys():\n value[key] = [value[key]]\n\n # if len(name) != len(value):\n # raise ValueError('Length of names and all inputs must be equal.')\n\n for key in value.keys():\n if len(name) != len(value[key]):\n raise ValueError('Length of names and inputs must be equal.')\n\n if 'meta' in value.keys():\n # process higher order stuff first\n # multiple assignment, check length is appropriate\n pop_list = []\n for item, val in zip(name, value['meta']):\n if val is not None:\n self[item] = val\n pop_list.append(item)\n for item in pop_list:\n value = value.pop(item)\n\n if 'units' not in value.keys():\n # provide default value, or copy existing\n value['units'] = []\n for item_name in name:\n if item_name not in self:\n value['units'].append('')\n else:\n value['units'].append(self.data.ix[item_name,'units'])\n\n if 'long_name' not in value.keys():\n # provide default value, or copy existing\n value['long_name'] = []\n for item_name in name:\n if item_name not in self:\n value['long_name'].append(item_name)\n else:\n value['long_name'].append(self.data.ix[item_name,'long_name'])\n\n new = DataFrame(value, index=name)\n for item_name,item in new.iterrows():\n if item_name not in self:\n self.data = self.data.append(item)\n else:\n # info already exists, update with new info\n for item_key in item.keys():\n self.data.ix[item_name,item_key] = item[item_key]\n\n elif isinstance(value, Series):\n self.data.ix[name] = value\n\n elif isinstance(value, Meta):\n # dealing with higher order data set\n self.ho_data[name] = value\n\n def __getitem__(self,key):\n \"\"\"Convenience method for obtaining metadata.\n \n Maps to pandas DataFrame.ix method.\n \n Examples\n --------\n ::\n \n print(meta['name'])\n \n \"\"\"\n if key in self.ho_data.keys():\n return self.ho_data[key]\n else:\n return self.data.ix[key]\n \n def replace(self, metadata=None):\n \"\"\"Replace stored metadata with input data.\n \n Parameters\n ----------\n metadata : pandas.DataFrame \n DataFrame should be indexed by variable name that contains at minimum the \n standard_name (name), units, and long_name for the data stored in the associated \n pysat Instrument object.\n \n \"\"\"\n import string\n if metadata is not None:\n if isinstance(metadata, DataFrame):\n self.data = metadata\n self.data.columns = map(string.lower, self.data.columns)\n if 'long_name' not in self.data.columns:\n self.data['long_name'] = self.data.index\n if 'units' not in self.data.columns:\n self.data['units'] = ''\n else:\n raise ValueError(\"Input must be a pandas DataFrame type. \"+\n \"See other constructors for alternate inputs.\")\n \n else:\n self.data = DataFrame(None, columns=['long_name', 'units'])\n #self._orig_data = self.data.copy()\n \n @classmethod\n def from_csv(cls, name=None, col_names=None, sep=None, **kwargs):\n \"\"\"Create instrument metadata object from csv.\n \n Parameters\n ----------\n name : string\n absolute filename for csv file or name of file\n stored in pandas instruments location\n col_names : list-like collection of strings\n column names in csv and resultant meta object\n sep : string\n column seperator for supplied csv filename\n\n Note\n ----\n column names must include at least ['name', 'long_name', 'units'], \n assumed if col_names is None.\n \n \"\"\"\n import pysat\n req_names = ['name','long_name','units']\n if col_names is None:\n col_names = req_names\n elif not all([i in col_names for i in req_names]):\n raise ValueError('col_names must include name, long_name, units.')\n \n if sep is None:\n sep = ','\n \n if name is None:\n raise ValueError('Must supply an instrument name or file path.')\n elif not isinstance(name, str):\n raise ValueError('keyword name must be related to a string') \n elif not os.path.isfile(name):\n # Not a real file, assume input is a pysat instrument name\n # and look in the standard pysat location.\n test = os.path.join(pysat.__path__[0],'instruments',name)\n if os.path.isfile(test):\n name = test\n else:\n #trying to form an absolute path for success\n test = os.path.abspath(name)\n if not os.path.isfile(test):\n raise ValueError(\"Unable to create valid file path.\")\n else:\n #success\n name = test\n \n mdata = pds.read_csv(name, names=col_names, sep=sep, **kwargs) \n \n if not mdata.empty:\n # make sure the data name is the index\n mdata.index = mdata['name']\n del mdata['name']\n return cls(metadata=mdata)\n else:\n raise ValueError('Unable to retrieve information from ' + name)\n \n # @classmethod\n # def from_nc():\n # \"\"\"not implemented yet, load metadata from netCDF\"\"\"\n # pass\n #\n # @classmethod\n # def from_dict():\n # \"\"\"not implemented yet, load metadata from dict of items/list types\"\"\"\n # pass\n","sub_path":"pysat/_meta.py","file_name":"_meta.py","file_ext":"py","file_size_in_byte":9383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"146631935","text":"from flask import Flask, request, jsonify\n\n#This allows you to create an external database that is capable of interacting with Flask\nfrom flask_sqlalchemy import SQLAlchemy \n\n#This gived us the ability to fetch posts from a schema of the database\nfrom flask_marshmallow import Marshmallow \n\nimport os\nfrom datetime import datetime\n\nfrom kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.properties import ObjectProperty\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.label import Label\n#from database import DataBase\n\n\n# Init app. \"__name__ is referencing this file\"\napp = Flask(__name__)\n\n# Makes sure the server knows exactly where the database file is\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# Tells the Flask application where the database will be stored. In this situation, we are using a sqlite database\n# A databse file is created called 'db.sqlite' \n# 'os.path.join(basedir' finds where the databse is located on our computer\n# 'db.sqlite' is the name of our database file\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n# Created the database, and connects it to the Flask application\ndb = SQLAlchemy(app)\n\n# Init ma\nma = Marshmallow(app)\n\n\n# Product Class/Model\n# This BlogPost class inherits from our database model\nclass BlogPost(db.Model):\n\n #This makes a column in the database to help identify each post. \n # Because this is the primary key, it is the main distinguisher between blog posts\n id = db.Column(db.Integer, primary_key=True)\n\n # 'nullable' means that there must be something in this field. \n # 'db.string(20)' prevents the name field from being more than 20 characters\n name = db.Column(db.String(20), nullable=False)\n content = db.Column(db.Text, nullable=False)\n\n # 'default=datetime.utcnow' returns the Coordinated Universale Time(UTC)\n date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)\n\n #These are the things we want added to the instance of every post\n def __init__(self, content, name):\n self.content = content\n self.name = name\n\n# Allows you to decide what fields you want to show from every post in the database\nclass BlogPostSchema(ma.Schema):\n class Meta:\n fields = ('id', 'name', 'content', 'date_posted')\n\n# Initializes the BlogPostSchema\n# Allows us to fetch a single post\nblogpost_schema = BlogPostSchema()\n\n# Allows us to fetch multiple posts\nblogposts_schema = BlogPostSchema(many=True)\n\nclass BlogActions:\n #App Routes call URLs\n\n # Create a Post. methods=['POST'] means that you can only use post requests on this webpage\n @app.route('/posts', methods=['POST'])\n\n #This is the code that runs whenever the url is called\n def posts(): \n \n # Uses the Flask request library to turn the information we will be placing into the 'content' field into JSON\n # JSON is code that is readable by a server\n post_content = request.json['content']\n post_name = request.json['name']\n\n # This adds a new row into the database \n # We only need to give it the content and the name because that is what we initialized\n new_post = BlogPost(content=post_content, name=post_name)\n\n # Adds to the database\n db.session.add(new_post)\n\n # Saves the entry we just added to the database\n db.session.commit()\n \n # returns to the client the new post we just added to the database\n # We use 'blogpost_schema' because it is a single post we are adding\n # 'jsonify' gives the server the new_post in JSON format\n return blogpost_schema.jsonify(new_post)\n\n\n # Get all Posts\n @app.route('/posts', methods=['GET'])\n def get_posts():\n \n all_posts = BlogPost.query.all()\n result = blogposts_schema.dump(all_posts)\n return jsonify(result)\n \n\n # Get Single Post\n @app.route('/posts/', methods=['GET'])\n def get_post(id):\n post = BlogPost.query.get(id)\n return blogpost_schema.jsonify(post)\n\n # Get posts since a specific post was made\n @app.route('/getsince/', methods=['GET'])\n def getSince(id):\n n = int(id)\n p = []\n p.append(n)\n n = n + 1\n\n while n != len(BlogPost.query.all()) + 1:\n p.append(n)\n n = n + 1\n\n posts = BlogPost.query.filter(BlogPost.id.in_(p))\n result = blogposts_schema.dump(posts)\n \n return jsonify(result)\n\n # Get the last n amount of posts\n @app.route('/lastn/', methods = ['GET'])\n def lastn(n):\n posts = BlogPost.query.order_by(BlogPost.id.desc()).limit(n)\n posts =posts[::-1]\n\n result = blogposts_schema.dump(posts)\n\n return jsonify(result)\n\n\n\n'''\nclass WindowManager(ScreenManager):\n # Responsible for moving things around on the screen\n pass\n\nclass ChatWindow(Screen):\n post = ObjectProperty(None)\n\nkv = Builder.load_file(\"my.kv\")\n\nsm = WindowManager()\n\nscreens = [ChatWindow(name=\"room\")]\nfor screen in screens:\n sm.add_widget(screen)\n\nsm.current = \"room\"\n\nclass MyMainApp(App):\n def build(self):\n return sm\n'''\n# This makes sure that if we are running this file directly, debug mode is turned on\nif __name__ == '__main__':\n\n #MyMainApp().run()\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"459949811","text":"# alist = []\n# l1 = []\n# l2 = []\n# from collections import Counter\n#\n#\n# def minion_game(string):\n# length = len(string)\n# global alist\n#\n# for i in range(length):\n# for j in range(i, length):\n# alist.append(string[i:j + 1])\n#\n# for word in alist:\n# if word[:1] in 'AEIOU':\n# l1.append(word)\n# else:\n# l2.append(word)\n# count_frequency()\n#\n#\n# def count_frequency():\n# score1 = Counter(l1)\n# score2 = Counter(l2)\n# player1 = 'Kevin'\n# player2 = 'Stuart'\n# score1 = list(score1.values())\n# score2 = list(score2.values())\n# if (sum(score1) > sum(score2)):\n# print('{} {}'.format(player1,sum(score1)))\n# elif (sum(score1) < sum(score2)):\n# print('{} {}'.format(player2, sum(score2)))\n# elif sum(score1) == sum(score2):\n# print('Draw')\n\ns = input()\n\nvowels = 'AEIOU'\n\nkevsc = 0\nstusc = 0\nfor i in range(len(s)):\n if s[i] in vowels:\n kevsc += (len(s)-i)\n else:\n stusc += (len(s)-i)\n\nif kevsc > stusc:\n print (\"Kevin\", kevsc)\nelif kevsc < stusc:\n print (\"Stuart\", stusc)\nelse:\n print(\"Draw\")\n\n\n\n\n","sub_path":"Minions_Game.py","file_name":"Minions_Game.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"233933827","text":"#!/usr/bin/python3\nimport sys, re, math\n\ndef count(file):\n average = 0\n deviation = 0\n num = 0\n\n for line in file:\n if line.startswith(\"open\"):\n break\n for line in file:\n result = re.search('(\\d+) usec', line)\n if result:\n value = int(result.group(1))\n average += value\n deviation += value * value\n num += 1\n if num > 0:\n average /= num\n deviation = math.sqrt(deviation / num)\n else:\n return None\n\n return average, deviation\n\nif __name__ == \"__main__\":\n if(len(sys.argv) < 2):\n print(\"Not enough arguments!\")\n else:\n try:\n with open(sys.argv[1], 'r') as f:\n average, deviation = count(f)\n print(\"average : \" + str(average) + \"\\ndeviation : \" + str(deviation))\n except Exception as e:\n print(e.strerror, file=sys.stderr)\n","sub_path":"problems-3/pyataev/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"339616834","text":"import os\nimport random\n\nfrom flask import Flask, jsonify\n\napp = Flask(__name__)\n\n\n@app.route('/get_age/', methods=['GET'])\ndef get_user_id_by_name(name):\n return jsonify(random.randint(1, 100)), 200\n\n\nif __name__ == '__main__':\n host = os.environ.get('STUB_HOST', '127.0.0.1')\n port = os.environ.get('STUB_PORT', '8090')\n\n app.run(host, port)\n","sub_path":"SDET-Python-homework-7/code/stub/flask_stub.py","file_name":"flask_stub.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"120519227","text":"\ndef eval(p, x):\n y = 0\n power = 1\n for coeff in p:\n y += coeff * power\n power *= x\n return y\n\ndef binary_search(p, y):\n lo = 0\n hi = y\n\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n value = eval(p, mid)\n\n if value == y:\n return mid\n elif value < y:\n lo = mid + 1\n else:\n hi = mid - 1\n\n return -1\n\nt = int(input())\n\nfor _ in range(t):\n n, y = map(int, input().split(\" \"))\n p = list(map(int, input().split(\" \")))\n x = binary_search(p, y)\n\n if x == -1:\n print(\"N/A\")\n else:\n print(x)","sub_path":"vanilla_solutions/ps5_jaime.py","file_name":"ps5_jaime.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"240389236","text":"import numpy as np\n\nclass Scheduler:\n def __init__(self, lr_max, lr_min, T_max):\n self.lr_max = lr_max\n self.lr_min = lr_min\n self.T_max = T_max\n\n def cosine_decay(self, epoch):\n lr = self.lr_min\n lr += 1/2*(self.lr_max-self.lr_min)*(1+np.cos(epoch/self.T_max*np.pi))\n return lr\n","sub_path":"farmer/ncc/schedulers/schedulers.py","file_name":"schedulers.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"390664354","text":"# Download all staff members listed on page to transfer to new site\n\nimport requests, bs4\n\nurl = 'http://citrusridge.polk-fl.net/staff/'\nres = requests.get(url)\nres.raise_for_status()\n\nsoup = bs4.BeautifulSoup(res.text,'html5lib')\n\nnames = soup.find_all(\"h3\", class_=\"staff-member-name\")\nemails = soup.find_all(\"a\", class_=\"staff-member-email\")\n\n\nfor name, email in zip(names, emails):\n print(name.text, email.text)\n","sub_path":"staff_download.py","file_name":"staff_download.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"71244110","text":"from flask import Flask, render_template, request\napp = Flask(__name__)\n\nsnippets = [\n\t{\n\t\"name\":\"a snippet\",\n\t\"lang\":\"python\",\n\t\"desc\":\"a short snippet\",\n\t\"snip\":\"print('hello')\"\n\t},\n\t{\n\t\"name\":\"cool code\",\n\t\"lang\":\"html\",\n\t\"desc\":\"some descriptidsjkfaj\",\n\t\"snip\":\"

Title here

\"\n\t}\n]\n\n@app.route(\"/\")\ndef index():\n\treturn render_template(\"index.html\")\n\n@app.route(\"/snippets/get/\")\ndef snippets_get():\n\treturn str(snippets).replace(\">\", \">\").replace(\"<\", \"<\")\n\n@app.route(\"/snippets/add/\", methods=[\"POST\", \"GET\"])\ndef snippets_add():\n\tdesc = request.args.get(\"desc\")\n\tsnip = request.args.get(\"snip\")\n\tname = request.args.get(\"name\")\n\tlang = request.args.get(\"lang\")\n\tnew = {\"desc\":desc, \"name\":name, \"lang\":lang, \"snip\":snip}\n\tsnippets.append(new)\n\treturn str(new)\n\napp.run(debug=True)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52404902","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file contains the definition of Vertex class and RandomWalks class\n\"\"\"\n\nimport numpy as np\n\nclass Vertex(object):\n \"\"\"Hold information about the vertex (neighbors, transition probabilties)\"\"\"\n \n def __init__(self, idx, transition_probas):\n self.idx = idx\n self.neighbors_idx = np.where(transition_probas > 0)[0]\n self.probas = transition_probas[self.neighbors_idx]\n\n\nclass RandomWalks(object):\n \"\"\"\n Perform walks and compute the total distances between all pairs of vertices\n over a minimum number of walks\n \"\"\"\n \n def __init__(self, vertices, min_n_walks):\n \"\"\"Initialize data before performing walks\"\"\"\n self.vertices = vertices\n self.min_n_walks = min_n_walks\n n_vertices = len(vertices)\n self.total_distances = np.zeros((n_vertices, n_vertices))\n self.n_walks = np.zeros((n_vertices, n_vertices))\n np.fill_diagonal(self.n_walks, self.min_n_walks)\n self.starting_step = np.nan * np.empty((n_vertices, n_vertices))\n \n def walk(self):\n \"\"\"\n Walk until the minimum number of walks have been performed \n over all pairs of vertices in the graph\n \"\"\"\n self.__init_walk()\n while(np.min(self.n_walks) < self.min_n_walks):\n self.__take_a_step()\n self.__update_distances()\n return self.total_distances, self.n_walks\n \n def __init_walk(self):\n \"\"\"Randomly determine the starting vertex\"\"\"\n self.current_vertex = np.random.choice(self.vertices)\n self.step = 0\n self.starting_step[self.current_vertex.idx] = self.step\n \n def __take_a_step(self):\n \"\"\"Move from a vertex to a neighbor according to transition probabilities\"\"\"\n vertex_idx = np.random.choice(self.current_vertex.neighbors_idx,\n p=self.current_vertex.probas)\n self.current_vertex = self.vertices[vertex_idx]\n self.step += 1\n \n def __update_distances(self):\n \"\"\"\n Update the total distances and the number of walks performed between vertices at a specific step\n Example:\n Let's consider the sequence of vertices v1 -> v3 -> v4 -> v3 -> v5\n This method will compute the distances\n d(v1 -> v5) = 4, d(v3 -> v5) = 3 and d(v4 -> v5) = 2 \n \"\"\"\n current_idx = self.current_vertex.idx\n previous_vertices = np.where(~np.isnan(self.starting_step[:, current_idx]))[0]\n self.total_distances[previous_vertices, \n current_idx] += self.step - self.starting_step[previous_vertices, current_idx]\n self.n_walks[previous_vertices, current_idx] += 1\n self.starting_step[previous_vertices, current_idx] = np.nan\n nan_idx = np.isnan(self.starting_step[current_idx, :])\n self.starting_step[current_idx, nan_idx] = self.step\n","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"193266628","text":"from math import sqrt\r\n\r\nstart, end = 11275, 16328\r\n\r\nqStart = int(sqrt(start))\r\nqEnd = int(sqrt(end))+1\r\nfor q in range( qStart, qEnd+1 ):\r\n n = q*q\r\n a = [q] # массив для хранения делителей\r\n for d in range(1, q):\r\n if n % d == 0:\r\n a = a + [d, n//d]\r\n if len(a) > 5: break\r\n if len(a) == 5:\r\n print( *sorted(a) )\r\n","sub_path":"tasks_25/solutions/25-24.py","file_name":"25-24.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"231798488","text":"import argparse\n\nimport torch\nfrom torch import optim\n\nfrom model.gan import GAN\nfrom model.io import ModelPackage\nfrom model.tacotron_new import Tacotron\nfrom trainer import Trainer\nfrom utils.config import Config\nfrom utils.io import get_latest_file\nfrom utils.paths import Paths\n\n\ndef get_device() -> torch.device:\n if torch.cuda.is_available():\n return torch.device('cuda')\n else:\n return torch.device('cpu')\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(\n description='Entrypoint for training the TacoGan model.')\n parser.add_argument(\n '--config', '-c', help='Point to the config.', default='config.yaml')\n\n args = parser.parse_args()\n device = get_device()\n paths = Paths()\n cfg = Config.load(args.config)\n ckpt_path = paths.ckpt/cfg.config_id\n print(ckpt_path)\n latest_ckpt = get_latest_file(ckpt_path, extension='.zip')\n if latest_ckpt:\n print(f'\\nLoading model from {latest_ckpt}')\n model = ModelPackage.load(latest_ckpt, device)\n model.cfg.update(cfg)\n else:\n print(f'\\nInitialising new model from {args.config}')\n print(f'Checkpoint path: {ckpt_path}')\n tacotron = Tacotron.from_config(cfg).to(device)\n gan = GAN.from_config(cfg).to(device)\n taco_opti = optim.Adam(tacotron.parameters())\n gen_opti = optim.Adam(gan.generator.parameters())\n disc_opti = optim.Adam(gan.discriminator.parameters())\n model = ModelPackage(\n tacotron=tacotron, gan=gan, taco_opti=taco_opti,\n gen_opti=gen_opti, disc_opti=disc_opti, cfg=cfg)\n\n trainer = Trainer(model.cfg)\n trainer.train(model)","sub_path":"train_tacogan.py","file_name":"train_tacogan.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"647147162","text":"product_and_price = input().split(\"|\")\r\nbudget = float(input())\r\n\r\nnew_list = []\r\nprofit = 0\r\nnew_budget = 0\r\n\r\nfor product in product_and_price:\r\n token = product.split(\"->\")\r\n item = token[0]\r\n price = float(token[1])\r\n if item == \"Clothes\" and price <= 50 and budget - price >= 0:\r\n budget -= price\r\n new_price = round(price * 1.40, 2)\r\n new_list.append(new_price)\r\n profit += new_price - price\r\n elif item == \"Shoes\" and price <= 35 and budget - price >= 0:\r\n budget -= price\r\n new_price = round(price * 1.40, 2)\r\n new_list.append(new_price)\r\n profit += new_price - price\r\n elif item == \"Accessories\" and price <= 20.50 and budget - price >= 0:\r\n budget -= price\r\n new_price = round(price * 1.40, 2)\r\n new_list.append(new_price)\r\n profit += new_price - price\r\n\r\nfor price in new_list:\r\n print(f\"{price:.2f}\", end=\" \")\r\nprint()\r\n\r\nnew_budget = sum(new_list) + budget\r\nprint(f\"Profit: {profit:.2f}\")\r\nif new_budget >= 150:\r\n print(\"Hello, France!\")\r\nelse:\r\n print(\"Time to go.\")","sub_path":"03.Lists_Basics/02.Exercise/09. Hello, France.py","file_name":"09. Hello, France.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403998116","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 31 12:10:51 2020\n\n@author: nt0ny\n\"\"\"\n\n\nimport frontmatter\nimport os\nfrom bs4 import BeautifulSoup\nimport urllib\nimport collections\nimport json\nimport time\nimport re\nimport numpy as np\n\n\ndir = 'people'\n\npeople = []\n\nname_map = {}\nfaculty_map = {}\n\nfor file in os.listdir(dir):\n if '.md' not in file:\n continue\n \n post = frontmatter.load(os.path.join(dir, file))\n \n search = []\n \n for t in post['tagList']:\n if 'alt-pubmed-author' in t:\n search = t.replace('alt-pubmed-author::', '').split(' ')\n break\n \n firstName = post['firstName'].split(' ')[0]\n people.append({'name':[firstName, post['lastName']], 'search':search, 'id':post['id']})\n name_map['{} {}'.format(firstName, post['lastName']).lower()] = post['id']\n name_map['{} {}'.format(firstName[0], post['lastName']).lower()] = post['id']\n \n if len(search) > 0:\n name_map['{} {}'.format(search[0], search[1]).lower()] = post['id']\n name_map['{} {}'.format(search[0][0], search[1]).lower()] = post['id']\n \n is_faculty = False\n \n for title in post['titles']:\n if 'Prof' in title:\n is_faculty = True\n break\n \n if is_faculty:\n faculty_map['{} {}'.format(firstName, post['lastName']).lower()] = post['id']\n faculty_map['{} {}'.format(firstName[0], post['lastName']).lower()] = post['id']\n \n if len(search) > 0:\n faculty_map['{} {}'.format(search[0], search[1]).lower()] = post['id']\n faculty_map['{} {}'.format(search[0][0], search[1]).lower()] = post['id']\n \n \n\npubmap = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict())))\n\nsel_pubmap = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict())))\n\n\nwith open('downloaded-publications.json', 'r') as f:\n publications = json.load(f)\n\nused = set()\n\nfor pub in publications:\n if (pub['pmid'] not in used):\n used.add(pub['pmid'])\n pubmap[pub['year']][pub['month']][pub['day']][pub['title']] = pub\n\nfor file in os.listdir('faculty'):\n if 'selected-publications.json' in file:\n print(file)\n \n person = file.replace('-selected-publications.json', '')\n \n with open(os.path.join('faculty', file), 'r') as f:\n selectedpublications = json.load(f)\n \n file2 = os.path.join('faculty', '{}-additional-publications.json'.format(person))\n \n if os.path.exists(file2):\n print(file2)\n with open(file2, 'r') as f:\n additionalpublications = json.load(f)\n \n for pub in additionalpublications:\n pub['tagList'].append('additional')\n \n selectedpublications.extend(additionalpublications)\n \n # copy to api \n # os.makedirs('../../static/api/v1/publications/{}/selected'.format(person), exist_ok=True) \n # with open('../../static/api/v1/publications/{}/selected/data.json'.format(person), 'w') as outfile:\n # json.dump(selectedpublications, outfile)\n \n for pub in selectedpublications:\n if 'article' not in pub['tagList']:\n pub['tagList'].append('article')\n \n if 'selected' not in pub['tagList']:\n pub['tagList'].append('selected')\n \n if 'selected::{}'.format(person) not in pub['tagList']:\n pub['tagList'].append('selected::{}'.format(person))\n \n if 'Article' in pub['tagList']:\n pub['tagList'].remove('Article')\n \n if 'doi' not in pub:\n pub['doi'] = ''\n \n if 'isbn' not in pub:\n pub['isbn'] = ''\n \n pub['authors'] = ', '.join(pub['authorList'])\n \n pubs = {'person':person, 'publications':selectedpublications}\n \n with open('selected-publications/{}.json'.format(person), 'w') as outfile:\n json.dump(pubs, outfile, indent=2)\n \n for pub in selectedpublications:\n sel_pubmap[pub['year']][pub['month']][pub['day']][pub['title']] = pub\n \n if pub['title'] not in pubmap[pub['year']][pub['month']][pub['day']]:\n pubmap[pub['year']][pub['month']][pub['day']][pub['title']] = pub\n else:\n # merge article tags\n pubmap[pub['year']][pub['month']][pub['day']][pub['title']]['tagList'] = list(sorted(np.union1d(pubmap[pub['year']][pub['month']][pub['day']][pub['title']]['tagList'], pub['tagList'])))\n \n # if (pub['pmid'] not in used):\n # used.add(pub['pmid'])\n # pubmap[pub['year']][pub['month']][pub['day']][pub['title']] = pub\n \n # else:\n # print('used', pub['pmid'])\n\n\n\n\n\nret = []\n\nfor year in reversed(sorted(pubmap)):\n for month in reversed(sorted(pubmap[year])):\n for day in reversed(sorted(pubmap[year][month])):\n for title in sorted(pubmap[year][month][day]):\n ret.append(pubmap[year][month][day][title])\n \nfor pub in ret:\n if 'Article' in pub['tagList']:\n pub['tagList'].remove('Article')\n \n if 'doi' not in pub:\n pub['doi'] = ''\n \n if 'isbn' not in pub:\n pub['isbn'] = ''\n \n institute_pub = False\n \n print(pub['title'], pub['authorList'])\n \n author = pub['authorList'][-1]\n \n if not re.match(r' +', author):\n firstName = author.lower().split(' ')[-1]\n firstName = firstName[0]\n lastName = ' '.join(author.lower().split(' ')[0:-1])\n name = '{} {}'.format(firstName, lastName)\n institute_pub = name in faculty_map\n \n if not institute_pub:\n author = pub['authorList'][0]\n \n if not re.match(r' +', author):\n firstName = author.lower().split(' ')[-1]\n firstName = firstName[0]\n lastName = ' '.join(author.lower().split(' ')[0:-1])\n name = '{} {}'.format(firstName, lastName)\n institute_pub = name in faculty_map\n \n if institute_pub:\n pub['tagList'].append('first-author')\n\n\npubs = {'person':'all', 'publications':ret} \nwith open('publications/all.json', 'w') as outfile:\n json.dump(pubs, outfile, indent=2)\n \n# pubs for all people\npub_map = collections.defaultdict(list)\n\nfor pub in ret:\n for person in pub['peopleList']:\n if 'powers' in person:\n print(person, pub['title'])\n pub_map[person].append(pub)\n \n\nfor person in pub_map:\n pubs = {'person':person, 'publications':pub_map[person]}\n \n with open('publications/{}.json'.format(person), 'w') as outfile:\n json.dump(pubs, outfile, indent=2)\n\n\nret2 = []\n\nfor year in reversed(sorted(sel_pubmap)):\n for month in reversed(sorted(sel_pubmap[year])):\n for day in reversed(sorted(sel_pubmap[year][month])):\n for title in sorted(sel_pubmap[year][month][day]):\n ret2.append(sel_pubmap[year][month][day][title])\n\n\npubs = {'person':'all', 'publications':ret2} \nwith open('selected-publications/all.json', 'w') as outfile:\n json.dump(pubs, outfile) #, indent=2)\n \n \n","sub_path":"content/3_merge_publications.py","file_name":"3_merge_publications.py","file_ext":"py","file_size_in_byte":7456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"87973018","text":"from numpy import mat, shape, zeros, multiply\nfrom numpy.random import random\n\n\nclass SMO:\n def looadDataSet(self, fileName):\n dataMat =[]; labelMat = []\n fr = open(fileName)\n for line in fr.readlines():\n lineArr = line.strip().split('\\t')\n dataMat.append([float(lineArr[0]),float(lineArr[1])])\n labelMat.append(float(lineArr[2]))\n return dataMat, labelMat\n\n\n def selectJrand(self, i, m):\n j=i\n while(j==i):\n j = int(random.uniform(0,m))\n return j\n\n def clipAlpha(self, aj, H, L):\n if aj > H:\n aj=H\n if L> aj:\n aj = L\n return aj\n def smoSimple(self, dataMatIn, classLabels, C, toler, maxIter):\n dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()\n b = 0; m,n = shape(dataMatrix)\n alphas = mat(zeros((m, 1)))\n iter = 0\n while (iter toler) and (alphas[i]>0)):\n j = self.selectJrand(i, m)\n fXj = float(multiply(alphas, labelMat).T*(dataMatrix*dataMatrix[j, :].T)) + b\n Ej = fXj - float(labelMat[j])\n alphaIold = alphas[i].copy(); alphJold = alphas[j].copy()\n\n\n\nif __name__ == \"__main__\":\n smo = SMO()\n dataSet, labelSet = smo.looadDataSet('testSet.txt')\n print(dataSet)\n print(labelSet)\n\n print(zeros((10,1)))\n\n\n\n\n\n","sub_path":"ch06/SMO.py","file_name":"SMO.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"194361393","text":"#!/usr/bin/env python3\n\nimport subprocess\nimport socket\nimport time\nimport sys\n\ndef FormatMac(MacAddr):\n #\n newMacAddr = \"\"\n #\n i = 0\n #\n while(i <= len(MacAddr)-2):\n #\n for j in range(0,2):\n #\n newMacAddr += MacAddr[i]\n #\n i += 1\n #\n newMacAddr += \":\"\n #\n newMacAddr = newMacAddr[0:len(newMacAddr)-1]\n #\n return newMacAddr\n\n\ndef MonitorMode():\n #\n amng_chk = subprocess.check_output(['which','airmon-ng'])\n #\n if(bytes(\"airmon-ng\",'utf-8') in amng_chk):\n #\n pass\n #\n else:\n #\n sys.exit(\"[!] This script requires airmon-ng\")\n #\n print(\"[+] Gathering interface data... \")\n #\n time.sleep(1)\n #\n subprocess.call(['iwconfig'])\n #\n print()\n #\n iface = input(\"[+] Enter the interface for monitoring-> \")\n #\n try:\n #\n subprocess.call(['airmon-ng','start',iface])\n #\n except:\n #\n sys.exit(\"[!] Transition to monitor mode failed \")\n\n\ndef main():\n #\n print(\"<-- Wireless Sniffer -->\")\n #\n sniffer = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, 3)\n #\n print(\"[*] Setting monitor mode \")\n #\n time.sleep(3)\n #\n MonitorMode()\n #\n subprocess.call(['iwconfig'])\n #\n print()\n #\n bind_iface = input(\"[+] Enter the monitoring interface-> \")\n #\n try:\n #\n sniffer.bind((bind_iface,0x003))\n #\n except:\n #\n sys.exit(\"[!] Bind operation failed \")\n #\n print()\n #\n print(\"*** Sniffing Wireless Traffic ***\")\n #\n while(True):\n #\n frames = sniffer.recvfrom(6000)\n #\n frame = frames[0]\n #\n if(frame[18] == 128):\n #\n bssid = frame[34:40].hex()\n #\n bssid = FormatMac(bssid)\n #\n ssid = frame[55:75]\n #\n print(\"[*] SSID -> \", ssid)\n #\n print(\"[*] BSSID -> \", bssid)\n #\n time.sleep(2)\n\nif(__name__ == '__main__'):\n #\n main()\n","sub_path":"Python-Penetration-Testing/WirelessSniffer.py","file_name":"WirelessSniffer.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"42380699","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: F:\\Coding\\py\\IPython Notebooks\\experiment\\chunking\\lazyEEG\\algorithms\\classifier.py\n# Compiled at: 2017-04-28 11:58:35\n# Size of source mod 2**32: 6078 bytes\nfrom ..default import *\nfrom .. import group\nfrom .general import *\nfrom ..graph import put as plot_put\nfrom ..statistics import process\nfrom ..statistics import test\nfrom tqdm import tqdm\nimport sklearn\nfrom sklearn import linear_model\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import accuracy_score\n\ndef condition_shuffled(data):\n group_labels = list(data.index.get_level_values(level='cond_group'))\n random.shuffle(group_labels)\n data.index = data.index.set_labels(group_labels, level='cond_group')\n return data\n\n\ndef run_model(X, Y, model, fold, test_size):\n score_train_folds = []\n score_test_folds = []\n coef_folds = []\n for train_index, test_index in StratifiedShuffleSplit(fold, test_size=test_size).split(X, Y):\n model.fit(X[train_index], Y[train_index])\n if getattr(model, 'predict_proba', None):\n prob_train = model.predict_proba(X[train_index])[:, 1]\n prob_test = model.predict_proba(X[test_index])[:, 1]\n else:\n prob_train = model.decision_function(X[train_index])\n prob_test = model.decision_function(X[test_index])\n score_train_folds.append(roc_auc_score(Y[train_index], prob_train))\n score_test_folds.append(roc_auc_score(Y[test_index], prob_test))\n try:\n coef_folds.append(model.coef_[0])\n except:\n coef_folds.append(0)\n\n return (\n score_train_folds, score_test_folds, coef_folds)\n\n\nmodel = linear_model.LogisticRegression(class_weight='balanced')\nfrom sklearn.decomposition import PCA\n\ndef Classifier(data, groups, step='1ms', win='1ms', sample='mean', model=model, permute_baseline=False, pca=False, feature=lambda x: x, fold=30, test_size=0.3):\n\n def calc(data_in_condition):\n data_in_condition = data_in_condition.groupby(level=['subject', 'channel', 'trial', 'cond_group']).mean()['data']\n if step != '1ms':\n data_in_condition = point_sample(data_in_condition, step)\n else:\n if win != '1ms':\n data_in_condition = window_sample(data_in_condition, win, sample)\n data_in_condition = data_in_condition.unstack('channel')\n return data_in_condition\n\n data_groups = group.extract(data, groups, 'MVPA')\n pval_groups_data = []\n score_groups_data = []\n info_groups_data = []\n for title, group_data in data_groups:\n pval_group_data = []\n score_group_data = []\n info_group_data = []\n for compr_name, compr_data in group_data:\n classN = len(compr_data.index.get_level_values('cond_group').unique())\n datasets = calc(compr_data)\n pvs = pd.Series(name=compr_name)\n score_detail = []\n info = {'score':dict(), 'std':dict(), 'variance':dict(), 'coef':dict()}\n for tp, tp_data in tqdm(datasets.stack('time').groupby(level=['time']), ncols=0):\n score_subjects = []\n variance_subjects = []\n std_subjects = []\n coef_subjects = []\n baselines = []\n for subject, samples in tp_data.groupby(level=['subject']):\n X = sklearn.preprocessing.scale(samples)\n if pca:\n pca = PCA(svd_solver='randomized', whiten=True).fit(X)\n X = pca.transform(X)\n Y = np.array(samples.index.labels[2])\n score_train_folds, score_test_folds, coef_folds = run_model(X, Y, model, fold, test_size)\n score_subjects.append(np.mean(score_test_folds))\n variance_subjects.append(np.mean(score_train_folds) - np.mean(score_test_folds))\n std_subjects.append(np.std(score_test_folds))\n coef_subjects.append(np.mean(coef_folds, axis=0))\n if permute_baseline:\n baseline = np.mean([run_model(X, np.random.permutation(Y), model, fold, test_size)[1] for i in range(3)])\n baselines.append(baseline)\n else:\n baselines.append(1 / classN)\n\n pv = two_sample(score_subjects, baselines, reps=1000, stat=(lambda u, v: np.mean(u - v)), alternative='greater')[0]\n pvs.set_value(tp, pv)\n score_detail.append(pd.Series(score_subjects, name=tp))\n tp_name = (tp / np.timedelta64(1, 'ms')).astype(int)\n info['score'][tp_name] = float('%.4f' % np.mean(score_subjects))\n info['variance'][tp_name] = float('%.4f' % np.mean(variance_subjects))\n info['std'][tp_name] = float('%.4f' % np.mean(std_subjects))\n info['coef'][tp_name] = np.around(np.mean(coef_subjects, axis=0), decimals=3)\n\n pval_group_data.append(pvs)\n score_group_data.append((compr_name, pd.DataFrame(score_detail).T))\n info_group_data.append((compr_name, pd.DataFrame(info)))\n\n pval_groups_data.append((title, pd.DataFrame(pval_group_data)))\n score_groups_data.append((title, score_group_data))\n info_groups_data.append((title, info_group_data))\n\n return {'p':pval_groups_data, 'score':score_groups_data, 'other':info_groups_data}","sub_path":"pycfiles/easyEEG-0.8.4.1-py3-none-any/classifier.cpython-36.py","file_name":"classifier.cpython-36.py","file_ext":"py","file_size_in_byte":5717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"257131635","text":"\ndef f(text):\n return True\nimport DB\nfrom markov.markov_model import make_markov_model\nimport Anekdotes\n\n\n\n\n\n#aneks = DB.get_all_aneks()\naneks = DB.get_all_aneks()\nprint(len(aneks))\nprint(\"Aneks getted\")\n\ndata = Anekdotes.make_data_for_model(aneks[:10040:2],2,f)\nDB.add_model(\"all_1\",data)\nprint(\"Model loaded\")\ndata = Anekdotes.make_data_for_model(aneks[10040:],2,f)\nDB.add_model(\"all_2\",data)\nprint(\"Model loaded\")\n\n","sub_path":"DataCreator/DataLoader.py","file_name":"DataLoader.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265168219","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\n\"\"\"\nFILE: sample_dynamic_classification_async.py\n\nDESCRIPTION:\n This sample demonstrates how to dynamically classify documents into one or multiple categories.\n No model training is required to use dynamic classification.\n\n The dynamic classification feature is part of a gated preview. Request access here:\n https://aka.ms/applyforgatedlanguagefeature\n\nUSAGE:\n python sample_dynamic_classification_async.py\n\n Set the environment variables with your own values before running the sample:\n 1) AZURE_LANGUAGE_ENDPOINT - the endpoint to your Language resource.\n 2) AZURE_LANGUAGE_KEY - your Language subscription key\n\"\"\"\n\nimport asyncio\n\n\nasync def sample_dynamic_classification_async() -> None:\n # [START dynamic_classification_async]\n import os\n from azure.core.credentials import AzureKeyCredential\n from azure.ai.textanalytics.aio import TextAnalyticsClient\n\n endpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\n key = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\n text_analytics_client = TextAnalyticsClient(\n endpoint=endpoint,\n credential=AzureKeyCredential(key),\n )\n documents = [\n \"The WHO is issuing a warning about Monkey Pox.\",\n \"Mo Salah plays in Liverpool FC in England.\",\n ]\n\n async with text_analytics_client:\n results = await text_analytics_client.dynamic_classification(\n documents,\n categories=[\"Health\", \"Politics\", \"Music\", \"Sports\"],\n classification_type=\"Multi\"\n )\n\n for doc, classification_result in zip(documents, results):\n if classification_result.kind == \"DynamicClassification\":\n classifications = classification_result.classifications\n print(f\"\\n'{doc}' classifications:\\n\")\n for classification in classifications:\n print(\"Category '{}' with confidence score {}.\".format(\n classification.category, classification.confidence_score\n ))\n elif classification_result.is_error is True:\n print(\"Document '{}' has an error with code '{}' and message '{}'\".format(\n doc, classification_result.error.code, classification_result.error.message\n ))\n # [END dynamic_classification_async]\n\n\nif __name__ == \"__main__\":\n asyncio.run(sample_dynamic_classification_async())\n","sub_path":"sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_dynamic_classification_async.py","file_name":"sample_dynamic_classification_async.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"511676743","text":"import numpy as np\nimport pytest\nfrom openff.toolkit.topology import Molecule\n\nfrom openff.system import unit\nfrom openff.system.stubs import ForceField\n\n\ndef test_getitem():\n \"\"\"Test behavior of System.__getitem__\"\"\"\n mol = Molecule.from_smiles(\"CCO\")\n parsley = ForceField(\"openff-1.0.0.offxml\")\n out = parsley.create_openff_system(mol.to_topology())\n\n out.box = [4, 4, 4]\n\n assert not out.positions\n np.testing.assert_equal(out[\"box\"].m, (4 * np.eye(3) * unit.nanometer).m)\n np.testing.assert_equal(out[\"box\"].m, out[\"box_vectors\"].m)\n\n assert out[\"Bonds\"] == out.handlers[\"Bonds\"]\n\n with pytest.raises(LookupError, match=\"Only str\"):\n out[1]\n\n with pytest.raises(LookupError, match=\"Could not find\"):\n out[\"CMAPs\"]\n","sub_path":"openff/system/tests/test_system.py","file_name":"test_system.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583390567","text":"# Utils for comparing different committing algorithms from the Time point of view\n# Main stats: time passed from event creation until message reception after which event was committed\n# We consider separately node event stats and all event stats\n\nimport csv\nimport os\n\nimport collections\n\nimport statistics\n\nfrom src.node import Node\nfrom src.node21 import Node21\nfrom src.node23 import Node23\nfrom src.node25 import Node25\nfrom src.node4 import Node4\nfrom src.node6 import Node6\nfrom src.node7 import Node7\nfrom src.node_hg2 import NodeHG2\nfrom src.node_hg3 import NodeHG3\nfrom src.node_hg4 import NodeHG4\n\nFIRST_ENTRIES = 3\nOUR_NODE_ID = 0\n\n\n# here we either take info from 'commit_message_timestamp' column or deduce it ourselves\ndef get_message_timestamp(node_id, event_rows, row_num, hic_header_index):\n message_timestamp = None\n commit_index_str = event_rows[row_num][hic_header_index]\n if commit_index_str.isdigit():\n commit_index = int(commit_index_str)\n if commit_index < len(event_rows):\n for row in event_rows[(commit_index - 1):]:\n if row[0] == node_id:\n message_timestamp = row[2]\n break\n return message_timestamp\n\n\ndef get_class_pairs(class_groups):\n result = []\n for group in class_groups:\n result.extend([(group[0].__name__, c.__name__) for c in group[1:]])\n return result\n\n\ndef get_header(p):\n return p[1]+'/'+p[0]\n\n\ndef save_time_stats(comparison_folder, class_groups=[]):\n class_pairs = get_class_pairs(class_groups)\n scenario_dirs = [os.path.basename(x[0]) for x in os.walk(comparison_folder)]\n cmt_header_index = -1\n hic_header_index = -1\n node_id = -1\n for scenario_folder in scenario_dirs:\n if not scenario_folder.startswith('scen_'):\n print('Warning: shitty dir found: \\'{}\\'. Aborting.'.format(scenario_folder))\n continue\n scenario_path = os.path.join(comparison_folder, scenario_folder)\n scenario_files = [f for f in os.listdir(scenario_path) if f.endswith('.csv')]\n processed_dict = {f.split('_')[0]: f for f in scenario_files}\n processed_classes = sorted(processed_dict.keys())\n algo_results = collections.defaultdict(list)\n headers = []\n for class_ in processed_classes:\n with open(os.path.join(scenario_path, processed_dict[class_]), 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n if len(headers) == 0:\n scenario_headers = next(reader)\n headers = scenario_headers[:FIRST_ENTRIES] # node_id, index, timestamp\n hic_header_index = scenario_headers.index('history_index_commit')\n if 'commit_message_timestamp' in scenario_headers:\n # we suppose that either all files have 'commit_message_timestamp' or none of them\n cmt_header_index = scenario_headers.index('commit_message_timestamp')\n else:\n next(reader)\n headers.append(class_)\n for row in reader:\n algo_results[class_].append(row)\n if node_id == -1:\n node_id = row[0] # First event node_id is the id of our running node\n stat_folder = os.path.join(comparison_folder, 'time_stats')\n if not os.path.exists(stat_folder):\n os.makedirs(stat_folder)\n stat_filename = 'time_stat_{}_{}.csv'.format(node_id, scenario_folder)\n with open(os.path.join(stat_folder, stat_filename), 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n headers.extend([get_header(p) for p in class_pairs]) # Pair comparison headers\n writer.writerow(headers)\n for i in range(len(algo_results[processed_classes[0]])):\n row = algo_results[processed_classes[0]][i][:FIRST_ENTRIES]\n time_diffs_to_append = []\n for class_ in processed_classes:\n if cmt_header_index >= 0:\n commit_timestamp_str = algo_results[class_][i][cmt_header_index]\n else: # We deduce received message timestamp ourselves\n commit_timestamp_str = get_message_timestamp(node_id, algo_results[class_], i, hic_header_index)\n\n if commit_timestamp_str is not None and len(commit_timestamp_str) > 0:\n time_diff = round(float(commit_timestamp_str) - float(row[2]), 5)\n else:\n time_diff = None\n\n time_diffs_to_append.append(time_diff)\n row.extend(time_diffs_to_append)\n # Adding class pair comparisons\n pair_comparison = []\n for pair in class_pairs:\n if pair[0] not in processed_classes or pair[1] not in processed_classes:\n pair_comparison.append(None)\n else:\n td0 = time_diffs_to_append[processed_classes.index(pair[0])]\n td1 = time_diffs_to_append[processed_classes.index(pair[1])]\n if td0 is None or td1 is None:\n pair_comparison.append(None)\n else:\n pair_comparison.append(round(100*td1/td0, 2))\n row.extend(pair_comparison)\n writer.writerow(row)\n print('Written {} row into file \\'{}\\'. Enjoy!'.format(len(algo_results[processed_classes[0]]),\n stat_filename))\n print('Done stat saving! Enjoy!')\n\n\ndef load_time_stats(comparison_folder):\n result = collections.defaultdict(list)\n stat_filepath = os.path.join(comparison_folder, 'time_stats')\n for filename in os.listdir(stat_filepath):\n if not filename.startswith('time_stat_'):\n continue\n with open(os.path.join(stat_filepath, filename), 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n headers = next(reader)\n result[filename].append(headers)\n for row in reader:\n result[filename].append(row)\n print('Loaded stats from {} files.'.format(len(result)))\n return result\n\n\n# time_stat_0_scen_50_13_300_2018-05-15_13:46:05.csv\ndef get_node_number(scenario):\n return scenario.split('_')[4]\n\n\ndef get_comparative_stats(comparison_folder, class_groups, our_node_events_only=False):\n aggregated_pair_stats = collections.defaultdict(lambda: collections.defaultdict(list))\n pair_headers = [get_header(p) for p in get_class_pairs(class_groups)]\n\n stats = load_time_stats(comparison_folder)\n\n for scenario, scenario_stats in stats.items():\n headers = scenario_stats[0]\n for pair_header in pair_headers:\n if pair_header not in headers:\n print('No info for pair \\'{}\\' in scenario \\'{}\\''.format(pair_header, scenario))\n continue\n pair_index = headers.index(pair_header)\n\n for stat_row in scenario_stats[1:]:\n if not our_node_events_only or int(stat_row[0]) == OUR_NODE_ID: # Filtering our node stats\n if len(stat_row[pair_index]) > 0:\n aggregated_pair_stats[scenario][pair_header].append(float(stat_row[pair_index]))\n\n total_stats = collections.defaultdict(dict)\n total_pair_stats = collections.defaultdict(list)\n ts_by_node_number = collections.defaultdict(lambda: collections.defaultdict(list))\n\n for scenario, scenario_pair_stats in aggregated_pair_stats.items():\n for pair, pair_stats in scenario_pair_stats.items():\n if len(pair_stats) > 0:\n v = round(statistics.mean(pair_stats), 2)\n total_stats[scenario][pair] = v\n total_pair_stats[pair].append(v)\n ts_by_node_number[get_node_number(scenario)][pair].append(v)\n\n final_filepath = os.path.join(comparison_folder, 'time_stats',\n 'time_final_stats_{}_{}_groups.csv'.format(our_node_events_only, len(class_groups)))\n with open(final_filepath, 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['scenario'] + pair_headers)\n\n total_row = ['Total AVG']\n for pair in pair_headers:\n if pair in total_pair_stats:\n total_row.append(str(round(statistics.mean(total_pair_stats[pair]), 2)))\n else:\n total_row.append('')\n\n writer.writerow(total_row)\n\n # Appending per node number stats\n for node_number, nn_stats in ts_by_node_number.items():\n row = [node_number + ' Total AVG']\n for pair in pair_headers:\n if pair in nn_stats:\n row.append(str(round(statistics.mean(nn_stats[pair]), 2)))\n else:\n row.append('')\n writer.writerow(row)\n\n for scenario, scenario_stats in total_stats.items():\n row = [scenario]\n for pair in pair_headers:\n if pair in scenario_stats:\n row.append(scenario_stats[pair])\n else:\n row.append('')\n writer.writerow(row)\n\n print('Written {} rows into file \\'{}\\'. Enjoy!'.format(len(total_stats) + 2, final_filepath))\n print('Done stat saving! Enjoy!')\n\n\nif __name__ == \"__main__\":\n comp_folder = '/media/trafim/red/home/openworld_data/comp_test'\n class_groups = [[Node, Node6, Node7, Node23, Node25, NodeHG4], [NodeHG3, NodeHG4, Node6, Node7, Node23, Node25],\n [Node7, NodeHG4], [NodeHG2, NodeHG3, NodeHG4, Node7]]\n\n save_time_stats(comp_folder, class_groups)\n get_comparative_stats(comp_folder, class_groups, our_node_events_only=True)\n get_comparative_stats(comp_folder, class_groups, our_node_events_only=False)","sub_path":"src/alg_time_comparator.py","file_name":"alg_time_comparator.py","file_ext":"py","file_size_in_byte":10184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"406979173","text":"\"\"\"\nThis module additive the surface class.\nIt additive working with polarization matrix.\n\"\"\"\nimport numpy as np\nfrom typing import List, Tuple, Callable, Dict\n\nimport tools.numpy_tool\n\n_LEFT: str = \"left\"\n_RIGHT: str = \"right\"\n\n\nclass PolarMat:\n \"\"\"\n class PolarMat - Polarisation matrix\n It responsibility is transform polarisation of light\n with helping of matrix multiplication on vector Jones or parameters of Stokes\n\n It can contains some inner variable for returned transform matrix(optional)\n \"\"\"\n\n def __init__(self, trans_mat: (List[float or int or complex], np.ndarray) = np.identity(2, dtype=float)):\n \"\"\"\n trans_mat - transform polarisation of light matrix\n For Jones vector - 2 x 2 matrix with complex values (Jones matrix)\n For Stokes parameters - 4 x 4 float (Muller matrix)\n Identity matrix Jones is default\n \"\"\"\n res1, res2 = PolarMat._check_and_return_val(trans_mat)\n self.trans_mat: np.ndarray = res1\n # Boolean maker. If True - it is a Jones matrix. If False is a Muller matrix\n self.is_jones: bool = res2\n self.depend_param: Dict[str, List[Tuple[str]]] = {_LEFT: list(), _RIGHT: list()}\n self.addit_mat_func: Dict[str, List[Callable]] = {_LEFT: list(), _RIGHT: list()}\n\n # =========================================== property and inner state =============================================\n\n @property\n def dependence_param(self):\n return self.depend_param\n\n @property\n def additional_mat_func(self):\n return self.addit_mat_func\n\n @property\n def transform_mat(self):\n return self.trans_mat\n\n @transform_mat.setter\n def transform_mat(self, val: (List[float or int or complex], np.ndarray)):\n res1, res2 = PolarMat._check_and_return_val(val)\n self.trans_mat = res1\n self.is_jones = res2\n\n def is_it_jones_matrix(self):\n return self.is_jones\n\n # =========================================== accessor methods =============================================\n\n def add_dependence_from_param(self, params: Tuple[str], side: str, func: Callable):\n \"\"\"\n Add function, returned needed matrix(for Jones any 2 x 2 matrix with complex number,\n for Muller any 4 x 4 matrix with real number). It doesn't check.\n When call \"get_polar_mat\". U need give named properties and they will redirect to given function.\n Param can be empty to change matrix, but better set \"transform_mat\" parameter.\n\n param - tuple of str, name of named parameters within given function.\n It must be uniq or to have the same mean to work correct.\n side - \"left\" of \"right\". It definite the side of multiplication of this matrix.\n func - function only with named parameters.\n\n Example(pseudocode):\n\n rot_mat_a_ccw = lambda a: [[cos(a),-sin(a)],\n [sin(a),cos(a)]]\n param = (\"a\",)\n # add method and call \"get_polar_mat\"\n # see continue of example at description of method \"get_polar_mat\"\n \"\"\"\n if side not in (_LEFT, _RIGHT):\n raise ValueError(f\"Side must be '{_LEFT}' or '{_RIGHT}' values. Given value:{side}\")\n self.depend_param[side].append(params)\n self.addit_mat_func[side].append(func)\n\n def remove_dependence_from_param(self, params: Tuple[str], side: str, func: Callable):\n \"\"\"\n Remove function, returned needed matrix(for Jones any 2 x 2 matrix with complex number,\n for Muller any 4 x 4 matrix with real number). It doesn't check.\n\n Reverse operation to add_dependence_from_param.\n\n param - tuple of str, name of named parameters within given function.\n It must be uniq or to have the same mean to work correct.\n side - \"left\" of \"right\". It definite the side of multiplication of this matrix.\n func - function only with named parameters.\n \"\"\"\n if side not in (_LEFT, _RIGHT):\n raise ValueError(f\"Side must be '{_LEFT}' or '{_RIGHT}' values. Given value:{side}\")\n self.depend_param[side].remove(params)\n self.addit_mat_func[side].remove(func)\n\n def get_polar_mat(self, **kwargs):\n \"\"\"\n Returning the polar transform matrix for Jones or Stokes vectors.\n If added dependence from param it will redirect to needed function.\n Their result will matrix multiply on inner matrix on left from first added to last.\n M_n * M_n-1 * ... * M_1 * M_inner\n\n Example(pseudocode):\n # see previous pseudocode at description of method \"add_dependence_from_param\"\n some_obj.get_polar_mat(a=some_value)\n \"\"\"\n\n def search_kwargs(params: Tuple[str], **kwargs_) -> list:\n \"\"\"\n return list only with properties where names matches with \"properties\" values\n \"\"\"\n args = []\n for param in params:\n elem = kwargs_.get(param, None)\n args.append(elem)\n return args\n\n result = self.trans_mat.copy()\n n = len(self.depend_param[_LEFT])\n for i in range(n).__reversed__():\n needed_args = search_kwargs(self.depend_param[_LEFT][i], **kwargs)\n new_mat = self.addit_mat_func[_LEFT][i](*needed_args)\n result = np.dot(new_mat, result)\n\n n = len(self.depend_param[_RIGHT])\n for i in range(n).__reversed__():\n needed_args = search_kwargs(self.depend_param[_RIGHT][i], **kwargs)\n new_mat = self.addit_mat_func[_RIGHT][i](*needed_args)\n result = np.dot(result, new_mat)\n return result\n\n def get_new_polar_state(self, polar_vec: (List[float or int or complex], np.ndarray), **kwargs):\n \"\"\"\n Multiple polar matrix on polar vector with given param for ADDED FUNCTION.\n\n polar_ver - Jones or Stokes vector\n kwargs - parameter for added function. See description for \"add_dependence_from_param\" method\n \"\"\"\n return np.dot(self.get_polar_mat(**kwargs), polar_vec)\n\n # =========================================== static methods =======================================================\n\n @staticmethod\n def _check_and_return_val(trans_mat) -> (np.ndarray, bool):\n \"\"\"\n Check the trans_mat (transform polarisation of light matrix)\n It must be 2 x 2 matrix with complex values (Jones matrix) or 4 x 4 float (Muller matrix)\n And return trans_mat and boolean value, what mean is jones matrix or not.\n \"\"\"\n is_jones = PolarMat.is_matrix_jones(trans_mat)\n if not is_jones and not PolarMat.is_matrix_muller(trans_mat):\n raise ValueError(f\"trans_mat must be a Jones or Muller matrix!\\n{trans_mat}\\n\" +\n \"Jones matrix is a 2 x 2 complex matrix.\" +\n \"Muller matrix is a 4 x 4 real matrix.\")\n return np.asarray(trans_mat), is_jones\n\n @staticmethod\n def is_matrix_jones(trans_mat: (List[float or int or complex], np.ndarray)):\n trans_mat = np.asarray(trans_mat)\n if trans_mat.shape != (2, 2):\n return False\n elif not tools.numpy_tool.is_numpy_complex_num_type(trans_mat):\n return False\n else:\n return True\n\n @staticmethod\n def is_matrix_muller(trans_mat: (List[float or int or complex], np.ndarray)):\n trans_mat = np.asarray(trans_mat)\n if trans_mat.shape != (4, 4):\n return False\n elif not tools.numpy_tool.is_numpy_real_num_type(trans_mat):\n return False\n else:\n return True\n\n @staticmethod\n def from_jones_to_muller_matrix(trans_mat: (List[float or int or complex], np.ndarray)):\n \"\"\"\n It doesn't have a realization\n Transform Jones matrix to Muller\n \"\"\"\n pass\n\n @staticmethod\n def from_muller_to_jones_matrix(trans_mat: (List[float or int or complex], np.ndarray)):\n \"\"\"\n It doesn't have a realization\n Transform Muller matrix to Jones\n \"\"\"\n pass\n","sub_path":"surfaces/additional/polar_mat.py","file_name":"polar_mat.py","file_ext":"py","file_size_in_byte":8123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"247075278","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport config\nimport telebot\nimport logging\nimport requests\n\n\ndef google_safe_browsing(url):\n\tr = requests.get(\"https://sb-ssl.google.com/safebrowsing/api/lookup?client=yoursafebot&key=%s&appver=0.1&pver=3.1&url=%s\" % (config.GOOGLE_API_KEY, url))\n\n\tlogging.debug(\"Google Safe Browsing, response status code: %s - %s\" % (url, r.status_code))\n\tif r.status_code == 204:\n\t\treturn 0\n\telif r.status_code == 200:\n\t\tif r.text in [\"phishing\", \"malware\", \"unwanted\", \"phishing,malware\", \"phishing,unwanted\", \"malware,unwanted\", \"phishing,malware,unwanted\"]:\n\t\t\tlogging.debug(\"Google Safe Browsing, response text: %s - %s\" % (url, r.text))\n\t\t\treturn \"Attention\\nGoogle Safe Browsing say that link %s is dangerous: %s\" % (url, r.text)\n\t\telse:\n\t\t\tlogging.error(\"Google Safe Browsing, unknown response text: %s - %s\" % (url, r.text))\n\t\t\treturn None\n\telse:\n\t\tlogging.error(\"Google Safe Browsing, unknown response code: %s - %s\" % (url, r.status_code))\n\t\treturn None\n\n\ndef check_url(url):\n\tresult = google_safe_browsing(url)\n\tif not result:\n\t\treturn \"The link %s seems safe\" % url\n\telse:\n\t\treturn result\n\t\n\ndef listener(messages):\n\tfor m in messages:\n\t\tif m.content_type == 'text':\n\t\t\tlogging.debug(m)\n\t\t\tresult = check_url(m.text)\n\t\t\tif result != None:\n\t\t\t\tbot.reply_to(m, result, parse_mode = \"HTML\", disable_web_page_preview = True)\n\n\nif __name__ == '__main__':\n\tlogging.getLogger(\"requests\").setLevel(logging.WARNING)\n\tlogger = logging.getLogger()\n\tlogger.setLevel(logging.DEBUG)\n\tformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\n\tfh = logging.FileHandler('logs/yoursafebot.log')\n\tfh.setLevel(logging.DEBUG)\n\tfh.setFormatter(formatter)\n\tlogger.addHandler(fh)\n\n\tch = logging.StreamHandler()\n\tch.setLevel(logging.DEBUG)\n\tch.setFormatter(formatter)\n\tlogger.addHandler(ch)\n\n\tbot = telebot.TeleBot(config.TELEGRAM_TOKEN)\n\tbot.set_update_listener(listener)\n\tbot.polling(none_stop=True)\n","sub_path":"yoursafebot.py","file_name":"yoursafebot.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"160287464","text":"import timeit\n\nfrom anonymizers import LazyAnonymizer\nfrom readers import JSONFileReader\nfrom writers import MemoryWriter\n\n\ndef run_using_including_rest():\n reader = JSONFileReader({\"filepath\": \"./nginx.json\"}, {\n \"log.file.path\": \"file_path\",\n \"source.ip\": \"ipv4\",\n \"geo\": \"geo_point\",\n \"related.ip\": \"ipv4\"\n }, [\"user.name\"])\n writer = MemoryWriter({\"keep\": False})\n anon = LazyAnonymizer(reader=reader, writer=writer)\n anon.anonymize(infer=True, include_rest=True)\n\ndef run_using_excluding_rest():\n reader = JSONFileReader({\"filepath\": \"./nginx.json\"}, {\n \"log.file.path\": \"file_path\",\n \"source.ip\": \"ipv4\",\n \"geo\": \"geo_point\",\n \"related.ip\": \"ipv4\"\n }, [\"user.name\"])\n writer = MemoryWriter({\"keep\": False})\n anon = LazyAnonymizer(reader=reader, writer=writer)\n anon.anonymize(infer=True, include_rest=False)\n \ndef run_using_include_rest_message():\n reader = JSONFileReader({\"filepath\": \"./app.json\"}, {\n \"log.file.path\": \"file_path\",\n \"source.ip\": \"ipv4\",\n \"geo\": \"geo_point\",\n \"related.ip\": \"ipv4\",\n \"message\": \"message\"\n }, [\"user.name\"])\n writer = MemoryWriter({\"keep\": False})\n anon = LazyAnonymizer(reader=reader, writer=writer)\n anon.anonymize(infer=True, include_rest=True)\n\nif __name__ == '__main__':\n import timeit\n print(\"run_using_including_rest: %s\" % timeit.timeit(\"run_using_including_rest()\", setup=\"from __main__ import run_using_including_rest\", number=100))\n print(\"run_using_excluding_rest: %s\" % timeit.timeit(\"run_using_excluding_rest()\",\n setup=\"from __main__ import run_using_excluding_rest\",\n number=100))\n print(\"run_using_include_rest_message: %s\" % timeit.timeit(\"run_using_include_rest_message()\",\n setup=\"from __main__ import run_using_include_rest_message\",\n number=100))","sub_path":"gen_tests/performance_testing.py","file_name":"performance_testing.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87712803","text":"# encoding: utf-8\nfrom apps.task.models import Procedure\nfrom apps.manage.models import Script, User\nfrom libs.permissions import isServersInProject\n\n\ndef procedureCheck(project_id, procedure_dict, check_unique=False):\n \"\"\"通用流程数据结构检查\n\n 数据结构检查 返回新的正确的数据结构\n\n Arguments:\n procedure_dict {dict} -- 前端发来的未检查的数据结构\n\n Returns:\n {tuple} -- 1.是否检查正确 2.提示信息 3.新生成的数据结构\n \"\"\"\n success = False\n msg = \"\"\n procedure_checked = {}\n\n # 检查逻辑\n try:\n name = procedure_dict[\"name\"]\n if name:\n procedure_checked[\"name\"] = unicode(name)\n else:\n raise Exception(\"流程名不能为空\")\n\n if check_unique:\n if Procedure.objects.filter(name=name, project_id=project_id).exists():\n raise Exception(\"流程名已存在\")\n\n script_names = {}\n scripts = Script.objects.filter(project_id=project_id).values(\"name\")\n for script in scripts:\n script_names[script[\"name\"]] = 1\n\n user_ids = {}\n users = User.objects.filter(project_id=project_id)\n for user in users:\n user_ids[user.id] = user\n\n servers = []\n steps = []\n for index, step in enumerate(procedure_dict[\"steps\"]):\n step_ = {}\n step_[\"name\"] = unicode(step[\"name\"])\n step_[\"index\"] = index\n step_[\"type\"] = int(step[\"type\"])\n if not step_[\"name\"]:\n raise Exception(\"步骤名不能为空\")\n\n nodes = []\n for index, node in enumerate(step[\"nodes\"]):\n node_ = {}\n script_name = unicode(node[\"name\"])\n if not script_name:\n raise Exception(\"脚本名称不能为空\")\n\n if check_unique:\n if script_names.get(script_name):\n raise Exception(\"脚本名已存在\")\n\n user = int(node[\"user\"])\n if not user_ids.get(user):\n raise Exception(\"用户不存在\")\n\n if not node[\"content\"]:\n raise Exception(\"脚本{name}不能为空\".format(name=script_name))\n\n node_[\"name\"] = script_name\n node_[\"content\"] = node[\"content\"]\n node_[\"user\"] = user_ids[user]\n node_[\"index\"] = index\n node_[\"type\"] = int(node[\"type\"])\n node_[\"args\"] = unicode(node.get(\"args\", \"\"))\n hosts = list(set(node[\"servers\"]))\n if not hosts:\n raise Exception(\"服务器列表不能为空\")\n node_[\"servers\"] = \"|\".join(hosts)\n servers.extend(hosts)\n nodes.append(node_)\n step_[\"nodes\"] = nodes\n steps.append(step_)\n\n procedure_checked[\"steps\"] = steps\n\n # 检查ip是否属于项目\n if not isServersInProject(project_id, servers):\n raise Exception(\"非法服务器权限\")\n\n except(KeyError, ValueError):\n msg = \"数据格式错误\"\n\n except Exception as e:\n msg = e.message\n\n else:\n success = True\n\n return success, msg, procedure_checked\n","sub_path":"2017/job_server/apps/task/common/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"107105042","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 16 17:24:36 2020\n\n@author: gabriel , hugo\n\"\"\"\n\nfrom ImprovedTokenizer import ImprovedTokenizer\n\n\nclass TextPreProcessing():\n def __init__(self, index_opt):\n self.tokenizer = ImprovedTokenizer()\n self.index_opt = index_opt\n \n def count_occurences(self, word, string_tokens):\n count = 0\n for token in string_tokens:\n if token == word:\n count += 1\n return count\n \n def positions(self, word, string_tokens):\n positions = []\n for i in range (0, len (string_tokens)):\n if string_tokens[i] == word:\n positions.append (i)\n return positions \n \n def count_string_occurences(self, pmid, string):\n list_number_occurences = []\n list_words = []\n for word in string:\n if word not in list_words:\n if pmid:\n if self.index_opt == 2:\n list_number_occurences.append((word, [pmid, self.count_occurences (word, string), self.positions (word, string)]))\n list_words.append (word)\n if self.index_opt == 1:\n list_number_occurences.append ((word, [pmid, self.count_occurences (word, string)]))\n list_words.append(word)\n return list_number_occurences\n\n def TextPreProcess(self, text, sequential_pmid = -1):\n \"\"\" This function is used to process the information before putting it into the indexer.\n This one corresponds to the Improved Tokenizer.\n The tokenizers creates tokens that are returned in the end of the function.\n \"\"\"\n data = self.tokenizer.convert_lowercase (text)\n data = self.tokenizer.remove_specials (data)\n data = self.tokenizer.remove_3_letters (data)\n data = self.tokenizer.remove_stopwords (data)\n data = self.tokenizer.stemming (data)\n data = self.count_string_occurences (sequential_pmid, data)\n\n return data \n \n def QueryPreProcess(self, query):\n data = query.replace('\\t', ' ')\n data = data.replace('\\n', ' ')\n data = self.TextPreProcess(data)\n return data\n ","sub_path":"Codigo/PreProcesser.py","file_name":"PreProcesser.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132845474","text":"import pytest\nimport numpy as np\nfrom scipy import optimize\n\n\nfrom adopty.ista import ista\nfrom adopty.lista import Lista\nfrom adopty.utils import cost, grad\nfrom adopty.tests.utils import gradient_checker\n\n\n@pytest.mark.parametrize('reg', [.1, .3, .5])\ndef test_ista(reg):\n\n n_trials = 1000\n n_atoms = 100\n n_dimensions = 64\n\n n_iters = 100\n\n random_state = 42\n\n rng = np.random.RandomState(random_state)\n\n # Generate a problem\n D = rng.randn(n_atoms, n_dimensions)\n z = rng.randn(n_trials, n_atoms)\n x = z.dot(D)\n\n z_hat, cost_ista, *_ = ista(D, x, reg, max_iter=n_iters)\n\n assert all(np.diff(cost_ista) <= 0)\n\n\n@pytest.mark.parametrize('reg', [.1, .3, .5, 2])\ndef test_lista(reg):\n\n n_trials = 1000\n n_atoms = 100\n n_dimensions = 64\n\n n_iters = 100\n\n n_layers = 10\n random_state = 42\n\n rng = np.random.RandomState(random_state)\n\n # Generate a problem\n D = rng.randn(n_atoms, n_dimensions)\n z = rng.randn(n_trials, n_atoms)\n x = z.dot(D)\n\n z_hat, cost_ista, _, lmbd = ista(D, x, reg, max_iter=n_layers)\n\n lista = Lista(D, n_layers)\n z_lista = lista(x, lmbd)\n\n z_lista = z_lista.data.numpy()\n assert np.isclose(cost_ista[n_layers], cost(z_lista, D, x, lmbd))\n\n\ndef test_grad():\n\n n_trials = 10\n n_atoms = 20\n n_dimensions = 64\n\n random_state = 1729\n\n rng = np.random.RandomState(random_state)\n\n # Generate a problem\n D = rng.randn(n_atoms, n_dimensions)\n z = rng.randn(n_trials, n_atoms)\n x = z.dot(D)\n\n z = z.ravel()\n\n gradient_checker(cost, grad, n_trials * n_atoms, args=(D, x),\n kwargs=dict(lmbd=0, flatten=True), n_checks=100,\n debug=True)\n","sub_path":"adopty/tests/test_ista.py","file_name":"test_ista.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"223731159","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask,request,Response\nimport hashlib,time,json,requests,datetime\nfrom lxml import etree\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n return 'Hello t World!'\n\n\ndef tuling(content):\n say_ai_data = {\"reqType\": 0, \"perception\": {\"inputText\": {\"text\": content}},\"userInfo\": {\"apiKey\": \"3b27ac8f81ee4853be53a4d22211533a\", \"userId\": \"rudy\"}}\n api_url2 = \"http://openapi.tuling123.com/openapi/api/v2\"\n req = requests.post(api_url2, json.dumps(say_ai_data)).json()\n content = req['results'][0]['values']['text']\n return content\n\ndef event_sub(content):\n return content\n\ndef text_message(content):\n return content\n\n@app.route('/weixin',methods=['GET','POST'])\ndef weixin():\n app.logger.info(\"0method:\"+request.method)\n app.logger.info(\"0url:\"+request.url)\n if request.method == 'GET':\n signature=request.args.get(\"signature\")\n timestamp = request.args.get(\"timestamp\")\n nonce = request.args.get(\"nonce\")\n echostr = request.args.get(\"echostr\")\n token = \"csxwxapp\"\n list = [str(token), str(timestamp),str(nonce)]\n list.sort()\n ts = ''.join(list)\n hashcode = hashlib.sha1(ts.encode('utf-8')).hexdigest()\n if hashcode == signature:\n return echostr\n else:\n return \"error\"\n else:\n str_xml = request.data\n xml = etree.fromstring(str_xml)\n msgType = xml.find(\"MsgType\").text\n fromUser = xml.find(\"FromUserName\").text\n touserName = xml.find(\"ToUserName\").text\n nowTime = str(time.time())\n now = datetime.datetime.now()\n now.strftime('%Y-%m-%d')\n start_data = datetime.datetime.strptime('2019-02-05', '%Y-%m-%d')\n run_days = (now - start_data).days\n\n content=\"\"\n\n if str(msgType)==\"text\":\n content = xml.find(\"Content\").text\n # text_message(content)\n elif str(msgType)==\"event\":\n msgType=\"text\"\n event = xml.find(\"Event\").text\n content = \"/help\"\n # event_sub()\n\n if not str(content).startswith(\"/\"):\n content=tuling(content)\n\n\n if str(content)==\"/help\":\n content=\"您好!欢迎您!本号旨在探讨个人数据分析场景,并尝试使用简单、\" \\\n \"友好的方式帮助个人实现数据分析的需求。已累计运行\"+\\\n str(run_days)+\"天,实现AI聊天接入功能,后续会有更多分析功能上线,敬请期待!多谢关注!试试发送'/help'指令,获取分析技能!\"\n\n res=\"\"+nowTime+\"\"\n\n return Response(str(res),mimetype='application/xml')\n\n\nif __name__ == '__main__':\n app.debug=True\n app.run(host='0.0.0.0',port=80)","sub_path":"one.py","file_name":"one.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"337816026","text":"import sys \r\nimport os\r\nimport androidhelper as ah\r\nimport time\r\nfrom datetime import datetime\r\nimport math\r\nimport pandas as pd\r\n\r\ndroid=ah.Android()\r\n\r\nn = 0\r\nm = 1000\r\nX = []\r\nY = []\r\nZ = []\r\nc_tita = []\r\nc_phi = []\r\n\r\n\r\nti = datetime.now()\r\ndroid.startSensingTimed(2, 250)\r\n\r\n\r\nfor i in range(n, m+1):\r\n\r\n acelerometro = droid.sensorsReadAccelerometer()\r\n \r\n if (type(acelerometro[1][1]) and type(acelerometro[1][2]) and type(acelerometro[1][0]) == float or type(acelerometro[1][1]) and type(acelerometro[1][2]) and type(acelerometro[1][0]) == int) and abs(acelerometro[1][1]) < (9.81):\r\n \r\n tita = math.acos( float(acelerometro[1][1])/(9.81))\r\n phi = math.atan( float(acelerometro[1][0])/ float(acelerometro[1][2]))\r\n\r\n \r\n else:\r\n\r\n tita = 0\r\n phi = 0\r\n\r\n\r\n print(\"\\n\\n\", \"\"\"\r\n\r\n Eje x: {}[m/s^2]\\n\r\n Eje y: {}[m/s^2]\\n\r\n Eje z: {}[m/s^2]\\n\r\n \\nReferencia G = 9,81[m/s^2]\"\r\n \\n\\nAngulo tita: {}\r\n \\nAngulo Phi: {}\r\n\r\n \"\"\".format((acelerometro[1][0]), (acelerometro[1][1]), (acelerometro[1][2]), tita, phi))\r\n sys.stdout.flush()\r\n \r\n \r\n\r\n os.system('clear')\r\n \r\n c_phi.append(phi)\r\n c_tita.append(tita)\r\n\r\n (X).append(acelerometro[1][0])\r\n (Y).append(acelerometro[1][1])\r\n (Z).append(acelerometro[1][2])\r\n\r\n\r\n #time.sleep(.01)\r\n\r\n\r\ntf = datetime.now()\r\n\r\ntiempo = ti - tf \r\nsegundos = tiempo.seconds\r\nsss = []\r\nsss.append(segundos)\r\n\r\ndroid.stopSensing()\r\n\r\ndatax = pd.DataFrame(X)\r\ndatay = pd.DataFrame(Y)\r\ndataz = pd.DataFrame(Z)\r\ndatatita = pd.DataFrame(c_tita)\r\ndataphi = pd.DataFrame(c_phi)\r\ndatasegundos = pd.DataFrame(sss)\r\n\r\ndf = pd.concat([datax, datay, dataz, datatita, dataphi, datasegundos], axis = 1)\r\n\r\ndf.to_csv(r'\\storage\\emulated\\0\\qpython\\data.csv', index = None, header=True)\r\nprint(\"Datos guardados en\\n\\storage\\emulated\\0\\qpython\")\r\nprint(\"Tiempo de ejecucion:\", segundos)\r\n\r\n\r\n\r\n\r\n\r\n# La inclinacion vertical con respecto al eje Z\r\n# angulo formado por el eje \"Y\" y el vector G\r\n\r\n# tita\r\n\r\n# Si existe el angulo phi\r\n# entonces hay una inclinacion \r\n\r\n# phi\r\n\r\n# En particular, la existencia de cualquier\r\n# angulo con respecto al vector g\r\n# me dtermina la inperfeccion en la cual el vector\r\n# g esta proyectado.\r\n\r\n\r\n\r\n","sub_path":"Visualizacion de datos de sensores del smartphone/acelerometro6.py","file_name":"acelerometro6.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"154056526","text":"\n\nclass A(object):\n # 实例方法\n def foo1(self):\n print(\"hello, \", self)\n\n # 静态方法\n @staticmethod\n def foo2():\n print(\"hello, \")\n\n # 类方法\n @classmethod\n def foo3(cls):\n print(\"hello, \", cls)\n\n\n# 实例方法\n# =====================================\na = A()\na.foo1()\n# 最常见的调用方式\n\nA.foo1(a)\n# 与第一种调用方式相同\n\n\n# 静态方法:支持类名和对象两种调用方式\n# =====================================\nA.foo2()\na.foo2()\n# 静态方法可以通过类名和对象调用\n\n\n# 类方法\n# =====================================\nA.foo3()\nprint(A)\n# 类方法,支持通过类名调用\n","sub_path":"Basement/code/section_9/threeMethodOfClass.py","file_name":"threeMethodOfClass.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"331757608","text":"from flask_restful import Resource\nfrom flask import request\n\nfrom copy import deepcopy\n\nfrom bson import ObjectId\n\nfrom dao.session import get_session\nfrom dao.user import get_user_by_id\nfrom dao.game_instance import get_game_instance\nfrom dao.game_instance import get_all_game_instances, make_move, completed_game_instance\nfrom dao.game_instance import create_game_instance, accepted_game_instance\n\nfrom views import game_instance as gameview\n\nfrom validators.session import authenticate_user\nfrom validators.game_instance import validate_create_game_instance\nfrom validators.game_instance import check_acceptance, validate_new_state\n\nfrom utils.game_instance import check_winning_state\n\n\nclass GameInstance(Resource):\n def get(self, game_id=None):\n params = request.args.to_dict()\n\n if not params:\n return {\"response\": \"Bad Request\"}, 400\n\n if not authenticate_user(params.get(\"token\")):\n return {\"response\": \"Unauthorized Access\"}, 401\n\n if game_id:\n game = get_game_instance(ObjectId(game_id))\n\n if not game:\n return {\"response\": \"Game not Found\"}, 404\n return {\"response\": gameview.single(game)}\n \n game_instances = get_all_game_instances()\n\n return {\"response:\": (gameview.multiple(game_instances))}\n\n\n def post(self):\n payload = request.json\n params = request.args.to_dict()\n\n if not payload or not params:\n return {\"response:\": \"Bad Request\"}, 400\n\n if not validate_create_game_instance(payload):\n return {\"response:\": \"Bad Request\"}, 400\n \n if not authenticate_user(params.get(\"token\")):\n return {\"response\": \"Unauthorized Access\"}, 401\n\n session = get_session(params.get(\"token\"))\n user1_id = session['user']\n user2_id = ObjectId(str(payload['user']))\n\n gi = create_game_instance(user1_id, user2_id)\n \n return {\"response\": str(gi)}\n\n\n def put(self):\n payload = request.json\n params = request.args.to_dict()\n\n if not payload or not params:\n return {\"response:\": \"Bad Request\"}, 400\n\n if not authenticate_user(params.get(\"token\")):\n return {\"response\": \"Unauthorized Access\"}, 401\n\n session = get_session(params.get(\"token\"))\n user_id = session['user']\n game_obj_id = ObjectId(payload['game_id'])\n\n if not check_acceptance(user_id, game_obj_id):\n return {\"response\": \"Unauthorized Access\"}, 401\n \n game_obj = get_game_instance(game_obj_id)\n accepted_game_instance(game_obj_id)\n\n return {\"response\": gameview.single(game_obj)}\n\n\n def patch(self):\n \"\"\"\n Make a move.\n Params : tokens\n payload: game_id, row, col\n \"\"\"\n payload = request.json\n params = request.args.to_dict()\n\n if not payload or not params:\n return {\"response:\": \"Bad Request\"}, 400\n\n if not authenticate_user(params.get(\"token\")):\n return {\"response\": \"Unauthorized Access\"}, 401\n\n print(payload)\n\n game_id = payload['game_id']\n game = get_game_instance(ObjectId(game_id))\n next_player = game['next_player']\n\n session = get_session(params.get(\"token\"))\n user = session['user']\n\n if next_player != user:\n return {\"response\": \"Forbidden\"}, 403\n\n row = int(payload['row'])\n col = int(payload['col'])\n\n if not (0 <= row <= 2 and 0 <= col <= 2):\n return {\"response:\": \"Bad Request\"}, 400\n\n if user == game['user1']:\n symbol = \"X\"\n next_player = game['user2']\n else:\n symbol = \"O\"\n next_player = game['user1']\n\n new_state = deepcopy(game[\"cstate\"])\n new_state[row][col] = symbol\n # print(\"neww\", new_state)\n\n if not validate_new_state(game[\"cstate\"], new_state, (row, col)):\n return {\"response:\": \"Bad Request\"}, 400\n\n new_status = game['status']\n\n if check_winning_state(new_state, row, col):\n print(\"Win state:\", row, \" \", col)\n winner = user\n completed_game_instance(ObjectId(game_id), winner)\n\n make_move(ObjectId(game_id), new_state, next_player)\n\n game = get_game_instance(ObjectId(game_id))\n # return {\"response\": new_state}\n\n return {\"response\": gameview.single(game)}, 200","sub_path":"gameservice/business_logic/serviceapis/gameinstance.py","file_name":"gameinstance.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"431411877","text":"# coding=utf-8\nfrom autobahn import wamp\nfrom autobahn.twisted.wamp import ApplicationSession\nfrom autobahn.wamp.exception import ApplicationError\nfrom twisted.internet.defer import inlineCallbacks\nfrom models.user import User\n\n\n# @note: Все-таки, терминология Controller в crossbar не используется\n# Скорее всего, вместо Controller нужно использовать Session\n# Еще раз взглянем на документацию\nclass UserController(ApplicationSession):\n \"\"\"\n NewController - component for work with news\n \"\"\"\n @wamp.register(u'server.authenticate')\n def authenticate(self, realm, authid, details):\n \"\"\"\n Method witch corresponds to authentication mechanism.\n \"\"\"\n\n try:\n user = User.get(authid=authid)\n except User.DoesNotExist:\n raise ApplicationError(u'server.user.does_not_exists', 'Wrong authid')\n\n return {\n 'secret': user.secret,\n 'role': user.role\n }\n\n @inlineCallbacks\n def onJoin(self, details):\n res = yield self.register(self)\n print(\"UserController: {} procedures registered!\".format(len(res)))","sub_path":"router/controllers/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"92647439","text":"# -*- coding: utf-8 -*-\n\"\"\"Compound object to simplify checking\n\"\"\"\nimport copy\nimport logging\nfrom rdkit import Chem\nfrom rdkit.Chem import rdMolDescriptors, rdDepictor, Descriptors, SaltRemover\nfrom rdkit.Chem.AllChem import ReplaceSubstructs\n# Silence RDKit Warning\nfrom rdkit import rdBase\nrdBase.DisableLog('rdApp.warning')\nfrom requests.exceptions import RequestException\n\nfrom .timeout import exit_after\nfrom .pubchem_smiles_standardizer import get_standardized_smiles\n\nclass Compound(object):\n\n def __init__(self, smiles, **kwargs):\n \"\"\"Initialize Compound object\n\n :smiles (str) - Input smiles string for compound object\n\n kwargs:\n :name (str) - Default = \"Unknown\" - Name of compound, also sets\n name in Molblock\n :standardize (bool) - Default = False - Control whether SMILES is\n subject to PubChem Standardization attempt\n \"\"\"\n\n # Standardize as a kwarg to allow disabling PubChem Standardization\n # explicitly\n standardize = kwargs.get(\"standardize\", False)\n if standardize:\n # Try to standardize the smiles, will time out after 5 seconds\n # and resort to supplied smiles string\n self._standardizeSmiles(smiles=smiles)\n else:\n self.smiles = smiles\n\n # Try to get the name if specified, but default to Unknown\n # This property\n self.name = kwargs.get(\"name\", \"Unknown\")\n\n # rdmol\n try:\n self.rdmol = Chem.MolFromSmiles(self.smiles)\n except TypeError as e:\n logging.error(\"RDKit was unable to load this compound\")\n logging.error(e)\n\n self.calcMolprops()\n\n\n def __repr__(self):\n \"\"\"repr for debugging\n \"\"\"\n return \"\" % (\n self.name, self.formula)\n\n def copy(self):\n return copy.deepcopy(self)\n\n def calcMolprops(self):\n \"\"\"Calculate masses for mol using RDKit\n\n Masses calculated and rounded to 4 decimal points\n [M+H]+ and other adducts can be calculated using RDKit\n and the calculate_exact_mass function by providing an\n appropriate SMILES string\n \"\"\"\n self.inchi = Chem.MolToInchi(self.rdmol)\n self.inchikey = Chem.MolToInchiKey(self.rdmol)\n self.accurate_mass = round(Descriptors.ExactMolWt(self.rdmol), 4)\n self.mass = round(Descriptors.MolWt(self.rdmol), 4)\n self.m_plus_h = round(self.accurate_mass + calculate_exact_mass('[H+]'), 4)\n self.m_plus_na = round(self.accurate_mass + calculate_exact_mass('[Na+]'), 4)\n # Set name in molblock\n self.rdmol.SetProp('_Name', self.name)\n rdDepictor.Compute2DCoords(self.rdmol)\n self.molblock = Chem.MolToMolBlock(self.rdmol)\n self.formula = rdMolDescriptors.CalcMolFormula(self.rdmol)\n\n def cleanStructure(self):\n \"\"\"Clean molecular structure using RDKit\n\n First: Strip salts\n Second: Second, check for fragments\n \"\"\"\n Chem.rdmolops.Cleanup(self.rdmol)\n neutralized = self._neutralizeMol()\n defragmented = self._getLargestFragment()\n if neutralized or defragmented:\n logging.warning('WARNING: Compound structure changed')\n self._standardizeSmiles()\n self.calcMolprops()\n\n def _neutralizeMol(self):\n \"\"\"Strip salts and neutralize molecule\"\"\"\n neutralized = False\n _remover = SaltRemover.SaltRemover()\n molnosalt, deleted = _remover.StripMolWithDeleted(self.rdmol)\n if deleted:\n logging.info('Found salt in molecule: %s\\t%s'\n % (self.name, self.inchikey))\n neutralized_mol, neutralized = _neutraliseCharges(\n Chem.MolToSmiles(molnosalt))\n else:\n neutralized_mol, neutralized = _neutraliseCharges(\n self.smiles)\n neutral_mol = Chem.MolFromSmiles(neutralized_mol)\n if neutralized:\n logging.debug('Molecule was neutralized')\n self.rdmol = neutral_mol\n self.smiles = neutralized_mol\n return neutralized\n\n def _getLargestFragment(self):\n \"\"\"Check if molecule is fragmented. If so, strip to largest fragment\"\"\"\n is_fragments = False\n fragments = Chem.GetMolFrags(self.rdmol, asMols=True)\n if len(fragments) > 1:\n is_fragments = True\n logging.info('Found multiple fragments in molecule: %s\\t%s'\n % (self.name, self.inchikey))\n for frag in fragments:\n longest = 0\n n_atoms = frag.GetNumAtoms()\n if n_atoms > longest and n_atoms > 0:\n longest = n_atoms\n self.rdmol = frag\n return is_fragments\n\n def _standardizeSmiles(self, smiles=None):\n \"\"\"Use PubChem webservices to standardize smiles\n If the service timesout, or fails for some other reason\n SMILES remains the same\n \"\"\"\n if not smiles:\n smiles = self.smiles\n try:\n self.smiles = standardize_smiles_wrapper(smiles)\n except (KeyboardInterrupt, TypeError, ValueError,\n RequestException) as e:\n logging.error(\"Unable to standardize %s\", smiles)\n logging.error(e)\n self.smiles = smiles\n\n\n# Helper functions\n# Below two functions are taken directly from\n# http://www.rdkit.org/docs/Cookbook.html\ndef _InitialiseNeutralisationReactions():\n patts = (\n # Imidazoles\n ('[n+;H]', 'n'),\n # Amines\n ('[N+;!H0]', 'N'),\n # Carboxylic acids and alcohols\n ('[$([O-]);!$([O-][#7])]', 'O'),\n # Thiols\n ('[S-;X1]', 'S'),\n # Sulfonamides\n ('[$([N-;X2]S(=O)=O)]', 'N'),\n # Enamines\n ('[$([N-;X2][C,N]=C)]', 'N'),\n # Tetrazoles\n ('[n-]', '[nH]'),\n # Sulfoxides\n ('[$([S-]=O)]', 'S'),\n # Amides\n ('[$([N-]C=O)]', 'N'),\n )\n return [(Chem.MolFromSmarts(x),\n Chem.MolFromSmiles(y, False)) for x, y in patts]\n\n\n_reactions = None\n\n\ndef _neutraliseCharges(smiles, reactions=None):\n global _reactions\n if reactions is None:\n if _reactions is None:\n _reactions = _InitialiseNeutralisationReactions()\n reactions = _reactions\n mol = Chem.MolFromSmiles(smiles)\n replaced = False\n for i, (reactant, product) in enumerate(reactions):\n while mol.HasSubstructMatch(reactant):\n replaced = True\n rms = ReplaceSubstructs(mol, reactant, product)\n mol = rms[0]\n if replaced:\n return (Chem.MolToSmiles(mol, True), True)\n else:\n return (smiles, False)\n\n\ndef calculate_exact_mass(smiles):\n m = Chem.MolFromSmiles(smiles)\n return Descriptors.ExactMolWt(m)\n\n@exit_after(5)\ndef standardize_smiles_wrapper(smiles):\n return get_standardized_smiles(smiles)\n\ndef inchikey_from_smiles(smiles):\n m = Chem.MolFromSmiles(smiles)\n return Chem.MolToInchiKey(m)\n","sub_path":"app/utils/Compound.py","file_name":"Compound.py","file_ext":"py","file_size_in_byte":7117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"525389358","text":"# coding: utf-8\n\nimport requests\nfrom tqdm.auto import tqdm\nimport os\n\n\"\"\"\nDownload file with progress bar. Implemented by requests & tqdm.\nref: https://stackoverflow.com/questions/15644964/python-progress-bar-and-downloads/15645088\n\n@param url: the file you'd like to get\n@param save_file: file's saving name. Optional.\n\nexample:\n url = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'\n download_file(url)\n\"\"\"\ndef download_file(url, save_file=None):\n if save_file is None:\n save_file = url.split('/')[-1]\n if os.path.exists(save_file) is True:\n return\n response = requests.get(url, stream=True)\n with tqdm.wrapattr(open(save_file, \"wb\"), \"write\", miniters=1,\n total=int(response.headers.get('content-length', 0)),\n desc=save_file) as fout:\n for chunk in response.iter_content(chunk_size=4096):\n fout.write(chunk)\n","sub_path":"useful_scripts/download_file.py","file_name":"download_file.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"80859826","text":"import torch\nimport torchvision.transforms as trn\nimport h5py\nimport numpy as np\n\nfrom torch.utils.data import Dataset\nfrom demo.predictor import COCODemo\nfrom maskrcnn_benchmark.config import cfg\n\n\nclass CaptionDataset(Dataset):\n def __init__(self, input_file, use_maskrcnn_benchmark=True, transform=None):\n h = h5py.File(input_file)\n self.imgs = h['images']\n self.captions = h['captions']\n self.captions_per_img = h.attrs['captions_per_image']\n self.coco_demo = COCODemo(cfg)\n assert self.captions.shape[0] // self.imgs.shape[0] == self.captions_per_img\n\n if transform is not None:\n # if customer transform rules are defined\n # we will use this\n self.transform = transform\n elif use_maskrcnn_benchmark:\n # if we use maskrcnn_benchmark as our encoder\n # we need to follow the corresponding image\n # pre-process procedure\n self.transform = self.coco_demo.build_transform()\n else:\n self.transform = trn.Compose([trn.Resize(255), trn.ToTensor()])\n\n assert self.imgs.shape[0] * 1 == self.captions.shape[0]\n\n def __getitem__(self, item):\n img = self.imgs[item // self.captions_per_img]\n img = self.transform(img)\n\n caption = self.captions[item]\n caption = torch.from_numpy(caption).long()\n\n data = {'image': img, 'caption': caption}\n return data\n\n def __len__(self):\n return self.captions.shape[0]\n","sub_path":"dataset/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"39526016","text":"from autocnet.examples import get_path\nfrom autocnet.graph.network import CandidateGraph\nfrom autocnet.io.network import load\n\nimport numpy as np\n\ndef test_save_project(tmpdir, candidategraph):\n path = tmpdir.join('prject.proj')\n candidategraph.save(path.strpath)\n candidategraph2 = load(path.strpath)\n\n for i,n in candidategraph.nodes.data('data'):\n print('Node {}: {}'.format(i,n == candidategraph2.node[i]['data']))\n\n for s,d,e in candidategraph.edges.data('data'):\n print(type(candidategraph2.edges[s,d]), candidategraph2.edges[s,d].keys())\n print('Edge {}: {}'.format((s,d), e == candidategraph2.edges[s,d]['data']))\n e1 = candidategraph2.edges[s,d]['data']\n print(e.keys())\n print(e1.keys())\n assert candidategraph == candidategraph2\n\ndef test_save_features(tmpdir, candidategraph):\n path = tmpdir.join('features')\n candidategraph.save_features(path.strpath)\n\n d = np.load(path.strpath + '_0.npz')\n np.testing.assert_array_equal(d['descriptors'],\n candidategraph.node[0]['data'].descriptors)\n","sub_path":"tests/test_save_load.py","file_name":"test_save_load.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"62633074","text":"import argparse\nfrom src.Client import Client\n\n\nclass Application(object):\n \"\"\"\n Main application class. It parses parameters and run client\n \"\"\"\n version = '1.0'\n\n def __init__(self):\n \"\"\"\n In constructor program arguments are parsed and client is prepared\n \"\"\"\n arguments = self.parseArgs()\n self.client = Client(\n configFile=arguments.config,\n limit=arguments.limit,\n register=arguments.register\n )\n\n def parseArgs(self):\n \"\"\"\n Parses all parameters given to the application during running it\n\n :return: returns data of all parsed parameters\n \"\"\"\n parser = argparse.ArgumentParser(prog='resmon-client')\n parser.add_argument(\n '-c',\n '--config',\n type=str,\n default='./data/config.json',\n help='Location where is stored JSON configuration file'\n )\n parser.add_argument(\n '-l',\n '--limit',\n type=int,\n default=10,\n help='Maximal limit of displayed hosts for every metric'\n )\n parser.add_argument(\n '--register',\n action='store_true',\n help='If it\\'s set, then user can be registered \\\n at start of the application. \\\n In other case user has to be logged before using this.'\n )\n parser.add_argument(\n '-v',\n '--version',\n action='version',\n version=('ResMon client '+Application.version)\n )\n return parser.parse_args()\n\n def run(self):\n \"\"\"\n Client is started\n\n :return: returns None\n \"\"\"\n self.client.run()\n","sub_path":"src/Application.py","file_name":"Application.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"8537766","text":"import itertools\nfrom collections import OrderedDict\nimport warnings\nfrom pyspark.sql.types import StructType\nimport json\nimport ast\n\n\nclass CustomWarning:\n def __init__(self, flag=False):\n self.to_screen = flag\n\n def warn(self, msg):\n if self.to_screen:\n print(msg)\n else:\n warnings.warn(msg, UserWarning)\n\n\ndef _dict_compare(d1, d2):\n \"\"\"Code Src: https://stackoverflow.com/a/18860653/5776539\"\"\"\n d1_keys = set(d1.keys())\n d2_keys = set(d2.keys())\n intersect_keys = d1_keys.intersection(d2_keys)\n added = d1_keys - d2_keys\n removed = d2_keys - d1_keys\n modified = {o: (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}\n same = set(o for o in intersect_keys if d1[o] == d2[o])\n return added, removed, modified, same\n\n\ndef compare_schemas(left_df, right_df):\n \"\"\"Return the difference, if any, of two Dataframe schemas.\n\n Column order is not enforced.\n\n Args:\n left_df: Dataframe for comparison\n right_df: Dataframe to compare against\n\n Returns:\n (set(string), set(string), set(string), set(string)): a tuple of columns unique to left, unique to right, same name but different type, and equivalent.\n \"\"\"\n\n right_schema = right_df.schema\n left_schema = left_df.schema\n\n right_dict = OrderedDict(\n {field.name.lower(): field for field in right_schema.fields}\n )\n left_dict = OrderedDict({field.name.lower(): field for field in left_schema.fields})\n\n return _dict_compare(left_dict, right_dict)\n\n\ndef validate_schema(df, schema, spark, warnings_to_stdout=False):\n \"\"\" Compare a Dataframe with a schema object.\n\n This is useful when comparing an inferred schema to a previous known defined schema. Column ordering is not enforced.\n\n TODO: enforce ordering\n\n Returns:\n bool: result is `True` if schema match (ordering ignored)\n \"\"\"\n\n df_l = df\n df_r = spark.createDataFrame(spark.sparkContext.emptyRDD(), schema=schema)\n\n warning = CustomWarning(warnings_to_stdout)\n\n added, removed, modified, _ = compare_schemas(df_l, df_r)\n result = True\n\n if len(added) > 0:\n warning.warn(\n \"Dataframe has additional fields over given schema.\\n{}\".format(\n \"\\n\".join(added)\n )\n )\n result = False\n if len(removed) > 0:\n warning.warn(\n \"Schema has additional fields over given Dataframe.\\n{}\".format(\n \"\\n\".join(removed)\n )\n )\n result = False\n if len(modified) > 0:\n warning.warn(\n \"Datatype mismatches in the following fields.\\n{}\".format(\n \"\\n\".join(modified)\n )\n )\n\n return result\n\n\ndef compare_schema_to_header(csv_path, schema, spark):\n \"\"\" Compare a CSV header with a schema object.\n \n Column ordering is enforced when comparing headers to the defined schema.\n \n Returns:\n list((string, string, bool)): list of column comparisons and the outcome\n \"\"\"\n df_l = spark.read.csv(csv_path, header=True, inferSchema=True).sample(fraction=.1)\n df_r = spark.createDataFrame(spark.sparkContext.emptyRDD(), schema=schema)\n\n added, removed, _, _ = compare_schemas(df_l, df_r)\n\n if len(added) > 0:\n raise RuntimeError(\"CSV has additional fields.\\n{}\".format(\"\\n\".join(added)))\n if len(removed) > 0:\n raise RuntimeError(\n \"Schema has defined additional fields.\\n{}\".format(\"\\n\".join(removed))\n )\n\n mismatches = list(\n filter(\n lambda tup: tup[2] is False,\n map(\n lambda left_right: (*left_right, True)\n if left_right[0].lower() == left_right[1].lower()\n else (*left_right, False),\n itertools.zip_longest(df_l.columns, df_r.columns),\n ),\n )\n )\n\n df_l.unpersist()\n df_r.unpersist()\n\n if len(mismatches) > 0:\n raise RuntimeError(\n \"The designed schema does not match the given CSV header.\\n{}\".format(\n \"\\n\".join(\n list(\n map(\n lambda tup: \"{0}\\t!=\\t{1}\".format(tup[0], tup[1]),\n mismatches,\n )\n )\n )\n )\n )\n\n\ndef import_pyspark_json(fp):\n \"\"\" Import a json representation of a\n :class:`pyspark.sql.types.StructType`\n\n Args:\n fp: Filepath of json.\n\n Returns:\n :class:`pyspark.sql.types.StructType`\n \"\"\"\n\n json_schema = None\n with open(fp, \"r\") as infile:\n json_str = infile.read()\n json_schema = json.loads(ast.literal_eval(json_str))\n\n schema = StructType().fromJson(json_schema)\n return schema\n","sub_path":"databricks_util/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"598934147","text":"\"\"\"\nMicro Service that asserts the requested idp_hint\n\"\"\"\nimport hashlib\nimport logging\n\nfrom satosa.internal_data import InternalResponse\nfrom satosa.micro_services.base import ResponseMicroService\n\nlogger = logging.getLogger('satosa')\n\ndef inacademia_hinting_hash(data):\n \"\"\"\n Hash data the same way this is done in the inacademia-hinting code.\n\n This code should not be changed on its own - if needed, it should be\n changed in-sync with the inacademia-hinting code.\n \"\"\"\n raw = data.encode(\"utf-8\") if isinstance(data, str) else data\n hash = hashlib.sha1(raw).hexdigest()\n return hash\n\nclass AssertHint(ResponseMicroService):\n \"\"\"\n idp_hint asserting micro_service\n \"\"\"\n\n def __init__(self, config, internal_attributes, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.internal_attribute = config.get('internal_attribute', 'idp_used')\n logger.info(f\"AssertHint micro_service is active {self.internal_attribute}\")\n\n def process(self, context, internal_response):\n idp_hint_key = context.state['InAcademia'].get('idp_hint_key', None)\n fresh_idp_hint_key = context.state['InAcademia'].get('fresh_idp_hint_key', None)\n logger.debug(f\"AssertHint requested idp_hint: {idp_hint_key}, fresh_idp_hint: {fresh_idp_hint_key}\")\n\n if fresh_idp_hint_key is not None:\n issuer = internal_response.auth_info.issuer\n logger.info(f\"AssertHint issuer: {issuer}\")\n\n issuer_hash = inacademia_hinting_hash(issuer)\n #logger.info(f\"AssertHint issuer hash: {issuer_hash}\")\n if issuer_hash == fresh_idp_hint_key:\n internal_response.attributes[self.internal_attribute] = [idp_hint_key]\n\n return super().process(context, internal_response)\n","sub_path":"src/svs/assert_hint.py","file_name":"assert_hint.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"221639324","text":"from django.shortcuts import render\nfrom django.views.decorators.http import require_http_methods\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom xpir.models import HL7Message\nfrom xpir.models import HL7MessageForwarding\nfrom xpir.models import HL7Patient\n\nfrom crosspir.elastic_db import Patient, PatientSearch\nimport logging\nimport simplejson as json\n\nSQL_DB_FIELDS = ['family_name', 'given_name', 'sex', 'birth_date', 'zip_code', 'city', 'street', 'street_number']\n\n# --------------------- Patient Assignment Start page -------------------------\n\n@require_http_methods([\"GET\"])\n@login_required\ndef patient_assign(request):\n print(\"You're at in patient_assign view, request is\", request)\n context = {}\n try:\n patient_ids = __get_all_pending_forwarding_patients__()\n except Exception as e:\n context['pending_patients_data'] = {}\n context['error'] = \"Problem mit der HL7-Datenbankverbindung\"\n return render(request, 'xpir/match_patient.html', context)\n\n context['pending_patients_data'] = __get_hl7patients_as_json__(patient_ids)\n return render(request, 'xpir/match_patient.html', context)\n\n\n# --------------------- Search request for USZ Patient ------------------------\n\n@require_http_methods([\"POST\"])\n@login_required\ndef patient_search(request):\n print(\"You're at in patient_search, request is\", request.POST)\n results = {'success':False}\n # decorator assures that this is a POST request\n POST = request.POST\n search_keys = Patient.create_from_dictionary(request.POST)\n search = PatientSearch()\n err = search.search(search_keys)\n if not err:\n json_data = search.get_results_as_json_array()\n results = {'success': True, 'result_data': json_data}\n else:\n logging.getLogger(__name__).error(\"Error running patient db query: %s\", str(err))\n results = {'success': False, 'result_data': \"[]\"}\n\n return JsonResponse(results)\n\n\n#----------- Request to perform match on USZ and RKB Patients ------------------\n\n@require_http_methods([\"POST\"])\n@login_required\ndef patient_match(request):\n print(\"You're at in patient_match, request is\", request.POST)\n result = __assign_matching__(request.POST[\"rkb_patient_id\"], request.POST[\"usz_patient_id\"])\n return JsonResponse(result)\n\n\n#-------------------------------------------------------------------------------\n#------------------------------ HELPER FUNCTIONS -------------------------------\n#-------------------------------------------------------------------------------\n\n# Get all HL7 patients (more exact: RKB Patient IDs) that cannot be forwarded\n# since they wait for manual USZ Patient ID matching\ndef __get_all_pending_forwarding_patients__() -> list:\n patient_ids = list()\n try:\n forwards = HL7MessageForwarding.objects.filter(state__exact=HL7MessageForwarding.STATE_MANUAL_PATID)\n for f in forwards:\n if f.patient.patient_id_rkb not in patient_ids:\n patient_ids.append(f.patient.patient_id_rkb)\n except Exception as e:\n logging.getLogger(__name__).error(\"Could not get forwarding patients: %s\", str(e))\n raise e;\n return patient_ids\n\n\n# Get patient details for the patient IDs provided and return the details as\n# JSON data for web display.\ndef __get_hl7patients_as_json__(patient_ids):\n # Collect all patients\n patients = []\n try:\n for i in patient_ids:\n p = HL7Patient.objects.get(patient_id_rkb=i)\n if p:\n patients.append(p)\n except Exception as e:\n logging.getLogger(__name__).error(\"Could not get forwarding patients: %s\", str(e))\n return \"{'success':False}\"\n\n # Convert patients to JSON\n jsondata = \"[\"\n for p in patients:\n jsondata += '[\"{}\", \"{}\", \"{}\", \"{}\", \"{}\", \"{}\", \"{}\", \"{}\", \"{}\"],'.format(p.patient_id_rkb, p.family_name, p.given_name, p.sex, p.birth_date, p.zip_code, p.city, p.street, p.street_number )\n if len(jsondata) > 0:\n jsondata = jsondata.rstrip(\",\")\n jsondata += \"]\"\n jsondata = jsondata.replace('\"\"', 'null')\n return jsondata\n\n\n# Assign matching in database\ndef __assign_matching__(rkb_patient_id: str, usz_patient_id: str) -> dict:\n rkb_patient = None\n forwards = None\n # Find related HL7 patient by RKB patient ID\n try:\n rkb_patient = HL7Patient.objects.get(patient_id_rkb=rkb_patient_id)\n except Exception as e:\n logging.getLogger(__name__).error(\"Could not find patient while assigning match information: %s\", str(e))\n return {'success':False}\n # Assign USZ patient ID to HL7 patient and save\n try:\n rkb_patient.patient_id_usz = usz_patient_id;\n rkb_patient.save();\n except Exception as e:\n logging.getLogger(__name__).error(\"Could not save patient while assigning match information: %s\", str(e))\n return {'success':False}\n # Find all pending forwardings related to this patient\n try:\n forwards = HL7MessageForwarding.objects.filter(state__exact=HL7MessageForwarding.STATE_MANUAL_PATID, patient__patient_id_rkb__exact=rkb_patient_id)\n print(\"Num Forwards:\", len(forwards))\n except Exception as e:\n logging.getLogger(__name__).error(\"Could not find any pending forwardings while assigning match information: %s\", str(e))\n return {'success':False}\n # Assign new status to forwarding denoting that patient ID matching is complete\n # and message can be forwarded now.\n try:\n for f in forwards:\n f.state = HL7MessageForwarding.STATE_SCHEDULED\n f.save()\n except Exception as e:\n logging.getLogger(__name__).error(\"Could schedule message while assigning match information: %s\", str(e))\n return {'success':False}\n # Finally report success\n return {'success':True}\n\n\n","sub_path":"CROSSPIR/xpir/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"199203095","text":"# -*- coding:utf-8 -*-\nimport pandas as pd\nimport os, sys\nimport matplotlib.pyplot as plt\n\ndef main():\n dfs = []\n filename = []\n path = sys.path[0]\n dirs = os.listdir(path)\n for i in dirs:\n if os.path.splitext(i)[1] == \".csv\": # 筛选csv文件\n dfs.append(pd.read_csv(i))\n filename.append(os.path.splitext(i)[0])\n print('{} loaded'.format(i))\n \n lines = []\n for df in dfs:\n line, = plt.plot(df['\"A\" credits needed'], df['Goal GPA'])\n lines.append(line)\n plt.legend(lines, filename, loc='lower right')\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"101900504","text":"\n\nfrom xai.brain.wordbase.nouns._nark import _NARK\n\n#calss header\nclass _NARKING(_NARK, ):\n\tdef __init__(self,): \n\t\t_NARK.__init__(self)\n\t\tself.name = \"NARKING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"nark\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_narking.py","file_name":"_narking.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"372563621","text":"from tkinter import *\nfrom PIL import ImageTk, Image\n\nclass DisplayBoard():\n\n def __init__(self):\n self.root = Tk()\n self.w = 800\n self.h = 660\n self.tileSize = 60\n self.canvas = Canvas(self.root, width=self.w, height=self.h, bg='white')\n self.canvas.pack()\n self.floor = self.resizeImage(\"floor.png\")\n self.wall = self.resizeImage(\"wall.png\")\n self.hero_down = self.resizeImage(\"hero-down.png\")\n self.hero_up = self.resizeImage(\"hero-up.png\")\n self.hero_left = self.resizeImage(\"hero-left.png\")\n self.hero_right = self.resizeImage(\"hero-right.png\")\n self.monster = self.resizeImage(\"skeleton.png\")\n self.boss = self.resizeImage(\"boss.png\")\n\n def drawLevel(self, level):\n self.canvas.create_text(200, 200, anchor = 'nw', text = \"Level \"+ str(level), tags = \"text\", font= 'Arial', fill='black')\n\n def drawMap(self, board):\n for i in range(len(board)):\n for j in range(len(board[i])):\n if board[i][j] == 'f':\n self.canvas.create_image(j*self.tileSize, i*self.tileSize, image=self.floor, anchor=NW)\n else:\n self.canvas.create_image(j*self.tileSize, i*self.tileSize, image=self.wall, anchor=NW)\n self.canvas.update()\n\n def drawTextHero(self, HP, DP, SP, level):\n self.canvas.create_text(10*self.tileSize+10, 60, anchor = 'nw', text = \"TKWanderer Game\\n\", tags = \"text\", font= 'Arial', fill='black')\n self.canvas.create_text(10*self.tileSize+10, 100, anchor = 'nw', text = \"Level: \"+ str(level), tags = \"text\", font= ('Arial', 30), fill='red')\n self.canvas.create_image(10*self.tileSize+10, 180, image=self.hero_down, anchor=NW)\n self.canvas.create_text(10*self.tileSize+10, 4*60, anchor = 'nw', text = \" HP: \" + str(HP) + \"\\n DP: \" + str(DP) + \"\\n SP: \" + str(SP) +\"\\n\", tags = \"text\", font= ('Arial', 20), fill='black')\n\n def drawTextEnemy(self, HP, DP, SP):\n self.canvas.create_image(10*self.tileSize+10, 360, image=self.monster, anchor=NW)\n self.canvas.create_text(10*self.tileSize+10, 7*60, anchor = 'nw', text = \" HP: \" + str(HP) + \"\\n DP: \" + str(DP) + \"\\n SP: \" + str(SP) +\" \\n\", tags = \"text\", font= ('Arial', 20), fill='black')\n\n def resizeImage(self, file_name):\n image = Image.open(file_name)\n resized_image = image.resize((self.tileSize, self.tileSize), Image.ANTIALIAS)\n return ImageTk.PhotoImage(resized_image)\n\n def drawCharacter(self, pos, charType):\n if charType == 'hero_down':\n self.canvas.create_image(pos[1]*self.tileSize, pos[0]*self.tileSize, image=self.hero_down, anchor=NW)\n elif charType == 'hero_up':\n self.canvas.create_image(pos[1]*self.tileSize, pos[0]*self.tileSize, image=self.hero_up, anchor=NW)\n elif charType == 'hero_left':\n self.canvas.create_image(pos[1]*self.tileSize, pos[0]*self.tileSize, image=self.hero_left, anchor=NW)\n elif charType == 'hero_right':\n self.canvas.create_image(pos[1]*self.tileSize, pos[0]*self.tileSize, image=self.hero_right, anchor=NW)\n elif charType == 'monster':\n self.canvas.create_image(pos[1]*self.tileSize, pos[0]*self.tileSize, image=self.monster, anchor=NW)\n elif charType == 'boss':\n self.canvas.create_image(pos[1]*self.tileSize, pos[0]*self.tileSize, image=self.boss, anchor=NW)\n\n def clearCharacter(self, pos):\n self.canvas.create_image(pos[1]*self.tileSize, pos[0]*self.tileSize, image=self.floor, anchor=NW)\n\n def clearText(self):\n self.canvas.create_rectangle(10*self.tileSize, 0, self.w, self.h, fill=\"white\", outline=\"white\")\n\n def clearTextEnemy(self):\n self.canvas.create_rectangle(10*self.tileSize, 4*60, self.w, self.h, fill=\"white\", outline=\"white\")\n\n def clearScreen(self):\n self.canvas.create_rectangle(0, 0, self.w, self.h, fill=\"white\", outline=\"white\")\n\n def drawTextGameOver(self):\n self.canvas.create_text(100, 100, anchor = 'nw', text = \"GAME\\nOVER\", tags = \"text\", font= ('Arial', 100), fill='red')\n","sub_path":"week-06/rpg_Game/rpgView.py","file_name":"rpgView.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"571005746","text":"import requests \nimport json\nimport datetime\n\nurl = \"http://localhost:5000\"\n\n#Die on any error\ndef fail(what):\n print(\"ERROR :\" + what)\n exit(1)\n\n#Generic checking of return format\ndef test_response(response,status,checktype,template):\n if response.status_code != status:\n fail(\"Incorrect status expected %d got %d\" % (status,response.status_code))\n \n if response.status_code != 200:\n return\n\n try:\n rval = response.json()\n except Exception as e :\n fail(\"Failed to parse JSON \" + str(e))\n \n if checktype != None:\n if isinstance(rval,checktype) == False:\n fail(\"Returned data type was %s not %s \" % (str(type(rval)),str(checktype)))\n\n #If we get a list check the first object otherwise check the object\n if template != None:\n if checktype == list:\n if len(rval) < 1: \n fail(\"Empty list returned\")\n obj = rval[0]\n else:\n obj = rval\n\n\n for (fname,ftype) in template.items():\n try:\n val = obj[fname]\n if isinstance(val,ftype) == False and val != None:\n fail(\"Returned data field %s was %s not %s \" % (fname,str(type(val)),str(ftype)))\n except Exception as e:\n fail(\"Failed to get key %s from object %s\" % (fname,obj))\n \n\n\ndef city_unit_tests():\n cityfields = { \"name\" : str, \"country\":str, \"location\": list}\n\n #Get All City Info\n #@app.route(\"/cities\", methods=[\"GET\"])\n\n print(\"Testing /cities\")\n r = requests.get(url + \"/cities\")\n test_response(r,200,list,cityfields)\n\n #@app.route(\"/cities/\", methods=[\"GET\"])\n\n print(\"Testing /cities/London\")\n r = requests.get(url + \"/cities/London\")\n test_response(r,200,dict,cityfields)\n\n print(\"Testing /cities/AnkhMorpork\")\n r = requests.get(url + \"/cities/AnkhMorpork\")\n test_response(r,404,dict,cityfields)\n\n\n\ndef plane_unit_tests():\n \n planefields = { \"callsign\" : str, \"heading\": float, \"currentLocation\": list, \"route\" : list, \"landed\": str}\n print(\"Testing GET /planes\")\n r = requests.get(url + \"/planes\")\n test_response(r,200,list,planefields)\n\n print(\"Testing GET /planes/CARGO0\")\n r = requests.get(url + \"/planes/CARGO0\")\n test_response(r,200,dict,planefields)\n\n print(\"Testing GET /planes/AIRWOLF\")\n r = requests.get(url + \"/planes/AIRWOLF\")\n test_response(r,404,dict,planefields)\n\n print(\"Testing PUT /planes/CARGO0/location/5.5,56.5/180\")\n r = requests.put(url + \"/planes/CARGO0/location/5.5,56.5/180\")\n test_response(r,200,None,planefields)\n r = requests.get(url + \"/planes/CARGO0\")\n test_response(r,200,dict,planefields)\n o = r.json()\n if o.get(\"currentLocation\") != [5.5,56.5]:\n fail(\"Incorrectly recorded position\")\n if o.get(\"heading\") != 180:\n fail(\"Incorrectly recorded heading\")\n\n\n print(\"Testing PUT /planes/CARGO0/location/5.5,56.5/180/Edinburgh\")\n r = requests.put(url + \"/planes/CARGO0/location/5.5,56.5/180/Edinburgh\")\n test_response(r,400,None,planefields)\n\n\n print(\"Testing PUT /planes/CARGO0/location/5.5,56.5/180/Madrid\")\n r = requests.put(url + \"/planes/CARGO0/location/5.5,56.5/180/Madrid\")\n test_response(r,200,None,planefields)\n r = requests.get(url + \"/planes/CARGO0\")\n test_response(r,200,dict,planefields)\n o = r.json()\n if o.get(\"currentLocation\") != [5.5,56.5]:\n fail(\"Incorrectly recorded position\")\n if o.get(\"heading\") != 180:\n fail(\"Incorrectly recorded heading\")\n if o.get(\"landed\") != \"Madrid\":\n fail(\"Incorrectly recorded landed\")\n\n\n print(\"Testing PUT /planes/CARGO1/route/Gondor\")\n r = requests.put(url + \"/planes/CARGO1/route/Gondor\")\n test_response(r,400,None,planefields)\n\n print(\"Testing PUT /planes/CARGO1/route/Paris\")\n r = requests.put(url + \"/planes/CARGO1/route/Paris\")\n test_response(r,200,None,planefields)\n r = requests.get(url + \"/planes/CARGO1\")\n test_response(r,200,dict,planefields)\n o = r.json()\n if o.get(\"route\") != [\"Paris\"]:\n fail(\"Incorrectly replaced route\")\n\n print(\"Testing POST /planes/CARGO1/route/Berlin\")\n r = requests.post(url + \"/planes/CARGO1/route/Berlin\")\n test_response(r,200,None,planefields)\n r = requests.get(url + \"/planes/CARGO1\")\n test_response(r,200,dict,planefields)\n o = r.json()\n if o.get(\"route\") != [\"Paris\",\"Berlin\"]:\n fail(\"Incorrectly added to route\")\n\n print(\"Testing POST /planes/CARGO1/route/Atlantis\")\n r = requests.post(url + \"/planes/CARGO1/route/Atlantis\")\n test_response(r,400,None,planefields)\n\n print(\"Testing DELETE /planes/CARGO1/route/destination\")\n r = requests.delete(url + \"/planes/CARGO1/route/destination\")\n test_response(r,200,None,planefields)\n\n r = requests.get(url + \"/planes/CARGO1\")\n test_response(r,200,dict,planefields)\n o = r.json()\n if o.get(\"route\") != [\"Berlin\"]:\n fail(\"Failed to delete destination\")\n\ndef cargo_unit_tests():\n cargofields = { \"id\": str,\"destination\": str,\n \"location\":str,\"courier\": str,\n \"received\": str, \"status\": str }\n\n #Check we have at least one\n print(\"Testing POST /cargo/Berlin/to/London\")\n r = requests.post(url + \"/cargo/Berlin/to/London\")\n test_response(r,200,None,None)\n try:\n o = r.json()\n except Exception as e:\n fail(\"Could not parse returned JSON\")\n id = o.get(\"id\")\n if id == None:\n fail(\"No id value returned for new cargo\")\n\n print(\"Testing GET /cargo/location/Berlin\")\n r = requests.get(url + \"/cargo/location/Berlin\")\n test_response(r,200,list,cargofields)\n try:\n o = r.json()\n except Exception as e:\n fail(\"Could not parse returned JSON\")\n \n found = None\n for c in o:\n if c.get(\"id\") == id and id != None:\n found = c\n\n if found == None:\n fail(\"Newly added Cargo not present\")\n\n print(\"Testing PUT /cargo/%s/courier/CARGO0\" % id)\n r = requests.put(\"%s/cargo/%s/courier/CARGO0\" % (url,id))\n test_response(r,200,None,cargofields)\n \n print(\"Testing GET /cargo/location/Berlin\")\n r = requests.get(url + \"/cargo/location/Berlin\")\n test_response(r,200,list,cargofields)\n try:\n o = r.json()\n except Exception as e:\n fail(\"Could not parse returned JSON\")\n \n found = None\n for c in o:\n if c.get(\"id\") == id and id != None:\n found = c\n\n if found == None:\n fail(\"Updated Cargo not present\")\n\n if found.get(\"courier\") != \"CARGO0\":\n fail(\"Failed to set Courier on cargo\")\n\n print(\"Testing DELETE /cargo/%s/courier\" % id)\n r = requests.delete(\"%s/cargo/%s/courier\" % (url,id))\n test_response(r,200,None,cargofields)\n \n print(\"Testing GET /cargo/location/Berlin\")\n r = requests.get(url + \"/cargo/location/Berlin\")\n test_response(r,200,list,cargofields)\n try:\n o = r.json()\n except Exception as e:\n fail(\"Could not parse returned JSON\")\n \n found = None\n for c in o:\n if c.get(\"id\") == id and id != None:\n found = c\n\n if found == None:\n fail(\"Updated Cargo not present\")\n\n if found.get(\"courier\") != None:\n fail(\"Failed to remove Courier from cargo\")\n\n #Teleporting must be allowed for this\n print(\"Testing PUT /cargo/%s/location/CARGO1\" % id)\n r = requests.put(\"%s/cargo/%s/location/CARGO1\" % (url,id))\n test_response(r,200,None,cargofields)\n\n print(\"Testing GET /cargo/location/CARGO1\")\n r = requests.get(url + \"/cargo/location/CARGO1\")\n test_response(r,200,list,cargofields)\n try:\n o = r.json()\n except Exception as e:\n fail(\"Could not parse returned JSON\")\n \n found = None\n for c in o:\n if c.get(\"id\") == id and id != None:\n found = c\n\n if found == None:\n fail(\"Updated Cargo not present\")\n\n if found.get(\"location\") != \"CARGO1\":\n fail(\"Failed to relocate cargo\")\n\n\n #sDelivered is shoudl hide from API\n print(\"Testing PUT /cargo/%s/delivered\" % id)\n r = requests.put(\"%s/cargo/%s/delivered\" % (url,id))\n test_response(r,200,None,cargofields)\n\n print(\"Testing GET /cargo/location/CARGO1\")\n r = requests.get(url + \"/cargo/location/CARGO1\")\n\n try:\n o = r.json()\n except Exception as e:\n fail(\"Could not parse returned JSON\")\n \n found = None\n for c in o:\n if c.get(\"id\") == id and id != None:\n found = c\n\n if found != None:\n fail(\"Delivered cargo still visible\")","sub_path":"unit_tests.py","file_name":"unit_tests.py","file_ext":"py","file_size_in_byte":8614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"541901163","text":"from deck import Deck\nfrom hand import Hand\n\n\nclass Game:\n def __init__(self):\n self.deck = Deck()\n self.player = Hand()\n self.dealer = Hand()\n\n def setup(self):\n print(\"Starting a new game of Blackjack!\")\n print(\"Creating Deck...\")\n print(\"Shuffling the Deck...\")\n self.deck.shuffle()\n return True\n\n def deal_starting_hands(self):\n print(\"Dealing Cards...\")\n self.player.add_card(self.deck.draw_card())\n self.player.add_card(self.deck.draw_card())\n self.dealer.add_card(self.deck.draw_card())\n self.dealer.add_card(self.deck.draw_card())\n\n def check_winner(self):\n print(\"Player has: \" + str(self.player))\n print(\"Player's hand is worth \" + str(self.player.value))\n\n if self.player.check_blackjack():\n print(\"Player has Blackjack!\")\n return True\n\n print(\"Dealer has: \" + str(self.dealer))\n print(\"Dealer's hand is worth \" + str(self.dealer.value))\n\n if self.dealer.check_blackjack():\n print(\"Dealer has Blackjack!\")\n return True\n\n return False\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"295060501","text":"#! /usr/bin/env python3\n\nimport os\nimport os.path\nimport sys\nimport uritemplate\nimport glob\n\nsys.path.append(\"adabot\")\nimport github_requests as github\n\nexit_status = 0\n\nfilepaths = list(glob.iglob('../bin/*/*', recursive=True))\nfilepaths.sort()\n\nfor full_filename in filepaths:\n filename = os.path.basename(full_filename)\n url_vars = {}\n url_vars[\"name\"] = filename\n url = uritemplate.expand(os.environ[\"UPLOAD_URL\"], url_vars)\n headers = {\"content-type\": \"application/octet-stream\"}\n print(url)\n with open(full_filename, \"rb\") as f:\n response = github.post(url, data=f, headers=headers)\n if not response.ok:\n if response.status_code == 422 and response.json().get(\"errors\", [{\"code\":\"\"}])[0][\"code\"] == \"already_exists\":\n print(\"File already uploaded. Skipping.\")\n continue\n print(\"Upload of {} failed with {}.\".format(filename, response.status_code))\n print(response.text)\n sys.exit(response.status_code)\n\nsys.exit(exit_status)\n","sub_path":"tools/upload_release_files.py","file_name":"upload_release_files.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"622470742","text":"import socket, time, json, threading, sys\nimport cv2\nimport pyaudio\nimport tkinter\nimport PIL.Image, PIL.ImageTk\n\n#------------------CONSTANTS---------------------\n\nAPP_STATE = True\nDEBUG = True\n\n# get streamers's IP address\nstreamer_name = socket.gethostname()\nstreamer_IP = socket.gethostbyname(streamer_name)\n\n# define all port numbers\nstreamer_tcp_port = 60000\nstreamer_audio_udp_port = 60001\nstreamer_video_udp_port = 60002\n\n# audio\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 8000\nCHUNK = 1024\n\nlistener_tcp_sockets = []\nlistener_IP_list = []\nsend_list = []\nthread_vid_client_ls = []\n\nbuf = 0\n\n#------------------------------------------------\n\ndef Get_streamer_ip():\n global streamer_IP\n global entry1, entry2\n global streamer_tcp_port\n global streamer_audio_udp_port\n global streamer_video_udp_port\n\n streamer_IP = entry1.get()\n streamer_tcp_port = int(entry2.get())\n streamer_audio_udp_port = streamer_tcp_port + 1\n streamer_video_udp_port = streamer_tcp_port + 2\n configure.quit()\n configure.destroy()\n\n# Tkinter window\nconfigure = tkinter.Tk()\nconfigure.title(\"Let's connect!\")\n\nlabel = tkinter.Label(\n configure,\n text=\"Enter the IPV4 address of the streamer\\n(127.0.0.1 for local testing)\",\n width=50,\n height=4\n)\nlabel.pack()\n\nentry1 = tkinter.Entry(configure)\nentry1.insert(0,streamer_IP)\nentry1.pack(pady=(0,10))\n\nportlabel = tkinter.Label(\n configure,\n text=\"Enter the custom port for streamer\",\n width=50,\n height=4\n)\nportlabel.pack()\n\nentry2 = tkinter.Entry(configure)\nentry2.insert(0,str(streamer_tcp_port))\nentry2.pack(pady=(0,10))\n\nbuttonst = tkinter.Button(\n master=configure,\n text=\"Start\",\n width=10,height=4,\n bg=\"green\",fg=\"white\",\n command=Get_streamer_ip)\nbuttonst.pack(pady=(10,10))\n\nconfigure.mainloop()\n\n# print streamer info\nprint(\"Streamer Name: \" + streamer_name)\nprint(\"Streamer IP: \" + streamer_IP)\n\n#----------------FUNCTIONS-----------------------\n\n# Audio callback function\ndef callback(in_data, frame_count, time_info, status):\n # sizeof(in_data) = 2081 bytes\n # sizeof(in_data) = 2048 bytes for RATE=8K\n global send_list,listener_IP_list, udp_audio_socket\n for i in send_list:\n udp_audio_socket.sendto(in_data, (i[0], i[1]+1))\n return (None, pyaudio.paContinue)\n\n# function to create the streamer \"send list\"\ndef create_streamer_send_list(listener_IP_list):\n global APP_STATE\n send_list = []\n i = 1\n while APP_STATE:\n index = 2**i-2\n if index < len(listener_IP_list):\n send_list.append(listener_IP_list[index])\n else:\n break\n i += 1\n return send_list\n\n# Function which creates video packets(buf) and\n# opens image window\ndef video_streamer():\n global buf, webcam, photo, send_list\n try:\n if webcam.isOpened():\n retval, frame = webcam.read()\n if not retval:\n print(\"webcam.read() failed\")\n return\n\n frame = cv2.resize(frame, (480, 360)) # sizeof(frame) = 518536\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n buf = cv2.imencode('.jpg', frame)[1] # sizeof(buf) = ~50000\n\n photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))\n canvas.create_image(0, 0, image = photo, anchor = tkinter.NW)\n\n for client_addr in send_list:\n udp_video_socket.sendto(buf, (client_addr[0],client_addr[1]+2))\n \n window.after(50, video_streamer)\n\n except KeyboardInterrupt:\n print(\"Streaming terminated\")\n \n except:\n print(\"Error encountered while streaming video\")\n\n\ndef thread_client_commander():\n global listener_tcp_sockets\n global listener_IP_list\n global send_list, APP_STATE, DEBUG\n dl = {}\n while APP_STATE:\n for i in range(len(listener_tcp_sockets)-1,-1,-1):\n try:\n if DEBUG==True:\n dl[listener_IP_list[i]] = i\n mssg = '{}'.format(json.dumps(listener_IP_list))\n listener_tcp_sockets[i].send(mssg.encode())\n else:\n mssg = '{}'.format(json.dumps(listener_IP_list))\n start_time = (time.time())*1000\n listener_tcp_sockets[i].send(mssg.encode())\n end_time = (time.time())*1000\n try:\n # Inorder to eliminate race condition\n if abs(dl[listener_IP_list[i]]-(end_time - start_time))>2:\n dl[listener_IP_list[i]] = end_time - start_time\n elif end_time-start_time==0:\n dl[listener_IP_list] = i\n except:\n dl[listener_IP_list[i]] = end_time - start_time\n except:\n del listener_IP_list[i]\n del listener_tcp_sockets[i]\n send_list = create_streamer_send_list(listener_IP_list)\n if len(listener_IP_list)==len(dl):\n listener_IP_list = list(dict(sorted(dl.items(), key=lambda item: item[1])).keys())\n UI_update()\n time.sleep(5)\n\ndef client_threader(tcp_socket):\n global listener_tcp_sockets\n global listener_IP_list\n global send_list, APP_STATE\n\n tcp_socket.listen(10)\n tcp_socket.settimeout(100)\n while APP_STATE:\n try:\n # Extra try except for tcp_socket timeout\n try:\n sock, addr = tcp_socket.accept()\n print(\"New listener:\",addr)\n # store listener IP address and port\n listener_IP_list.append(addr)\n # store tcp client socket\n listener_tcp_sockets.append(sock)\n send_list = create_streamer_send_list(listener_IP_list)\n UI_update()\n except:\n pass\n\n except:\n print(\"Streaming terminated\")\n APP_STATE = False\n break\n\ndef UI_update():\n global num_list_str,send_list_str\n global listener_IP_list, send_list\n\n num_list_str.set(\"Number of listeners: \" + str(len(listener_IP_list)) \n + \"\\nListener IP addresses\\n\" + str(listener_IP_list).lstrip('[').rstrip(']').replace(',','\\n'))\n send_list_str.set(\"send list\\n \" + str(send_list).lstrip('[').rstrip(']').replace(',','\\n'))\n\ndef Stop_Services(event):\n try:\n window.destroy()\n except:\n print(\"Window already closed.\")\n\n APP_STATE = False\n webcam.release()\n audio_stream.stop_stream()\n audio_stream.close()\n audio.terminate()\n udp_video_socket.close()\n tcp_socket.close()\n\n print(\"Streaming services stopped\")\n sys.exit()\n\n#------------------------------------------------\n\n#--------------SOCKETS AND THREADING-------------\n\n# create TCP socket and bind it to streamer's IP and tcp port\ntcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ntcp_socket.bind((streamer_IP, streamer_tcp_port))\n\n# UDP video socket\nudp_video_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nudp_video_socket.bind((streamer_IP, streamer_video_udp_port))\n\n# UDP Audio socket\nudp_audio_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nudp_audio_socket.bind((streamer_IP, streamer_audio_udp_port))\n\nwebcam = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n\n# Audio\naudio = pyaudio.PyAudio()\naudio_stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK, stream_callback=callback)\n\n# Tkinter window\nwindow = tkinter.Tk()\nwindow.title(\"Streamer\")\n\n# Frame 1\nframe1 = tkinter.Frame(master=window)\ncanvas = tkinter.Canvas(window, width = 480, height = 360)\ncanvas.pack(side=tkinter.LEFT)\n\n# Frame 2\nframe2 = tkinter.Frame(master=frame1,width=200,height= 360)\n\n# Listener IP list on tk\nnum_list_str = tkinter.StringVar()\nlabel1 = tkinter.Label(frame2, textvariable = num_list_str)\nnum_list_str.set(\"Number of listeners: \" + str(len(listener_IP_list)) \n + \"\\nListener list: \" + str(listener_IP_list))\nlabel1.pack(side=tkinter.TOP,fill=tkinter.BOTH)\n\n# send list on tk\nsend_list_str = tkinter.StringVar()\nlabel2 = tkinter.Label(frame2, textvariable = send_list_str)\nsend_list_str.set(\"send list: \" + str(send_list))\nlabel2.pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True)\n\nframe2.pack(side=tkinter.LEFT,fill=tkinter.BOTH,expand=True)\nframe1.pack()\n\n# frame 3\nframe3 = tkinter.Frame(window)\n\nbutton = tkinter.Button(master=frame3,text=\"Stop\",width=10,height=4,bg=\"red\",fg=\"white\")\nbutton.bind(\"\",Stop_Services)\nbutton.pack(side=tkinter.BOTTOM)\n\nframe3.pack()\n\n# Video thread\nvideo_streamer()\n\n# Controller TCP socket\nthread_commnd_client = threading.Thread(target=thread_client_commander,daemon=True)\nthread_commnd_client.start()\n\nclient_thread = threading.Thread(target=client_threader,args=(tcp_socket,),daemon=True)\nclient_thread.start()\n\nwindow.mainloop()\n\nStop_Services('dummy')","sub_path":"streamerIPV4.py","file_name":"streamerIPV4.py","file_ext":"py","file_size_in_byte":8982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"319060381","text":"#-*- encoding: utf-8 -*-\r\n\r\nimport mysql\r\n\r\n\r\ndef readcsv(fileName):\r\n\tfile_object = open(fileName)\r\n\tlist_of_all_the_lines = file_object.readlines( )\r\n\tfile_object.close()\r\n\treturn list_of_all_the_lines\r\n\r\n\r\nlines = readcsv('0720bmspay2.csv')\r\n\r\n_sql = 'INSERT INTO bmspayinfo(ACCOUNTCODE, USERID, ACCOUNT, EMAIL) values(%s, %s, %s, %s)'\r\n\r\nfor line in lines:\r\n\tls = line.split(',')\t\r\n\tll = []\r\n\tfor l in ls:\r\n\t\tl = l.replace('\\r\\n', '')\r\n\t\tl = l[1:-1]\r\n\t\tll.append(l)\r\n\tmysql.insert_or_update_or_delete(sql)\r\n\r\n","sub_path":"app/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"425876977","text":"#=============================\n# JointFontGAN\n# Modified from https://github.com/azadis/MC-GAN\n# By Yankun Xi\n#=============================\n\nimport os\nimport sys\nimport shutil\nimport time\nimport configparser\nif __package__ is None:\n this_path = os.path.dirname(os.path.realpath(__file__))\n project_root = this_path.rpartition(\"JointFontGAN\")[0]\n sys.path.insert(0, project_root)\n from JointFontGAN.options.XItrain_options import TrainOptions\n # set CUDA_VISIBLE_DEVICES before import torch\n opt = TrainOptions().parse()\n from JointFontGAN.models.XImodels import create_model\n from JointFontGAN.util.XIvisualizer import Visualizer\n from JointFontGAN.data.XIdata_loader import CreateDataLoader\nelse:\n from ...options.XItrain_options import TrainOptions\n # set CUDA_VISIBLE_DEVICES before import torch\n opt = TrainOptions().parse()\n from ...models.XImodels import create_model\n from ...util.XIvisualizer import Visualizer\n from ...data.XIdata_loader import CreateDataLoader\n\n# read configuration from files\nconfigParser = configparser.RawConfigParser()\nconfigFilePath = r''\n\ndata_loader = CreateDataLoader(opt)\n\ndataset = data_loader.load_data()\ndataset_size = len(data_loader)\n\nmodel = create_model(opt)\nvisualizer = Visualizer(opt)\n\n# get the first epoch if resuming\nfirst_epoch = opt.which_epoch + 1\n\ndataset_training_size = dataset_size - dataset_size % opt.batchSize\nprint('#training images = %d / %d' % (dataset_training_size,\n dataset_size))\nprint('LOADING from %s' % opt.which_epoch)\ntotal_steps = (first_epoch - 1) * dataset_training_size\nlast_display_step = total_steps\nlast_print_step = total_steps\nlast_save_step = total_steps\n\nn_rgb = 3 if opt.rgb else 1\nblanknum = int(opt.blanks * opt.input_nc / n_rgb)\nremainnum = int(opt.input_nc / n_rgb) - blanknum\n\nl1_score = 0\nssim_score = 0\nmse_score = 0\nfor epoch in range(first_epoch, opt.niter + opt.niter_decay + 1):\n epoch_start_time = time.time()\n model.next_epoch()\n for i, data in enumerate(dataset):\n iter_start_time = time.time()\n total_steps += opt.batchSize\n epoch_iter = total_steps - (dataset_size - dataset_size %\n opt.batchSize) * (epoch - 1)\n model.set_input(data)\n model.optimize_parameters()\n\n if total_steps > (last_display_step + opt.display_freq - 1):\n visualizer.display_current_results(\n model.get_current_visuals(), model.epoch_str)\n last_display_step = total_steps\n\n if total_steps > (last_print_step + opt.print_freq - 1):\n errors = model.get_current_errors()\n t = (time.time() - iter_start_time) / opt.batchSize\n visualizer.print_current_errors(epoch, epoch_iter, errors,\n t)\n if opt.display_id > 0:\n visualizer.plot_current_errors(epoch, float(\n epoch_iter) / dataset_training_size, opt, errors)\n last_print_step = total_steps\n\n # if total_steps > (last_save_step + opt.save_latest_freq - 1):\n # print(\n # 'saving the latest model (epoch %d, total_steps %d)' %\n # (epoch, total_steps))\n # model.save('latest')\n # last_save_step = total_steps\n\n if opt.batchSize==1:\n visuals = model.get_current_visuals()\n img_path = model.get_image_paths()\n print('process image... %s' % img_path, end =\" \")\n scores = visualizer.eval_current_result(visuals)\n print(\"L1: %s\" % (scores[0]), end =\" \")\n print(\"ssim: %s\" % (scores[1]), end =\" \")\n print(\"MSE: %s\" % (scores[2]))\n l1_score += scores[0]\n ssim_score += scores[1]\n mse_score += scores[2]\n\n if opt.batchSize==1:\n print(\"Final scores for %d images:\" % (i + 1),\n \"L1: %s\" % (l1_score / (i + 1)),\n \"ssim: %s\" % (ssim_score / (i + 1)),\n \"MSE: %s\" % (mse_score / (i + 1)))\n\n print('saving the latest model (epoch %s, total_steps %d)' % (\n model.epoch_str, total_steps))\n model.save(latest=True)\n\n if epoch % opt.save_epoch_freq == 0:\n print('saving the model at the end of epoch %s, iters %d' %\n (model.epoch_str, total_steps))\n model.save()\n\n print('End of epoch %d / %d \\t Time Taken: %d sec' %\n (epoch, opt.niter + opt.niter_decay, time.time() - epoch_start_time))\n\n","sub_path":"exe/EskGAN/XItrain_EskGAN.py","file_name":"XItrain_EskGAN.py","file_ext":"py","file_size_in_byte":4521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"168766599","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 21 14:11:44 2018\n\n@author: xsxsz\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist=input_data.read_data_sets(\"../../mnist\",one_hot=True)\n\n#------------------\ntrain_rate=0.001\ntrain_step=1000\nbatch_size=128\ndisplay_step=10\nframe_size=28\nlength=28\nhidden_size=5\nn_classes=10\n#------------------\n\nx=tf.placeholder(dtype=tf.float32,shape=[None,length*frame_size],name='input_X')\ny=tf.placeholder(dtype=tf.float32,shape=[None,n_classes],name='label_Y')\nweights=tf.Variable(tf.truncated_normal(shape=[hidden_size,n_classes]))\nbias=tf.Variable(tf.zeros(shape=[n_classes]))\n\ndef RNN(x,weights,bias):\n x=tf.reshape(x,shape=[-1,length,frame_size])\n rnn_cell=tf.nn.rnn_cell.BasicRNNCell(hidden_size)\n output,states=tf.nn.dynamic_rnn(rnn_cell,x,dtype=tf.float32)\n return tf.nn.softmax(tf.matmul(output[:,-1,:],weights)+bias)\n\npred_y= RNN(x,weights,bias)\ncost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred_y,labels=y))\ntrain=tf.train.AdamOptimizer(train_rate).minimize(cost)\n\ncorrect_pred=tf.equal(tf.argmax(pred_y,1),tf.argmax(y,1))\nacc=tf.reduce_mean(tf.cast(correct_pred,dtype=tf.float32))\n\ninit=tf.global_variables_initializer()\nwith tf.Session() as sess:\n sess.run(init)\n test_x,test_y=mnist.test.next_batch(batch_size)\n step=1\n while step%s' % (d['id'], d['label']))\n d['items_string'] = items.get(d['id'], '')\n return data\n\n\n@dispatch(dict)\ndef unfulfilled(qstring):\n sales_qs = Sale.objects \\\n .prefetch_related('unit_sale__sku__skuunit__inventory_item') \\\n .prefetch_related('fulfillments__fulfill_lines__inventory_item')\n\n incomplete = [s.id for s in sales_qs if s.unfulfilled_items]\n \n qs = Sale.objects.filter(id__in=incomplete)\n qs = SaleFulfillmentSerializer.setup_eager_loading(qs)\n return SaleFulfillmentSerializer(qs, many=True).data\n\n\n@dispatch(str, dict)\ndef unfulfilled(id, qstring):\n qs = Sale.objects.get(id=id)\n return SaleFulfillmentSerializer(qs).data\n\n@dispatch(dict)\ndef sale(qstring):\n start = time.time()\n start_date = qstring.get('from_date', settings.DATE_EARLY)\n end_date = qstring.get('to_date', datetime.datetime.now().date())\n view_type = qstring.get('view', 'full')\n paid_thru = qstring.get('paid_thru')\n\n if type(start_date) != datetime.date:\n start_date = parse(start_date).date()\n if type(end_date) != datetime.date:\n end_date = parse(end_date).date()\n qs = Sale.objects.filter(sale_date__gte=start_date, sale_date__lte=end_date) \\\n .order_by('-sale_date')\n\n if paid_thru:\n qs = qs.filter(paid_thru_id=paid_thru)\n \n if view_type == 'simple':\n serializer = SimpleSaleSerializer\n elif view_type == 'simple2':\n serializer = SimpleSaleSerializer2\n elif view_type == 'shipping':\n serializer = ShippingSaleSerializer\n elif view_type == 'fulfillment':\n serializer = SaleFulfillmentSerializer\n elif view_type == 'proceeds':\n serializer = SaleProceedsSerializer\n elif view_type == 'grossproceeds':\n qs = qs.annotate(gross_proceeds=Coalesce(Sum(F('unit_sale__quantity') * F('unit_sale__unit_price'), output_field=DecimalField()),\n Decimal('0')))\n serializer = SaleGrossProceedsSerializer\n elif view_type == 'proceedsadjustments':\n qs = qs.annotate(total_adjustments=Coalesce(Sum('proceedsadjustment_sale__amount', output_field=DecimalField()),\n Decimal('0')))\n serializer = SaleProceedsAdjustmentSerializer\n elif view_type == 'payouts':\n qs = qs.annotate(total_payout=Coalesce(Sum('payoutline_sale__amount', output_field=DecimalField()),\n Decimal('0')))\n serializer = SalePayoutsSerializer\n elif view_type == 'salestax':\n qs = qs.annotate(total_salestax=Coalesce(Sum('sales_tax__tax', output_field=DecimalField()),\n Decimal('0')))\n serializer = SalesTaxSerializer3\n else:\n serializer = FullSaleSerializer\n qs = serializer.setup_eager_loading(qs)\n data = list(serializer(qs, many=True).data)\n return data\n\n\n@dispatch(str, dict)\ndef sale(id, qstring):\n view_type = qstring.get('view', 'full')\n if type(view_type) == list:\n view_type = view_type[0]\n\n qs = Sale.objects.filter(id=id).first()\n\n if view_type == 'simple':\n serializer = SimpleSaleSerializer\n elif view_type == 'shipping':\n serializer = ShippingSaleSerializer\n elif view_type == 'fulfillment':\n serializer = SaleFulfillmentSerializer\n else:\n serializer = FullSaleSerializer\n\n return serializer(qs).data\n\n\n@dispatch(unicode, dict)\ndef sale(id, qstring):\n qs = Sale.objects.filter(id=id).first()\n return FullSaleSerializer(qs).data\n\n\n\ndef sales_by_month(qstring):\n output = qstring.get('output', 'raw')\n by_month = UnitSale.objects \\\n .annotate(year=Year('date'), month=Month('date')) \\\n .values('year', 'month') \\\n .annotate(qty=Sum('quantity'))\n \n def fmt_month(yr, mth):\n return datetime.date(yr, mth, 1)\n\n rslt = [(fmt_month(r['year'], r['month']), r['qty']) for r in by_month]\n if output == 'raw':\n return rslt\n elif output == 'chart':\n sorted_data = sorted(rslt, key=operator.itemgetter(0))\n\n chart_data = {}\n chart_data['chart_data'] = {}\n chart_data['chart_data']['x_points'] = [x[0] for x in sorted_data]\n chart_data['chart_data']['values'] = []\n chart_data['chart_data']['values'].append([x[1] for x in sorted_data])\n chart_data['chart_data']['seriesTypes'] = ['bar']\n return chart_data\n\n\"\"\"\ndef sales_by_month(qstring):\n all_sales = sorted(sale({'view': 'full'}), key=lambda x: parse(x['sale_date']))\n output = qstring.get('output', 'raw')\n\n def group_key(o):\n dt = parse(o['sale_date'])\n return (dt.year, dt.month)\n\n def agg(o):\n return sum([u['quantity'] for u in o['unit_sale']])\n\n def fmt_month(m):\n return datetime.date(m[0], m[1], 1).strftime('%b-%y')\n\n grouped = itertools.groupby(all_sales, key=group_key)\n if output == 'raw':\n return dict((fmt_month(k), sum([agg(o) for o in v])) for k, v in grouped)\n elif output == 'chart':\n data = dict((k, sum([agg(o) for o in v])) for k, v in grouped)\n sorted_dates = sorted(data.keys(), key=lambda x: x[0]*12 + x[1])\n\n chart_data = {}\n chart_data['chart_data'] = {}\n chart_data['chart_data']['x_points'] = [fmt_month(d) for d in sorted_dates]\n chart_data['chart_data']['values'] = []\n chart_data['chart_data']['values'].append([data.get(x, 0) for x in sorted_dates])\n chart_data['chart_data']['seriesTypes'] = ['bar']\n return chart_data\n else:\n return None\n\"\"\"\n\ndef incomplete_sales_count(qstring):\n return Sale.objects.filter(customer_code='unknown').count()\n\ndef sales_by_counterparty(qstring):\n all_sales = sorted(sale({'view': 'full'}), key=lambda x: x['customer_code'])\n output = qstring.get('output', 'raw')\n\n def agg(o):\n return sum([u['quantity'] for u in o['unit_sale']])\n\n grouped = itertools.groupby(all_sales, key=lambda x: x['customer_code'])\n if output == 'raw':\n return dict((k, sum([agg(o) for o in v])) for k, v in grouped)\n elif output == 'chart':\n data = dict((k, sum([agg(o) for o in v])) for k, v in grouped)\n sorted_data = sorted(data.items(), key=operator.itemgetter(1))\n sorted_data = [x for x in sorted_data if x[1] >= 5]\n chart_data = {}\n chart_data['chart_data'] = {}\n chart_data['chart_data']['x_points'] = [x[0] for x in sorted_data]\n chart_data['chart_data']['values'] = []\n chart_data['chart_data']['values'].append([x[1] for x in sorted_data])\n chart_data['chart_data']['seriesTypes'] = ['bar']\n return chart_data\n\n\ndef sales_by_channel(qstring):\n output = qstring.get('output', 'raw')\n by_channel = UnitSale.objects.values('sale__channel__label').annotate(Sum('quantity'))\n rslt = dict((r['sale__channel__label'], r['quantity__sum']) for r in by_channel)\n # only count those at greater than 5% of total\n total_units = sum(rslt.values())\n threshold = int(0.05 * total_units)\n\n if output == 'raw':\n return rslt\n elif output == 'chart':\n rslt = dict((k, v) for k, v in rslt.items() if v >= threshold)\n rslt['OTHER'] = total_units - sum(rslt.values())\n\n sorted_data = sorted(rslt.items(), key=operator.itemgetter(1))\n\n chart_data = {}\n chart_data['chart_data'] = {}\n chart_data['chart_data']['x_points'] = [x[0] for x in sorted_data]\n chart_data['chart_data']['values'] = []\n chart_data['chart_data']['values'].append([x[1] for x in sorted_data])\n chart_data['chart_data']['seriesTypes'] = ['bar']\n return chart_data\n\n\"\"\"\ndef sales_by_channel(qstring):\n all_sales = sorted(sale({'view': 'full'}), key=lambda x: x['channel'])\n output = qstring.get('output', 'raw')\n\n def agg(o):\n return sum([u['quantity'] for u in o['unit_sale']])\n\n grouped = itertools.groupby(all_sales, key=lambda x: x['channel'])\n rslt = dict((k, sum([agg(o) for o in v])) for k, v in grouped)\n \n # only count those at greater than 5% of total\n total_units = sum(rslt.values())\n threshold = int(0.05 * total_units)\n \n\n if output == 'raw':\n return rslt\n elif output == 'chart':\n rslt = dict((k, v) for k, v in rslt.items() if v >= threshold)\n rslt['OTHER'] = total_units - sum(rslt.values())\n\n sorted_data = sorted(rslt.items(), key=operator.itemgetter(1))\n\n chart_data = {}\n chart_data['chart_data'] = {}\n chart_data['chart_data']['x_points'] = [x[0] for x in sorted_data]\n chart_data['chart_data']['values'] = []\n chart_data['chart_data']['values'].append([x[1] for x in sorted_data])\n chart_data['chart_data']['seriesTypes'] = ['bar']\n return chart_data\n\"\"\"\n\ndef missing_cps(qstring):\n qs = Sale.objects.filter(customer_code='unknown')\n qs = SimpleSaleSerializer.setup_eager_loading(qs)\n return SimpleSaleSerializer(qs, many=True).data\n\n\ndef channel_counts(qstring):\n channels = Channel.objects.all()\n return dict((str(channel), Sale.objects.filter(channel=channel).count()) for channel in channels)\n\n\ndef sale_count(qstring):\n sku_count = UnitSale.objects.values('sku').annotate(cnt=Sum('quantity'))\n products = product_api.product({})\n\n item_count = {}\n for sku in sku_count:\n product_info = next((p for p in products if p['id'] == sku['sku']), None)\n for u in product_info['skuunit']:\n if u['inventory_item'] not in item_count:\n item_count[u['inventory_item']] = sku['cnt'] * u['quantity']\n else:\n item_count[u['inventory_item']] += sku['cnt'] * u['quantity']\n\n if qstring.get('chart'):\n sorted_data = sorted(item_count.items(), key=operator.itemgetter(1))\n chart_data = {}\n chart_data['x_vals'] = [x[0] for x in sorted_data]\n series_0 = {'name': 'Unit Sales'}\n series_0['data'] = [x[1] for x in sorted_data]\n chart_data['series'] = [series_0]\n return chart_data\n else:\n return item_count\n\n\ndef sales_counts(qstring):\n all_skus = product_api.inventoryitem({})\n all_sales = UnitSale.objects.all() \\\n .prefetch_related(Prefetch('sku__skuunit__inventory_item'))\n\n sales_counts = dict((k['label'],0) for k in all_skus)\n\n for u_sale in all_sales:\n u_sale_counts = u_sale.inventory_items()\n for sku in u_sale_counts:\n sales_counts[sku] += u_sale_counts[sku]\n\n return sales_counts\n \ndef unpaid_sales(channel_lbl, qstring):\n \"\"\"\n For sales in a given channel aggregate all the payoutlines\n and report on those where aggregated payouts do not match\n the total receivable on the order\n \"\"\"\n pls = PayoutLine.objects.filter(payout__channel__counterparty_id=channel_lbl) \\\n .values('sale_id') \\\n .annotate(total=Sum('amount'))\n \n payout_lines = dict((p['sale_id'], p['total']) for p in pls)\n \n sale_ids = [t['sale_id'] for t in pls]\n qs = Sale.objects.filter(id__in=sale_ids)\n qs = SaleProceedsSerializer.setup_eager_loading(qs)\n proceeds = SaleProceedsSerializer(qs, many=True).data\n\n cols = ['label', 'sale_date', 'paid_thru', 'shipping_name', 'proceeds', 'items_string']\n\n def _get_row(raw):\n row = dict((k, raw.get(k)) for k in cols)\n if not row['proceeds']:\n row['proceeds'] = Decimal('0')\n\n row['received'] = payout_lines.get(raw['id'], Decimal('0'))\n row['diff'] = row['proceeds'] - row['received']\n return row\n\n output = [_get_row(r) for r in proceeds]\n output = [r for r in output if abs(r['diff']) > Decimal('1')]\n\n return output\n\n\n\n\ndef unpaid_channel(channel_lbl, qstring):\n # find Shopify sales which are not in a channel payout batch\n paidout_sales = [x['sale_id'] for x in PayoutLine.objects.filter(payout__channel__label=channel_lbl).values('sale_id')]\n qs = Sale.objects.filter(channel__label=channel_lbl) \\\n .exclude(id__in=paidout_sales)\n qs = SaleProceedsSerializer.setup_eager_loading(qs)\n unpaid = list(SaleProceedsSerializer(qs, many=True).data)\n return [u for u in unpaid if u['proceeds'] != Decimal('0')]\n","sub_path":"savor/sales/apiv1/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":15033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116225764","text":"import glob, os\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport random\n\nfrom sklearn import svm\nfrom merfishdecoder.core import dataset\nfrom merfishdecoder.util import utilities\nfrom merfishdecoder.util import barcoder\n\ndef run_job(dataSetName: str = None,\n decodedImagesDir: str = None,\n outputName: str = \"pixel_score_machine.pkl\",\n zposNum: int = 50):\n \n \"\"\"\n Training pixel-based score machine.\n\n Args\n ----\n dataSetName: input dataset name.\n \n decodedImagesName: a list of decoded image file names.\n\n outputName: pixel scoring model file name.\n \n zposNum: number of zplanes used for training the model.\n \n \"\"\"\n \n # dataSetName = \"MERFISH_test/data/\"\n # decodedImagesDir = \"decodedImages\"\n # outputName = \"pixel_score_machine.pkl\"\n \n utilities.print_checkpoint(\"Train Pixel Score Model\")\n utilities.print_checkpoint(\"Start\")\n \n # generate dataset object\n dataSet = dataset.MERFISHDataSet(\n dataDirectoryName = dataSetName);\n\n # change to work directory\n os.chdir(dataSet.analysisPath)\n fnames = glob.glob(os.path.join(decodedImagesDir, \"*.npz\"))\n fnames = random.sample(fnames,\n min(len(fnames), zposNum))\n \n X_tr = []; Y_tr = [];\n for fn in fnames:\n decodes = np.load(fn)\n\n m = np.log10(decodes[\"magnitudeImage\"][\n decodes[\"decodedImage\"] > -1])\n\n d = decodes[\"distanceImage\"][\n decodes[\"decodedImage\"] > -1]\n \n o = decodes[\"decodedImage\"][\n decodes[\"decodedImage\"] > -1]\n \n y = np.ones(m.shape[0])\n y[np.isin(o, dataSet.get_codebook().get_blank_indexes())] = 0\n \n x = np.array([m, d]).T\n\n # now sample the same number of positive barcodes\n numPos = np.count_nonzero(y == 1)\n numNeg = np.count_nonzero(y == 0)\n\n # sample\n num = min(numPos, numNeg)\n idxPos = np.random.choice(np.nonzero(y)[0], num)\n idxNeg = np.random.choice(np.where(y == 0)[0], num)\n\n # create training dataset\n x_tr = x[np.concatenate([idxPos, idxNeg])]\n y_tr = y[np.concatenate([idxPos, idxNeg])]\n \n X_tr.append(x_tr)\n Y_tr.append(y_tr)\n decodes.close()\n\n X_tr = np.concatenate(X_tr)\n Y_tr = np.concatenate(Y_tr)\n \n idx = np.random.choice(\n range(X_tr.shape[0]), \n min(X_tr.shape[0], 50000))\n\n rbf_svc = svm.SVC(\n kernel='rbf', \n probability=True, \n gamma=\"auto\",\n C = 0.5)\n\n rbf_svc.fit(X_tr[idx], Y_tr[idx])\n \n pickle.dump(rbf_svc, \n open(outputName, 'wb'))\n \n dat = pd.DataFrame(X_tr[idx], columns=[\"m\", \"d\"])\n dat = dat.assign(y = Y_tr[idx])\n dat = dat.assign(p = rbf_svc.predict_proba(X_tr[idx])[:,1])\n dat.to_csv(\"pixel_score_machine.csv\", index=False)\n utilities.print_checkpoint(\"Done\")\n\n\n","sub_path":"merfishdecoder/apps/run_train_psm.py","file_name":"run_train_psm.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633806800","text":"# -*- coding: utf-8 -*-\n\nimport config\n\nfrom tornado.gen import coroutine\nfrom tornado.web import RequestHandler\nfrom tornado.websocket import WebSocketHandler\nfrom tornado.concurrent import Future\n\nfrom .util import Utils\nfrom .cache import MCachePool\nfrom .metaclass import SubclassMetaclass\nfrom .database import safestr\n\nfrom model.m_rbac import RbacModel\n\n\nclass SocketBaseHandler(WebSocketHandler, Utils):\n\n pass\n\n\nclass RequestBaseHandler(RequestHandler, Utils):\n\n def __init__(self, application, request, **kwargs):\n\n self._prepare = []\n self._on_finish = []\n\n RequestHandler.__init__(self, application, request, **kwargs)\n\n def get_cache_client(self):\n\n if(hasattr(self, r'_cache_client')):\n return getattr(self, r'_cache_client')\n\n cache = MCachePool().get_client()\n\n setattr(self, r'_cache_client', cache)\n\n return cache\n\n def head(self, *args, **kwargs):\n\n self.finish()\n\n def options(self, *args, **kwargs):\n\n self.finish()\n\n @coroutine\n def prepare(self):\n\n self._parse_json_arguments()\n\n if(self._prepare):\n for func in self._prepare:\n result = func()\n if(isinstance(result, Future)):\n yield result\n\n def on_finish(self):\n\n if(self._on_finish):\n for func in self._on_finish:\n func()\n\n def set_default_headers(self):\n\n self.set_header(r'Cache-Control', r'no-cache')\n\n self.set_header(r'Timestamp', self.timestamp())\n\n payload = self.get_header(r'Payload')\n\n if(payload):\n self.set_header(r'Payload', payload)\n\n origin = self.get_header(r'Origin')\n\n if(origin):\n\n if(config.Static.Debug):\n\n self.set_header(r'Access-Control-Allow-Origin', r'*')\n\n else:\n\n allow_origin = config.Static.AccessControlAllowOrigin\n\n if(r'*' in allow_origin or origin in allow_origin):\n self.set_header(r'Access-Control-Allow-Origin', origin)\n\n method = self.get_header(r'Access-Control-Request-Method')\n if(method):\n self.set_header(r'Access-Control-Allow-Methods', method)\n\n headers = self.get_header(r'Access-Control-Request-Headers')\n if(headers):\n self.set_header(r'Access-Control-Allow-Headers', headers)\n\n self.set_header(r'Access-Control-Max-Age', r'86400')\n self.set_header(r'Access-Control-Allow-Credentials', r'true')\n\n def set_cookie(self, name, value, domain=None, expires=None, path=\"/\", expires_days=None, **kwargs):\n\n if(type(value) not in (str, bytes)):\n value = str(value)\n\n return super().set_cookie(name, value, domain, expires, path, expires_days, **kwargs)\n\n def get_secure_cookie(self, name, value=None, max_age_days=31, min_version=None):\n\n result = super().get_secure_cookie(name, value, max_age_days, min_version)\n\n if(isinstance(result, bytes)):\n result = result.decode(r'utf-8')\n\n return result\n\n def set_secure_cookie(self, name, value, expires_days=30, version=None, **kwargs):\n\n if(type(value) not in (str, bytes)):\n value = str(value)\n\n return super().set_secure_cookie(name, value, expires_days, version, **kwargs)\n\n def get_current_user(self):\n\n session = self.get_cookie(r'session')\n\n if(not session):\n\n session = self.uuid1()\n\n self.set_cookie(r'session', session)\n\n self.current_user = session\n\n return session\n\n def compute_etag(self):\n\n return None\n\n def _parse_json_arguments(self):\n\n self.request.json_arguments = {}\n\n content_type = self.content_type\n\n if(content_type and content_type.find(r'application/json') >= 0 and self.body):\n\n try:\n\n json_args = self.json_decode(self.body)\n\n if(isinstance(json_args, dict)):\n\n self.request.json_arguments.update(json_args)\n\n for key, val in self.request.json_arguments.items():\n\n if(not isinstance(val, str)):\n val = str(val)\n\n self.request.arguments.setdefault(key, []).append(val)\n\n except:\n\n self.exception(r'Invalid application/json body: {0}'.format(self.body))\n\n @property\n def request_module(self):\n\n return r'{0}.{1}'.format(self.module, self.method)\n\n @property\n def module(self):\n\n return r'{0}.{1}'.format(self.__class__.__module__, self.__class__.__name__)\n\n @property\n def method(self):\n\n return self.request.method.lower()\n\n @property\n def version(self):\n\n return self.request.version.lower()\n\n @property\n def protocol(self):\n\n return self.request.protocol\n\n @property\n def host(self):\n\n return self.request.host\n\n @property\n def path(self):\n\n return self.request.path\n\n @property\n def query(self):\n\n return self.request.query\n\n @property\n def body(self):\n\n return self.request.body\n\n @property\n def files(self):\n\n return self.request.files\n\n @property\n def referer(self):\n\n return self.get_header(r'Referer', r'')\n\n @property\n def client_ip(self):\n\n return self.get_header(r'X-Real-IP', self.request.remote_ip)\n\n @property\n def content_type(self):\n\n return self.get_header(r'Content-Type', r'')\n\n @property\n def content_length(self):\n\n result = self.get_header(r'Content-Length', r'')\n\n return int(result) if result.isdigit() else 0\n\n def get_header(self, name, default=None):\n \"\"\"\n 获取header数据\n \"\"\"\n return self.request.headers.get(name, default)\n\n def get_files(self, name):\n \"\"\"\n 获取files数据\n \"\"\"\n result = []\n\n file_data = self.files.get(name, None)\n\n if(file_data is not None):\n self.list_extend(result, file_data)\n\n for index in range(len(self.files)):\n\n file_data = self.files.get(r'{0:s}[{1:d}]'.format(name, index), None)\n\n if(file_data is not None):\n self.list_extend(result, file_data)\n\n return result\n\n def get_arg_str(self, name, default=r'', length=0, sqlsafe=False):\n \"\"\"\n 获取str型输入\n \"\"\"\n result = self.get_argument(name, None, True)\n\n if(result is None):\n return default\n\n if(not isinstance(result, str)):\n result = str(result)\n\n if(length > 0 and len(result) > length):\n result = result[0:length]\n\n return safestr(result) if sqlsafe else result\n\n def get_arg_bool(self, name, default=False):\n \"\"\"\n 获取bool型输入\n \"\"\"\n result = self.get_argument(name, None, True)\n\n if(result is None):\n return default\n else:\n return result not in (r'False', r'false', r'0', r'', False, 0)\n\n def get_arg_int(self, name, default=0, min_val=None, max_val=None):\n \"\"\"\n 获取int型输入\n \"\"\"\n result = self.get_argument(name, None, True)\n\n if(result is None):\n return default\n\n try:\n\n if(not isinstance(result, int)):\n result = int(result)\n\n if(min_val is not None):\n result = max(result, min_val)\n\n if(max_val is not None):\n result = min(result, max_val)\n\n except:\n\n result = default\n\n return result\n\n def get_arg_float(self, name, default=0.0, min_val=None, max_val=None):\n \"\"\"\n 获取float型输入\n \"\"\"\n result = self.get_argument(name, None, True)\n\n if(result is None):\n return default\n\n try:\n\n if(not isinstance(result, float)):\n result = float(result)\n\n if(min_val is not None):\n result = max(result, min_val)\n\n if(max_val is not None):\n result = min(result, max_val)\n\n except:\n\n result = default\n\n return result\n\n def get_arg_json(self, name, default=None, error=None):\n \"\"\"\n 获取json型输入\n \"\"\"\n result = self.get_argument(name, None, True)\n\n if(result is None):\n\n result = default\n\n else:\n\n try:\n\n result = self.json_decode(result)\n\n except:\n\n result = error\n\n self.exception(r'Invalid json argument: {0}'.format(result))\n\n return result\n\n def get_json_argument(self, name, default=None):\n\n return self.request.json_arguments.get(name, default)\n\n def get_json_arguments(self):\n\n return self.deepcopy(self.request.json_arguments)\n\n def get_all_arguments(self):\n\n result = {}\n\n for key in self.request.arguments.keys():\n result[key] = self.get_argument(key)\n\n return result\n\n def write_json(self, chunk, status_code=200):\n \"\"\"\n 输出JSON类型\n \"\"\"\n self.set_header(r'Content-Type', r'application/json')\n\n if(status_code != 200):\n self.set_status(status_code)\n\n try:\n response = self.json_encode(chunk) if chunk else r'{}'\n except:\n response = None\n\n return self.finish(response)\n\n def write_png(self, chunk):\n \"\"\"\n 输出PNG类型\n \"\"\"\n self.set_header(r'Content-Type', r'image/png')\n\n return self.finish(chunk)\n\n\nclass RequestRbacHandler(RequestBaseHandler, metaclass=SubclassMetaclass):\n\n @classmethod\n def get_rbac_modules(self):\n\n if(hasattr(self, r'_subclasses')):\n return getattr(self, r'_subclasses')\n else:\n return None\n\n @coroutine\n def prepare(self):\n\n yield super().prepare()\n\n if(not self._finished):\n\n result = yield self.rbac_auth()\n\n if(not result):\n self.send_error(401)\n\n @coroutine\n def rbac_auth(self):\n\n role_id = self.rbac_role\n\n if(not role_id):\n return False\n\n if(role_id == RbacModel.SUPER_ROLE):\n return True\n\n m_rbac = RbacModel()\n\n result = yield m_rbac.auth(role_id, self.module, self.method)\n\n return result\n\n @property\n def rbac_role(self):\n\n if(hasattr(self, r'_rbac_role')):\n return getattr(self, r'_rbac_role')\n else:\n return 0\n\n @rbac_role.setter\n def rbac_role(self, role):\n\n setattr(self, r'_rbac_role', int(role))\n\n\nclass RequestRbacMixin():\n\n @coroutine\n def rbac_auth(self):\n\n return True\n\n\nclass RequestSessMixin():\n\n def initialize(self):\n\n self._prepare.append(self._build_session)\n self._on_finish.append(self._flush_session)\n\n @coroutine\n def _build_session(self):\n\n self._session_data = {}\n self._session_flush = False\n\n cache = self.get_cache_client()\n\n ckey = cache.key(r'session_{0}'.format(self.current_user))\n\n result = yield cache.get(ckey)\n\n if(result and isinstance(result, dict)):\n self._session_data = result\n\n @coroutine\n def _flush_session(self):\n\n flush, self._session_flush = self._session_flush, False\n\n cache = self.get_cache_client()\n\n ckey = cache.key(r'session_{0}'.format(self.current_user))\n\n if(self._session_data):\n\n if(flush):\n yield cache.set(ckey, self._session_data, config.Static.SessionExpires)\n else:\n yield cache.expire(ckey, config.Static.SessionExpires)\n\n elif(flush):\n\n yield cache.delete(ckey)\n\n def has_session(self, key):\n\n return key in self._session_data\n\n def get_session(self, key, default=None):\n\n return self._session_data.get(key, default)\n\n def set_session(self, key, val):\n\n self._session_data[key] = val\n\n self._session_flush = True\n\n def del_session(self, key=None):\n\n if(key is None):\n\n self._session_data.clear()\n\n else:\n\n if(key in self._session_data):\n del self._session_data[key]\n\n self._session_flush = True\n","sub_path":"util/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":12369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"295308108","text":"#coding: utf-8\r\nimport pymysql\r\npymysql.install_as_MySQLdb()\r\nimport MySQLdb\r\n\r\ndef inserir_comentario_banco(nome, data, titulo, comentario):\r\n try:\r\n db = MySQLdb.connect(\"localhost\", \"seuloginmysql\", \"suasenhamysql\", \"seubancomysql\")\r\n\r\n cursor = db.cursor()\r\n\r\n cursor.execute(\"INSERT INTO comentarios VALUES(null, %s, %s, %s, %s)\" ,(data, nome, titulo, comentario))\r\n\r\n db.commit()\r\n return True\r\n except Exception as e:\r\n print (\"Erro: %s \"%(e))\r\n db.rollback()\r\n return False\r\n\r\n db.close()\r\n","sub_path":"funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"277480444","text":"import pygame\nfrom plane_sprites import *\n\n# mixer的初始化\npygame.init()\npygame.mixer.init()\n\nclass PlaneGame(object):\n \"\"\"飞机大战主程序\"\"\"\n\n def __init__(self):\n print(\"游戏初始化\")\n\n # 载入背景音乐\n pygame.mixer.music.load(\"./music/game_music.mp3\")\n # 播放背景音乐\n pygame.mixer.music.play()\n # 创建游戏窗口\n self.screen = pygame.display.set_mode(SCREEN_RECT.size)\n # 创建游戏时钟\n self.clock = pygame.time.Clock()\n # 调用精灵组创建的私有方法\n self.__create_sprites()\n\n # 创建定时器事件==> 创建敌机\n pygame.time.set_timer(ENEMY_EVENT, 1000) # 时间单位为毫秒\n # 创建定时器事件==> 发射子弹\n pygame.time.set_timer(HERO_FIRE_EVENT, 200)\n\n def __create_sprites(self):\n\n # 背景图片交替滚动实现\n bg1 = Background()\n bg2 = Background(True)\n\n self.back_group = pygame.sprite.Group(bg1, bg2)\n\n # 创建敌机精灵组:--敌机精灵在监听方法-定时器中创建\n self.eneny_group = pygame.sprite.Group()\n\n # 创建战机精灵\n self.hero = Hero()\n # 创建战机精灵组\n self.hero_group = pygame.sprite.Group(self.hero)\n\n\n def start_game(self):\n print(\"开始游戏===>>\")\n while True:\n # 刷新帧率\n self.clock.tick(FPS)\n # 事件监听\n self.__event_handler()\n # 碰撞检测\n self.__check_collide()\n # update/draw精灵组\n self.__update_sprites()\n # update显示\n pygame.display.update()\n\n\n # 事件监听\n def __event_handler(self):\n for event in pygame.event.get():\n # --> 退出游戏\n if event.type == pygame.QUIT:\n self.__game_over()\n elif event.type == ENEMY_EVENT:\n self.eneny_group.add(Enemy())\n elif event.type == HERO_FIRE_EVENT:\n self.hero.fire()\n\n # 控制战机左右移动的两种监听方式\n # 1.====>>>灵活性差,每次键盘落下抬起算一次响应\n # elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:\n # self.hero.rect.x += 1\n # print(\"战机右移==>\")\n # 2.===>>>灵活性好,可以按下不放,持续响应\n keys_pressed = pygame.key.get_pressed()\n if keys_pressed[pygame.K_RIGHT]:\n self.hero.speed = 2\n\n # self.hero.rect.x += 2\n # print(\"战机右移===>\")\n\n elif keys_pressed[pygame.K_LEFT]:\n self.hero.speed = -2\n\n # self.hero.rect.x -= 2\n # print(\"<===战机左移\")\n\n else:\n self.hero.speed = 0\n\n # 碰撞检测\n def __check_collide(self):\n\n # 子弹和敌机\"同归于尽\"\n while pygame.sprite.groupcollide(self.hero.bullet_group, self.eneny_group, True, True):\n pygame.mixer.music.stop()\n # 载入击中音乐\n pygame.mixer.music.load(\"./music/bullet.mp3\")\n # 播放击中音乐\n pygame.mixer.music.play()\n\n\n # 敌机与战机发生碰撞-->发生碰撞返回列表\n enemies = pygame.sprite.spritecollide(self.hero, self.eneny_group, True)\n # 判断列表值--确定战机状态\n if len(enemies) > 0:\n # 消除战机\n self.hero.kill()\n\n # 游戏结束\n PlaneGame.__game_over()\n\n # 精灵/精灵组的更新\n def __update_sprites(self):\n self.back_group.update()\n self.back_group.draw(self.screen)\n\n self.eneny_group.update()\n self.eneny_group.draw(self.screen)\n\n self.hero_group.update()\n self.hero_group.draw(self.screen)\n\n self.hero.bullet_group.update()\n self.hero.bullet_group.draw(self.screen)\n @staticmethod\n def __game_over():\n print(\"游戏结束\")\n pygame.quit()\n exit()\n\nif __name__ == '__main__':\n game = PlaneGame()\n game.start_game()","sub_path":"plane_main3.py","file_name":"plane_main3.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266230126","text":"'''\nThis file contains classes that implements a scikit-learn like API for MCMC\nsampling. \n'''\n\nfrom abc import abstractmethod\nimport pystan\nimport numpy as np\nimport pandas as pd\nimport utils\nfrom matplotlib import pyplot as plt\nfrom typing import Iterable\n\nclass BaseStanFactorizer:\n '''\n Template class for classes for matrix factorization using Stan\n '''\n def __init__(self):\n self.fitted = False\n\n @abstractmethod\n def fit_transform(self, X: np.ndarray):\n '''\n This abstract method should create the instance attributes \"Us\"\n and \"Vs\" and return them. It should also invoke the self.set_fitted \n method\n '''\n \n def fit(self, *args, **kwargs):\n '''\n Invokes self.fit_transform(*args, **kwargs)\n and returns self\n '''\n self.fit_transform(*args, **kwargs)\n return self\n\n @abstractmethod\n def _likelihood_sample(self, P: np.ndarray, picks: np.ndarray) -> np.ndarray:\n '''\n Function used for predictive sampling\n '''\n\n @staticmethod\n def get_dense_shape(df: pd.DataFrame):\n '''\n df should have first column representing row index\n and second column representing column index.\n '''\n # Plus 1 because first index should be 0\n return df.iloc[:,0].max()+1, df.iloc[:,1].max()+1\n\n def assert_fitted(self):\n assert self.fitted, 'Model not fitted'\n\n def set_fitted(self):\n self.fitted = True\n\n def mae(self, df: pd.DataFrame):\n '''\n Computes mean absolute error\n\n df: should represent matrix in sparse format, each row should\n consists only of [row_index, col_index, value] in that order\n '''\n # Xs is a 3D array\n Xs = self.Us@self.Vs\n\n row_inds = df.iloc[:,0]\n col_inds = df.iloc[:,1]\n ratings = df.iloc[:,2].values\n\n # Equivalent to np.array([X[row_inds, col_inds] for X in Xs])\n y_preds = Xs[:,row_inds, col_inds]\n abserrors = np.abs(y_preds - ratings)\n return abserrors.mean()\n\n def _plot_ci(self, n: int, P: np.ndarray, lower_bounds: np.ndarray, \n upper_bounds: np.ndarray, ax: 'Axis', *args, **kwargs):\n '''\n Plots credible intervals\n\n n: Number of elements to plot credible intervals for\n\n lower_bounds: array consisting of lower bounds of credible interval\n\n upper_bounds: array consisting of upper bounds of credible interval\n\n args and kwargs go to ax.errorbar\n '''\n means = P.mean(axis=0)\n\n if ax is None:\n ax = plt.gca()\n\n ax.errorbar(range(n), means,\n yerr=[means-lower_bounds, upper_bounds-means],\n fmt='o', *args, **kwargs)\n\n def ci(self, n_elements: int=20, thin: int=1, row_inds: Iterable=None, \n col_inds: Iterable=None, n_samples: int=1000, p=0.95, plot: bool=False, \n ax: 'matplotlib.Axes'=None, *args, **kwargs):\n '''\n Computes credible intervals first elements of matrix.\n\n Parameters\n ------------\n n_elements: Number of elements to calculte credible intervals for, \n no effect if col_inds and row_inds are given.\n\n thin: Thinning value, 1 by default. This is mostly used to reduce RAM\n usage\n\n row_inds: Optional, which row indices in X to show CIs for\n\n col_inds: Optional, which column indices in X to show CIs for\n\n n_samples: Number of samples to sample from predictive distribution\n\n p: Optional, credible interval percentage, 0.95 by default\n\n plot: Optional, to plot credible intervals or not, False by default\n\n ax: Optional, plots on given ax, no effect if show is False\n\n args and kwargs go to ax.errorbar if plot is True\n\n Returns\n --------\n (lower_bounds, upper_bounds)\n '''\n self.assert_fitted()\n\n # This is equivalent to Xs = np.array([U@V for U,V in zip(Us, Vs)])\n Xs = self.Us[::thin]@self.Vs[::thin]\n\n if (row_inds is None) or (col_inds is None):\n assert (row_inds and col_inds) is None,\\\n \"Either row_inds and col_inds are both None, or both Iterables\"\n # Used to extract first n_elements from predicted Xs\n row_inds, col_inds = np.unravel_index(range(n_elements), Xs.shape[1:])\n \n assert len(row_inds) == len(col_inds),\\\n \"Length mismatch between row_inds and col_inds\"\n\n # Sample from predictive distribution\n picks = np.random.randint(0, len(Xs), n_samples)\n # Equivalent to np.array([X[row_inds, col_inds] for X in Xs[picks]])\n # It picks the relevant predicted elemnts, hence the name P\n P = Xs[picks][:,row_inds, col_inds]\n # Sample from likelihood distribution\n P = self._likelihood_sample(P, picks)\n P.sort(axis=0)\n\n # Get credible intervals of samples from predictive distribution\n half_p = (1-p)/2\n lb = np.floor((half_p*n_samples)).astype(int)\n ub = np.ceil((p+half_p)*n_samples).astype(int)\n\n lower_bounds, upper_bounds = P[lb], P[ub]\n\n if plot:\n self._plot_ci(len(row_inds), P, lower_bounds, upper_bounds, ax, *args,\n **kwargs)\n\n return lower_bounds, upper_bounds\n\nclass SimpleFactorizer(BaseStanFactorizer):\n '''\n Class for probabilistic matrix factorization using Stan.\n\n Not used\n '''\n def __init__(self, n_components: int=2, mu_u: float=1, sigma_u: float=5,\n mu_v: float=1, sigma_v=5, sigma_x=1,\n stanfile: str='sm_simple.stan', cache_name: str='simple', \n **stan_kwargs):\n '''\n Factorization: X \\approx UV, where X is the dense matrix\n\n Model:\n U ~ N(mu_u, sigma_u)\n V ~ N(mu_v, sigma_v)\n X ~ N(UV, sigma_x)\n\n Parameters\n -----------\n n_components: Embedding dimension\n mu_u: mean of elements in U\n sigma_u: std of elements in U\n mu_v: mean of elements in\n sigma_v: std of elements in V\n sigma_x: std of elements in X\n stanfile: file with stancode\n cache_name: name for compiled model\n stan_kwargs: Kwargs used for stanmodel.fit(**stan_kwargs)\n '''\n super().__init__()\n self.stanfile = stanfile\n self.cache_name = cache_name\n\n self.n_components = n_components\n\n self.mu_u = mu_u\n self.sigma_u = sigma_u\n\n self.mu_v = mu_v\n self.sigma_v = sigma_v\n\n self.sigma_x = sigma_x\n self.stan_kwargs = stan_kwargs\n\n def _likelihood_sample(self, P: np.ndarray, picks: np.ndarray):\n '''\n This is used to sample from predictive distribution. \n\n P: Rating estimates. Is a 2D array, where each row represent the selected\n elements for a pair of sampled U and V.\n\n picks: The indices for the elements used to extract the values in P. Not used\n for this model, but is still there for API compatibility.\n '''\n self.assert_fitted()\n return np.random.normal(loc=P, scale=self.sigma_x, size=P.shape)\n\n def fit_transform(self, df: pd.DataFrame):\n '''\n Parameters\n ----------\n df: should represent matrix in sparse format, each row should\n consists only of [row_index, col_index, value] in that order.\n\n kwargs: keyword arguments for StanModel.sampling()\n\n Returns\n -------\n Sampled values\n (Us, Vs)\n '''\n # Get shape (p, q) of dense matrix\n self.p, self.q = self.get_dense_shape(df)\n\n datadict = dict(\n n_components=self.n_components, n=len(df), p=self.p,\n q=self.q, df=df, mu_u=self.mu_u, sigma_u=self.sigma_u,\n mu_v=self.mu_v, sigma_v=self.sigma_v, sigma_x=self.sigma_x\n )\n\n self.code = utils.get_stan_code(self.stanfile)\n self.sm = utils.StanModel_cache(self.code, model_name=self.cache_name)\n\n self.stanfit = self.sm.sampling(datadict, **self.stan_kwargs)\n self.Us, self.Vs, self.lp__ =\\\n self.stanfit['U'], self.stanfit['V'], self.stanfit['lp__']\n\n # Set fitted flag\n self.set_fitted()\n\n return self.Us, self.Vs\n\nclass NormalFactorizer(BaseStanFactorizer):\n '''\n Class for probabilistic matrix factorization using Stan.\n '''\n def __init__(self, n_components: int=2, mu_u: float=0, sigma_u: float=5,\n mu_v: float=0, sigma_v=5, a_beta: float=1, b_beta: float=1,\n stanfile: str='sm_normal.stan', cache_name: str='normal', \n **stan_kwargs):\n '''\n Factorization: X \\approx UV, where X is the dense matrix\n\n Model:\n U ~ N(mu_u, sigma_u)\n V ~ N(mu_v, sigma_v)\n beta ~ gamma(a_beta, b_beta)\n X ~ N(UV, beta)\n\n Parameters\n -----------\n n_components: Embedding dimension\n\n mu_u: mean of elements in U\n sigma_u: std of elements in U\n\n mu_v: mean of elements in V\n sigma_v: std of elements in V\n\n a_beta: shape of gamma distribution for beta\n b_beta: scale of gamma distribution for beta\n\n stanfile: file with stancode\n cache_name: name for compiled model\n stan_kwargs: Kwargs used for stanmodel.fit(**stan_kwargs)\n '''\n super().__init__()\n self.stanfile = stanfile\n self.cache_name = cache_name\n\n self.n_components = n_components\n\n self.mu_u = mu_u\n self.sigma_u = sigma_u\n\n self.mu_v = mu_v\n self.sigma_v = sigma_v\n\n self.a_beta = a_beta\n self.b_beta = b_beta\n\n self.stan_kwargs = stan_kwargs\n\n def _likelihood_sample(self, P, picks):\n '''\n This is used to sample from predictive distribution. \n\n P: Rating estimates. Is a 2D array, where each row represent the selected\n elements for a pair of sampled U and V.\n\n picks: The indices for the elements used to extract the values in P. \n '''\n self.assert_fitted()\n return np.random.normal(loc=P, scale=self.betas[picks].reshape(-1,1),\n size=P.shape)\n\n def fit_transform(self, df: pd.DataFrame):\n '''\n Parameters\n -----------\n df: should represent matrix in sparse format, each row should\n consists only of [row_index, col_index, value] in that order\n\n kwargs: keyword arguments for StanModel.sampling()\n\n Returns\n --------\n Sampled values\n (Us, Vs)\n '''\n # Get shape (p, q) of dense matrix\n self.p, self.q = self.get_dense_shape(df)\n\n datadict = dict(\n n_components=self.n_components, n=len(df), p=self.p,\n q=self.q, df=df, mu_u=self.mu_u, sigma_u=self.sigma_u,\n mu_v=self.mu_v, sigma_v=self.sigma_v, a_beta=self.a_beta,\n b_beta=self.b_beta\n )\n\n self.code = utils.get_stan_code(self.stanfile)\n self.sm = utils.StanModel_cache(self.code, model_name=self.cache_name)\n\n self.stanfit = self.sm.sampling(datadict, **self.stan_kwargs)\n self.Us, self.Vs, self.betas, self.lp__ =\\\n self.stanfit['U'], self.stanfit['V'], self.stanfit['beta'], self.stanfit['lp__']\n\n # Set fitted flag\n self.set_fitted()\n\n return self.Us, self.Vs\n\nclass NonNegativeFactorizer(BaseStanFactorizer):\n '''\n Class for probabilistic non negative matrix factorization using Stan.\n '''\n def __init__(self, n_components: int=2, a_u: float=2, b_u: float=1,\n a_v: float=2, b_v: float=1, a_beta: float=1, b_beta: float=1,\n stanfile: str='sm_nmf.stan', cache_name: str='nmf',\n **stan_kwargs):\n '''\n Factorization: X \\approx UV, where X is the dense matrix\n\n Model:\n U ~ gamma(a_u, b_u)\n V ~ gamma(a_v, b_v)\n beta ~ gamma(a_beta, b_beta)\n X ~ N(UV, beta)\n\n Parameters\n -----------\n n_components: Embedding dimension\n\n a_u: shape of elements in U\n b_u: scale of elements in U\n\n a_v: shape of elements in V\n b_v: scale of elements in V\n\n a_beta: shape of gamma distribution for beta\n b_beta: scale of gamma distribution for beta\n\n stanfile: file with stancode\n cache_name: name for compiled model\n stan_kwargs: Kwargs used for stanmodel.fit(**stan_kwargs)\n '''\n super().__init__()\n self.stanfile = stanfile\n self.cache_name = cache_name\n\n self.n_components = n_components\n\n self.a_u = a_u\n self.b_u = b_u\n\n self.a_v = a_v\n self.b_v = b_v\n\n self.a_beta = b_beta\n self.b_beta = b_beta\n \n self.stan_kwargs = stan_kwargs\n\n def _likelihood_sample(self, P, picks):\n '''\n This is used to sample from predictive distribution. \n\n P: Rating estimates. Is a 2D array, where each row represent the selected\n elements for a pair of sampled U and V.\n\n picks: The indices for the elements used to extract the values in P.\n '''\n self.assert_fitted()\n return np.random.normal(loc=P, scale=self.betas[picks].reshape(-1,1),\n size=P.shape)\n\n def fit_transform(self, df: pd.DataFrame):\n '''\n Parameters\n -----------\n df: should represent matrix in sparse format, each row should\n consists only of [row_index, col_index, value] in that order\n\n Returns\n --------\n Sampled values\n (Us, Vs)\n '''\n # Get shape (p, q) of dense matrix\n self.p, self.q = self.get_dense_shape(df)\n\n datadict = dict(\n n_components=self.n_components, n=len(df), p=self.p,\n q=self.q, df=df, a_u=self.a_u, b_u=self.b_u, a_v=self.a_v,\n b_v=self.b_v, a_beta=self.a_beta, b_beta=self.b_beta\n )\n\n self.code = utils.get_stan_code(self.stanfile)\n self.sm = utils.StanModel_cache(self.code, model_name=self.cache_name)\n\n self.stanfit = self.sm.sampling(datadict, **self.stan_kwargs)\n self.Us, self.Vs, self.betas, self.lp__ =\\\n self.stanfit['U'], self.stanfit['V'], self.stanfit['beta'], self.stanfit['lp__']\n\n # Set fitted flag\n self.set_fitted()\n\n return self.Us, self.Vs\n\nclass ARD_Factorizer(BaseStanFactorizer):\n '''\n Class for probabilistic ARD matrix factorization using Stan.\n '''\n def __init__(self, n_components: int=2, mu_u: float=0, mu_v: float=0,\n a_alpha: float=1, b_alpha: float=0.08, a_beta: float=1, \n b_beta: float=1, stanfile: str='sm_ard.stan',\n cache_name: str='ard', **stan_kwargs):\n '''\n Factorization: X \\approx UV, where X is the dense matrix\n\n Model:\n U ~ N(mu_u, sigma_u)\n V ~ N(mu_v, sigma_v)\n beta ~ gamma(a_beta, b_beta)\n X ~ N(UV, beta)\n\n Parameters\n -----------\n n_components: Embedding dimension\n\n mu_u: mean of elements in U\n sigma_u: std of elements in U\n\n mu_v: mean of elements in V\n sigma_v: std of elements in V\n\n a_alpha: shape of gamma distribution for alpha\n b_alpha: scale of gamma distribution for alpha\n \n a_beta: shape of gamma distribution for beta\n b_beta: scale of gamma distribution for beta\n\n stanfile: file with stancode\n cache_name: name for compiled model\n stan_kwargs: Kwargs used for stanmodel.fit(**stan_kwargs)\n '''\n super().__init__()\n self.stanfile = stanfile\n self.cache_name = cache_name\n\n self.n_components = n_components\n\n self.mu_u = mu_u\n self.mu_v = mu_v\n \n self.a_alpha = a_alpha\n self.b_alpha = b_alpha\n \n self.a_beta = a_beta\n self.b_beta = b_beta\n\n self.stan_kwargs = stan_kwargs\n\n def _likelihood_sample(self, P, picks):\n self.assert_fitted()\n return np.random.normal(loc=P, scale=self.betas[picks].reshape(-1,1),\n size=P.shape)\n\n def fit_transform(self, df: pd.DataFrame):\n '''\n Parameters\n -----------\n df: should represent matrix in sparse format, each row should\n consists only of [row_index, col_index, value] in that order\n\n kwargs: keyword arguments for StanModel.sampling()\n\n Returns\n --------\n Sampled values\n (Us, Vs)\n '''\n # Get shape (p, q) of dense matrix\n self.p, self.q = self.get_dense_shape(df)\n\n datadict = dict(\n n_components=self.n_components, n=len(df), p=self.p,\n q=self.q, df=df, mu_u=self.mu_u, mu_v=self.mu_v, a_alpha=self.a_alpha,\n b_alpha=self.b_alpha, a_beta=self.a_beta, b_beta=self.b_beta\n )\n\n self.code = utils.get_stan_code(self.stanfile)\n self.sm = utils.StanModel_cache(self.code, model_name=self.cache_name)\n\n self.stanfit = self.sm.sampling(datadict, **self.stan_kwargs)\n\n self.Us_raw = self.stanfit['U']\n self.Vs_raw = self.stanfit['VT']\n self.alphas = self.stanfit['alpha']\n self.betas = self.stanfit['beta']\n self.lp__ = self.stanfit['lp__']\n\n # Scale the columns with the alpha values\n self.Us = self.Us_raw*self.alphas[:,np.newaxis,:]\n self.Vs = (self.Vs_raw*self.alphas[:,np.newaxis,:]).transpose([0,2,1])\n\n # Set fitted flag\n self.set_fitted()\n\n return self.Us, self.Vs\n\n","sub_path":"Projects/Project2/StanClasses.py","file_name":"StanClasses.py","file_ext":"py","file_size_in_byte":17714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"81885365","text":"import gevent\nfrom gevent import monkey\nmonkey.patch_all()# 该剧执行在导入socket前\nfrom socket import *\ndef handle(c):\n while True:\n data =c.recv(1024)\n if not data:\n break\n print(data.decode())\n c.send(b'OK')\n c.close()\n#创建套接字\n\ns =socket()\n\ns.bind(('0.0.0.0',8888))\ns.listen(5)\nwhile True:\n c,addr = s.accept()\n print(\"connect from:\",addr)\n # handle(c)\n gevent.spawn(handle,c)","sub_path":"gevent_server.py","file_name":"gevent_server.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"185306105","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 30 10:52:29 2018\n\n@author: Dominic O'Kane\n\"\"\"\n\n###############################################################################\n\n\nclass FinRateConverter(object):\n\n def __init__(self):\n\n # we permit frequency to be entered as a string or integer\n if isinstance(frequency, int):\n\n if frequency == 1:\n self.name = \"1Y\"\n self.months = 12\n elif frequency == 2:\n self.name = \"6M\"\n self.months = 6\n elif frequency == 4:\n self.name = \"3M\"\n self.months = 3\n elif frequency == 12:\n self.name = \"1M\"\n self.months = 1\n else:\n raise Exception(\"Frequency value must be 1, 2, 4 or 12\")\n\n elif isinstance(frequency, str):\n\n if frequency == \"12M\":\n self.months = 12\n self.name = frequency\n if frequency == \"1Y\":\n self.months = 12\n self.name = frequency\n elif frequency == \"6M\":\n self.months = 6\n self.name = frequency\n elif frequency == \"3M\":\n self.months = 3\n self.name = frequency\n elif frequency == \"1M\":\n self.months = 1\n self.name = frequency\n else:\n raise Exception(\"Frequency value must be 1M, 3M, 6M or 12M\")\n\n###############################################################################\n\n def str(self):\n s = self.name\n return s\n\n###############################################################################\n","sub_path":"financepy/finutils/FinRateConverter.py","file_name":"FinRateConverter.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"203944366","text":"# Copyright 2020 Google LLC\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Defines the number operator, :math:`S^2` operator, :math:`S_z` operator, \\\n and time-reversal operator.\n\"\"\"\n\nimport copy\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom fqe.util import alpha_beta_electrons, vdot\nfrom fqe.fqe_ops import fqe_operator\n\nif TYPE_CHECKING:\n from fqe.wavefunction import Wavefunction\n\n\nclass NumberOperator(fqe_operator.FqeOperator):\n \"\"\"The number operator.\"\"\"\n\n def contract(self, brastate: \"Wavefunction\",\n ketstate: \"Wavefunction\") -> complex:\n \"\"\"Given two wavefunctions, generate the expectation value of the\n operator according to its representation.\n\n Args:\n brastate (Wavefunction): Wavefunction on the bra side.\n\n ketstate (Wavefunction): Wavefunction on the ket side.\n \"\"\"\n out = copy.deepcopy(ketstate)\n for _, sector in out._civec.items():\n sector.scale(sector.nalpha() + sector.nbeta())\n return vdot(brastate, out)\n\n def representation(self) -> str:\n \"\"\"\n Returns:\n (str): the representation of the number operator, which is 'N'.\n \"\"\"\n return \"N\"\n\n def rank(self) -> int:\n \"\"\"\n Returns:\n (int): the rank of the number operator. Always 2\n \"\"\"\n return 2\n\n\nclass S2Operator(fqe_operator.FqeOperator):\n r\"\"\"The :math:`S^2` operator.\"\"\"\n\n def contract(self, brastate: \"Wavefunction\",\n ketstate: \"Wavefunction\") -> complex:\n \"\"\"Given two wavefunctions, generate the expectation value of the\n operator according to its representation.\n\n Args:\n brastate (Wavefunction): Wavefunction on the bra side.\n\n ketstate (Wavefunction): Wavefunction on the ket side.\n \"\"\"\n out = copy.deepcopy(ketstate)\n for _, sector in out._civec.items():\n sector.apply_inplace_s2()\n return vdot(brastate, out)\n\n def representation(self) -> str:\n \"\"\"\n Returns:\n (str): the representation of the operator, which is s_2\n \"\"\"\n return \"s_2\"\n\n def rank(self) -> int:\n \"\"\"\n Returns:\n (int): rank of the operator. Always 2\n \"\"\"\n return 2\n\n\nclass SzOperator(fqe_operator.FqeOperator):\n r\"\"\"The :math:`S_z` operator.\"\"\"\n\n def contract(self, brastate: \"Wavefunction\",\n ketstate: \"Wavefunction\") -> complex:\n \"\"\"Given two wavefunctions, generate the expectation value of the\n operator according to its representation.\n\n Args:\n brastate (Wavefunction): Wavefunction on the bra side.\n\n ketstate (Wavefunction): Wavefunction on the ket side.\n \"\"\"\n out = copy.deepcopy(ketstate)\n for _, sector in out._civec.items():\n sector.scale((sector.nalpha() - sector.nbeta()) * 0.5)\n return vdot(brastate, out)\n\n def representation(self) -> str:\n \"\"\"\n Returns:\n (str): the representation of the :math:`S_z` operator, \\\n which is \"s_z\"\n \"\"\"\n return \"s_z\"\n\n def rank(self) -> int:\n \"\"\"\n Returns:\n (int): the rank of the :math:`S_z` operator. Always 2\n \"\"\"\n return 2\n\n\nclass TimeReversalOp(fqe_operator.FqeOperator):\n \"\"\"The time-reversal operator.\n\n The program assumes the Kramers-paired storage for the wavefunction.\n \"\"\"\n\n def contract(self, brastate: \"Wavefunction\",\n ketstate: \"Wavefunction\") -> complex:\n \"\"\"Given two wavefunctions, generate the expectation value of the\n operator according to its representation.\n\n Args:\n brastate (Wavefunction): Wavefunction on the bra side.\n\n ketstate (Wavefunction): Wavefunction on the ket side.\n \"\"\"\n out = copy.deepcopy(ketstate)\n for (nele, nab), sector in out._civec.items():\n nalpha, nbeta = alpha_beta_electrons(nele, nab)\n if nalpha < nbeta:\n if not (nele, nbeta - nalpha) in out._civec.keys():\n raise ValueError(\n \"The wavefunction space is not closed under \"\n \"time reversal.\")\n sector2 = out._civec[(nele, nbeta - nalpha)]\n tmp = np.copy(sector.coeff)\n phase = (-1)**(nbeta * (nalpha + 1))\n phase2 = (-1)**(nalpha * (nbeta + 1))\n sector.coeff = sector2.coeff.T.conj() * phase2\n sector2.coeff = tmp.T.conj() * phase\n elif nalpha > nbeta:\n if not (nele, nbeta - nalpha) in out._civec.keys():\n raise ValueError(\n \"The wavefunction space is not closed under \"\n \"time reversal.\")\n elif nalpha == nbeta:\n sector.coeff = sector.coeff.T.conj()\n return vdot(brastate, out)\n\n def representation(self) -> str:\n \"\"\"\n Returns:\n (str): the representation of the operator, which is T\n \"\"\"\n return \"T\"\n\n def rank(self) -> int:\n \"\"\"\n Returns:\n (int): the rank of the operator. Always 2\n \"\"\"\n return 2\n","sub_path":"src/fqe/fqe_ops/fqe_ops.py","file_name":"fqe_ops.py","file_ext":"py","file_size_in_byte":5806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"62449320","text":"\"\"\"Server URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls import url\n\n# from django.contrib import admin\nfrom django.urls import include, path\nfrom drf_spectacular.views import (\n SpectacularAPIView,\n SpectacularRedocView,\n SpectacularSwaggerView,\n)\n\nfrom backend.Profile.views import TokenView\n\nurlpatterns = [\n # path(\"admin/\", admin.site.urls),\n path(\"api/\", include(\"config.api_routers\")),\n path(\"api/\", include(\"config.api_urls\")),\n path(\"auth/token/\", TokenView.as_view()),\n]\n\n\nif settings.DEBUG:\n import debug_toolbar\n from django.contrib import admin\n\n urlpatterns += [\n url(r\"^__debug__/\", include(debug_toolbar.urls)),\n path(\n \"\",\n SpectacularRedocView.as_view(url_name=\"schema\"),\n name=\"redoc\",\n ),\n path(\"api/schema/\", SpectacularAPIView.as_view(), name=\"schema\"),\n # Optional UI:\n path(\n \"swagger-ui/\",\n SpectacularSwaggerView.as_view(url_name=\"schema\"),\n name=\"swagger-ui\",\n ),\n # path(\"admin/\", admin.site.urls),\n ]\n","sub_path":"src/Server/config/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538411172","text":"from flask import redirect, url_for, render_template, request\nfrom app_files import app, db, bcrypt\nfrom app_files.forms import RegistrationForm, LoginForm, UpdateAccountForm, \\\nOrderStatusForm, NewItemForm\nfrom app_files.db_models import User, Item, Order\nfrom flask_login import login_user, current_user, logout_user, login_required\nimport secrets\nimport os\nfrom PIL import Image\n\ndef save_user_picture(form_picture):\n random_hex = secrets.token_hex(8)\n file_name, file_extension = os.path.splitext(form_picture.filename)\n picture_filename = random_hex + file_extension\n picture_path = os.path.join(app.root_path, \n 'static/images/profile_pictures', \n picture_filename)\n output_size = (125, 125)\n resized_picture = Image.open(form_picture)\n resized_picture.thumbnail(output_size)\n resized_picture.save(picture_path)\n return picture_filename\n\ndef delete_old_picture(user):\n if user.image_file != 'defaultpp.jpg':\n old_picture_path = os.path.join(app.root_path, \n 'static/images/profile_pictures', \n user.image_file)\n os.remove(old_picture_path)\n\ndef save_item_picture(form_picture):\n random_hex = secrets.token_hex(8)\n file_name, file_extension = os.path.splitext(form_picture.filename)\n picture_filename = random_hex + file_extension\n picture_path = os.path.join(app.root_path, \n 'static/images/shop', \n picture_filename)\n output_size = (700, 700)\n resized_picture = Image.open(form_picture)\n resized_picture.thumbnail(output_size)\n resized_picture.save(picture_path)\n return picture_filename\n\n\n\n@app.route('/')\ndef root():\n items_list = Item.query.all()\n return render_template('main.html', items_list=items_list)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('root'))\n\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if (user and bcrypt.check_password_hash(user.password, \n form.password.data)):\n login_user(user, remember=form.remember.data)\n next_page = request.args.get('next')\n if next_page:\n return redirect(next_page)\n else: \n return redirect(url_for('root'))\n else:\n return render_template('login_failed.html')\n return render_template('login.html', form=form)\n\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('root'))\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('root'))\n\n form = RegistrationForm()\n if form.validate_on_submit():\n hashed_password = (bcrypt.generate_password_hash(form.password.data)\n .decode('utf-8'))\n user = User(username=form.username.data, \n email=form.email.data, \n password=hashed_password)\n db.session.add(user)\n db.session.commit()\n return render_template('register_ok.html')\n return render_template('register.html', form=form)\n\n\n@app.route('/account', methods=['GET', 'POST'])\n@login_required\ndef account():\n if current_user.is_admin:\n return redirect(url_for('root'))\n\n form = UpdateAccountForm()\n if form.validate_on_submit():\n if form.picture.data:\n picture_file = save_user_picture(form.picture.data)\n delete_old_picture(current_user)\n current_user.image_file = picture_file\n current_user.username = form.username.data\n current_user.email = form.email.data\n current_user.adress = form.adress.data\n current_user.phone = form.phone.data\n db.session.commit()\n return render_template('updated.html')\n\n elif request.method == 'GET':\n form.username.data = current_user.username\n form.email.data = current_user.email\n form.adress.data = current_user.adress\n form.phone.data = current_user.phone\n\n image_file = url_for('static', filename='images/profile_pictures/' \n + current_user.image_file)\n return render_template('account.html', form=form, image_file=image_file)\n\n\n@app.route('/cart', methods=['GET', 'POST'])\n@login_required\ndef cart():\n if current_user.is_admin:\n return redirect(url_for('root'))\n if request.method == 'POST': # if posted form from main.html\n ordered_item_ID = int(request.form['ordered_item_ID'])\n order = Order(item_ID=ordered_item_ID, user_ID=current_user.id)\n db.session.add(order)\n db.session.commit()\n user_orders_list = (db.session.query(Order, Item)\n .filter(Order.user_ID==current_user.id)\n .join(Item, Order.item_ID==Item.id))\n return render_template('cart.html', user_orders_list=user_orders_list)\n\n\n@app.route('/shopmanagement', methods=['GET', 'POST'])\n@login_required\ndef shopmanagement():\n if current_user.is_admin:\n # try - because there are 2 forms in one template\n try:\n # deletes item from the database by form from itmes table\n deleted_item_ID = int(request.form['deleted_item_ID'])\n deleted_item = Item.query.filter_by(id=deleted_item_ID).first()\n picture_path = os.path.join(app.root_path, 'static/images/shop', \n deleted_item.item_image)\n os.remove(picture_path)\n db.session.delete(deleted_item)\n db.session.commit()\n return redirect(url_for('shopmanagement'))\n except:\n # adds a new item\n form = NewItemForm()\n if form.validate_on_submit():\n new_item_image = save_item_picture(form.item_image.data)\n item = Item(item_name=form.item_name.data, \n item_main_description=(form\n .item_main_description\n .data), \n item_points_description=(form\n .item_points_description\n .data), \n item_image=new_item_image, \n item_price=form.item_price.data)\n db.session.add(item)\n db.session.commit()\n return redirect(url_for('shopmanagement'))\n items_list = Item.query.all()\n return render_template('shopmanagement.html', \n items_list=items_list, form=form)\n else:\n return redirect(url_for('root'))\n\n\n@app.route('/orders', methods=['GET', 'POST'])\n@login_required\ndef orders():\n if current_user.is_admin:\n form = OrderStatusForm()\n if form.validate_on_submit():\n order_ID = form.order_ID.data\n order = db.session.query(Order).filter(Order.id==order_ID).first()\n order.status = form.status.data\n db.session.commit()\n orders_list = (db.session.query(Order, Item, User)\n .join(Item, Order.item_ID==Item.id)\n .join(User, Order.user_ID==User.id).all())\n return render_template('orders.html', \n orders_list=orders_list, form=form)\n else:\n return redirect(url_for('root'))","sub_path":"app_files/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":7664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"587637783","text":"from __future__ import print_function\n\nfrom builtins import str\nfrom os import listdir\nfrom os.path import isfile, join\nfrom webwhatsapi import WhatsAPIDriver\nfrom webwhatsapi.objects.message import NotificationMessage\nfrom webwhatsapi.objects import message as MESSAGE\n\nfrom kafka_functions import KafkaManager\nfrom kafka import KafkaConsumer\nfrom kafka import KafkaProducer\n\nimport time\nimport random\nimport datetime\nimport os\nimport pathlib\nimport argparse\nimport json\nimport phonenumbers\nimport hash_functions\n\n\ndef smart_str(x):\n if isinstance(x, int) or isinstance(x, float):\n return str(x, \"utf-8\")\n return x\n\n\ndef get_messages_by_group(driver):\n msg_list = driver.get_unread(include_me=False, include_notifications=True, use_unread_count=False)\n return msg_list\n\n\ndef convert_data_from_timestamp(time_message):\n time_obj = datetime.datetime.fromtimestamp(time_message)\n return time_obj\n\n\nclass WhatsappCollector():\n \"\"\"\n Classe que encapsula o coletor de grupos do Whatsapp. Possui\n o método principal que realiza a leitura da entrada e faz a\n coleta das mensagens, mídias e notificações.\n\n Atributos\n -----------\n collection_mode : str\n Modo de coleção a ser utilizado (\"period\" ou \"unread\" ou \n \"continuous\").\n start_date : str\n Data de início do período de coleta (Modo \"period\").\n end_date : str\n Data de término do período de coleta (Modo \"period\").\n group_blacklist : list\n Lista de ids de grupos que devem ser excluídos da coleta.\n user_blacklist : list\n Lista de ids de usuários que devem ser excluídos da coleta.\n collect_messages : bool\n Se mensagens de texto devem ser coletadas durante a execução.\n collect_audios : bool\n Se áudios devem ser coletadas durante a execução.\n collect_videos : bool\n Se vídeos devem ser coletadas durante a execução.\n collect_images : bool\n Se imagens devem ser coletadas durante a execução.\n collect_notifications : bool\n Se notificações devem ser coletadas durante a execução.\n process_audio_hashes : bool\n Se hashes de áudios devem ser calculados durante a execução.\n process_image_hashes : bool\n Se hashes de imagens devem ser calculados durante a execução.\n process_video_hashes : bool\n Se hashes de vídeos devem ser calculados durante a execução.\n\n\n Métodos\n -----------\n Faz a coleta das mensagens de grupos de Whatsapp de acordo\n com os parâmetros fornecidos na criação do objeto de coleta.\n\n Parâmetros\n ------------\n profile_path : str\n Caminho para um profile alternativo do navegador\n utilizado na coleta.\n\n \"\"\"\n def __init__(self, args):\n \"\"\"\n Inicializa o objeto\n\n Parâmetros\n ------------\n args : argparse.Namespace()\n Objeto com atributos que contém os argumentos de linha de\n comando fornecidos.\n \"\"\"\n args_dict = vars(args)\n\n if args.json:\n with open(args.json) as json_file:\n json_args = json.load(json_file)\n args_dict.update(json_args)\n elif args.json_string:\n json_args = json.loads(args.json_string)\n args_dict.update(json_args)\n\n if (args_dict[\"collection_mode\"] not in\n ['continuous', 'period', 'unread']):\n print('Collection mode invalid <%s>!! Using instead' %\n (args_dict[\"collection_mode\"]))\n args_dict[\"collection_mode\"] = 'continuous'\n if args_dict[\"write_mode\"] not in ['both', 'day', 'file', 'group', 'kafka']:\n print('Save mode invalid <%s>!! Using instead' % (\n args_dict[\"write_mode\"]))\n args_dict[\"write_mode\"] = 'kafka'\n \n \n \n self.collection_mode = args_dict[\"collection_mode\"]\n self.start_date = args_dict[\"start_date\"]\n self.end_date = args_dict[\"end_date\"]\n self.write_mode = args_dict[\"write_mode\"]\n self.group_blacklist = args_dict[\"group_blacklist\"]\n self.user_blacklist = args_dict[\"user_blacklist\"]\n self.group_whitelist = args_dict[\"group_whitelist\"]\n self.user_whitelist = args_dict[\"user_whitelist\"]\n self.collect_messages = args_dict[\"collect_messages\"]\n self.collect_audios = args_dict[\"collect_audios\"]\n self.collect_videos = args_dict[\"collect_videos\"]\n self.collect_images = args_dict[\"collect_images\"]\n self.collect_notifications = args_dict[\"collect_notifications\"]\n self.process_audio_hashes = args_dict[\"process_audio_hashes\"]\n self.process_image_hashes = args_dict[\"process_image_hashes\"]\n self.process_video_hashes = args_dict[\"process_video_hashes\"]\n self.profile = args_dict[\"profile\"]\n self.data_path = '/data/'\n self.datalake = args_dict[\"datalake\"]\n self.bootstrap_servers = args_dict[\"bootstrap_servers\"]\n\n \n if self.write_mode == 'kafka' or self.write_mode == 'both':\n self.save_file = False\n self.save_kafka = True\n self.kafka = KafkaManager()\n if len(args_dict[\"bootstrap_servers\"]) > 1:\n self.bootstrap_servers = args_dict[\"bootstrap_servers\"]\n self.kafka.update_servers(self.bootstrap_servers )\n if len(args_dict[\"bootstrap_servers\"]) == 1:\n self.bootstrap_servers = args_dict[\"bootstrap_servers\"][0].split(',')\n self.kafka.update_servers(self.bootstrap_servers )\n self.producer = self.kafka.connect_kafka_producer()\n else:\n self.save_file = True\n self.save_kafka = False\n \n if self.write_mode == 'both':\n self.save_file = True\n self.save_kafka = True\n \n \n def _process_string(self, string):\n \"\"\"\n Processa strings que irão pra saída do coletor, removendo quebras\n de linha, tabulações e espaços extras.\n\n Parâmetros\n ------------\n string : str\n String a ser processada.\n \"\"\"\n string = string.strip()\n string = string.replace('\\r', '')\n string = string.replace('\\n', ' ')\n string = string.replace('\\t', ' ')\n string = smart_str(string)\n\n return string\n\n def _generate_unique_filename(self, message, filename):\n \"\"\"\n Gera um novo nome único para o arquivo de mídia contido na mensagem.\n\n Parâmetros\n ------------\n message : webwhatsapi.Message()\n Objeto de messagem que contem uma mídia.\n filename : str\n Nome original do arquivo.\n \"\"\"\n date = self._get_date_from_message(message).split(' ')[0]\n mediaID = message.id.split('.')[-1]\n filename = '%s/%s_%s_%s.%s' % (date, message.type, filename.split('.')[0],\n mediaID, filename.split('.')[-1])\n return filename\n\n def _get_image_from_message(self, message, path='/data/image/'):\n \"\"\"\n Baixa a imagem contida na mensagem coletada, caso ela exista.\n\n Parâmetros\n ------------\n message : webwhatsapi.Message()\n Objeto de messagem que contem uma imagem que pode ser baixada.\n path : str\n Caminho para a pasta onde o arquivo será salvo.\n \"\"\"\n if message.type == 'image':\n date = self._get_date_from_message(message).split(' ')[0]\n \n filename = self._generate_unique_filename(\n message, message.filename)\n message.filename = filename\n \n out_folder = join(path, filename.split('/')[0])\n pathlib.Path(out_folder).mkdir(parents=True, exist_ok=True)\n if not os.path.isfile(path+filename):\n message.save_media(path, force_download=True)\n\n def _get_video_from_message(self, message, path='/data/video/'):\n \"\"\"\n Baixa o vídeo contido na mensagem coletada, caso ele exista.\n\n Parâmetros\n ------------\n message : webwhatsapi.Message()\n Objeto de messagem que contem um vídeo que pode ser baixado.\n path : str\n Caminho para a pasta onde o arquivo será salvo.\n \"\"\"\n if message.type == 'video':\n date = self._get_date_from_message(message).split(' ')[0]\n \n filename = self._generate_unique_filename(\n message, message.filename)\n message.filename = filename\n \n out_folder = join(path, filename.split('/')[0])\n pathlib.Path(out_folder).mkdir(parents=True, exist_ok=True)\n if not os.path.isfile(path+filename):\n message.save_media(path, force_download=True)\n\n def _get_audio_from_message(self, message, path='/data/audio/'):\n \"\"\"\n Baixa o áudio contido na mensagem coletada, caso ele exista.\n\n Parâmetros\n ------------\n message : webwhatsapi.Message()\n Objeto de messagem que contem um áudio que pode ser baixado.\n path : str\n Caminho para a pasta onde o arquivo será salvo.\n \"\"\"\n if message.type == 'audio' or message.type == 'ptt':\n date = self._get_date_from_message(message).split(' ')[0]\n \n filename = self._generate_unique_filename(\n message, message.filename)\n message.filename = filename\n \n out_folder = join(path, filename.split('/')[0])\n pathlib.Path(out_folder).mkdir(parents=True, exist_ok=True)\n if not os.path.isfile(path+filename):\n message.save_media(path, force_download=True)\n\n def _get_date_from_message(self, message):\n \"\"\"\n Retorna a data em que a mensagem foi enviada.\n\n Parâmetros\n ------------\n message : webwhatsapi.Message()\n Objeto de mensagem.\n \"\"\"\n t = str(message)\n index = t.find(' at ') + 4\n index2 = index + 10\n date = t[index:index2]\n return date\n\n def _get_group_from_message(self, message):\n \"\"\"\n Retorna o nome do grupo em que a mensagem foi enviada.\n\n Parâmetros\n ------------\n message : webwhatsapi.Message()\n Objeto de mensagem.\n \"\"\"\n t = str(message)\n index = t.find('Group chat -') + 12\n group = t[index:].split(':')[0]\n return group\n\n def _get_load_notifications(self, path='/data/notificacoes/'):\n \"\"\"\n Carrega e retorna um dicionário contendo os ids e datas das\n notificações já coletadas.\n\n Parâmetros\n ------------\n path : str\n Caminho para pasta contendo arquivos de notificações.\n \"\"\"\n messagesIDs = dict()\n allfiles = [f for f in listdir(path) if isfile(join(path, f))]\n for f in allfiles:\n ID = f.split('.')[0].split('@')[0]\n messagesIDs[ID] = set()\n with open(path+f, 'r') as fin:\n for line in fin:\n data = json.loads(line.strip())\n mid = data['identificador']\n messagesIDs[ID].add(mid)\n\n return messagesIDs\n\n def _get_load_messages(self, path='/data/mids/'):\n \"\"\"\n Carrega e retorna um dicionário contendo os ids e datas das\n mensagens já coletadas.\n\n Parâmetros\n ------------\n path : str\n Caminho para pasta contendo arquivos de mensagens.\n \"\"\"\n messagesIDs = dict()\n allfiles = [f for f in listdir(path) if isfile(join(path, f))]\n for f in allfiles:\n ID = f.split('.')[0].split('@')[0]\n messagesIDs[ID] = dict()\n messagesIDs[ID]['messages'] = set()\n maxDate = '2000-01-01'\n with open(path+f, 'r') as fin:\n for line in fin:\n tokens = line.strip().split('\\t')\n date = tokens[2].split(' ')[0]\n if date >= maxDate:\n maxDate = date\n messagesIDs[ID]['messages'].add(tokens[0])\n messagesIDs[ID]['date'] = date\n return messagesIDs\n\n def _is_notification(self, messageID):\n \"\"\"\n Verifica se uma mensagem é do tipo notificação a partir do seu id.\n\n Parâmetros\n ------------\n messageID : str\n Id de uma mensagem coletada.\n \"\"\"\n if messageID.find('true') < 0:\n return False\n else:\n return True\n \n \n def check_user(self, message):\n check_user_w = False\n check_user_b = False\n if len(self.user_whitelist) > 0: check_user_w = True\n if len(self.user_blacklist) > 0: check_user_b = True\n \n sender = ''\n id = message.sender.id\n sender = message.sender.id\n sender = sender.replace(' ', '').strip()\n sender = sender.split('@')[0]\n sender = ('+'+sender)\n\n if check_user_w and (id not in self.user_whitelist):\n if check_user_w and (sender not in self.user_whitelist):\n return False\n \n if check_user_b and (id in self.user_blacklist or sender in self.user_blacklist):\n print('User', sender, 'in user blacklist!!! Next message')\n return False\n \n \n return True\n \n def _save_notification_(self, message, gid, path='/data/notificacoes/'):\n \"\"\"\n Escreve em formato json a notificação contida na mensagem no arquivo\n referente ao grupo em que ela foi enviada. Caso o arquivo do grupo\n ainda não exista, ele será criado.\n\n Parâmetros\n ------------\n message : webwhatsapi.Message()\n Objeto da mensagem coletada.\n gid : str\n Id do grupo em que a mensagem foi enviada.\n path : str\n Caminho da pasta em que os arquivos de notificações serão\n escritos.\n \"\"\"\n if(isinstance(message, NotificationMessage)):\n readable = {\n 'call_log': {\n 'miss': \"Missed Call\",\n },\n 'e2e_notification': {\n 'encrypt': \"Messages now Encrypted\"\n },\n 'gp2': {\n 'invite': \"Joined an invite link\",\n 'create': \"Created group\",\n 'add': \"Added to group\",\n 'remove': \"Removed from group\",\n 'leave': \"Left the group\",\n 'description': \"Changed the group description. Click to view.\"\n }\n }\n msgtype = message.type\n msgtype = message._js_obj['type']\n subtype = message._js_obj['subtype']\n timestamp = message._js_obj['timestamp']\n name = message._js_obj['chat']['contact']['name']\n name = self._process_string(name)\n date = datetime.datetime.fromtimestamp(int(timestamp)).strftime(\n '%Y-%m-%d %H:%M:%S')\n\n try:\n sender_user = message._js_obj['sender']['id']['user']\n except Exception:\n sender_user = 'No_sender'\n\n try:\n from_user = message._js_obj['from']['user']\n except Exception:\n from_user = 'No_user'\n\n try:\n alert = readable[message.type][message.subtype]\n except KeyError as e:\n alert = 'Other'\n\n notification = dict()\n\n notification['identificador'] = str(message.id)\n notification['mensagem_id'] = str(message.id)\n notification['grupo_id'] = gid\n notification['acao'] = msgtype\n notification['notification_type'] = subtype\n notification['timestamp'] = timestamp\n notification['criado_em'] = date\n notification['enviado_por'] = sender_user\n notification['contact'] = name\n notification['received_by'] = from_user\n\n n_date = notification['criado_em'].split(' ')[0]\n all_notification_filename = self.data_path+'all_notificacoes/all_notificacoes_%s.json' % \\\n (n_date)\n\n if message._js_obj['recipients']:\n for item in message._js_obj['recipients']:\n try:\n recipient_user = item['user']\n except Exception:\n recipient_user = 'No_user'\n notification['recipient'] = recipient_user\n finalstring = '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s' % \\\n (str(message.id), gid, msgtype, subtype, timestamp,\n date, name, sender_user, recipient_user, from_user)\n print(finalstring)\n \n if self.save_kafka:\n topic = self.kafka.get_topic('whatsapp' , 'notificacao')\n json_dump_object = json.dumps(notification)\n self.kafka.publish_kafka_message(self.producer, topic, 'raw', json_dump_object)\n \n if self.save_file:\n filename = '%snotificacoes_%s.json' % (path, gid)\n with open(filename, 'a') as json_file:\n json.dump(notification, json_file)\n print('', file=json_file)\n with open(all_notification_filename, 'a') as json_file:\n json.dump(notification, json_file)\n print('', file=json_file)\n\n else:\n try:\n recipient_user = message._js_obj['recipients'][0]['user']\n except Exception:\n recipient_user = 'No_user'\n notification['recipient'] = recipient_user\n finalstring = '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s' % \\\n (str(message.id), gid, msgtype, subtype, timestamp, date,\n name, sender_user, recipient_user, from_user)\n print(finalstring)\n \n if self.save_kafka:\n topic = self.kafka.get_topic('whatsapp' , 'notificacao')\n json_dump_object = json.dumps(notification)\n self.kafka.publish_kafka_message(self.producer, topic, 'raw', json_dump_object)\n \n if True:\n filename = '%snotificacoes_%s.json' % (path, gid)\n with open(filename, 'a') as json_file:\n json.dump(notification, json_file)\n print('', file=json_file)\n with open(all_notification_filename, 'a') as json_file:\n json.dump(notification, json_file)\n print('', file=json_file)\n\n return notification\n\n def _save_message(self, message, group_name, chat_id, msg_id, file_name,\n msg_id_path='/data/mensagens_grupo/'):\n \"\"\"\n Escreve em formato json a mensagem coletada no arquivo\n referente ao grupo em que ela foi enviada. Caso o arquivo do grupo\n ainda não exista, ele será criado.\n\n Parâmetros\n ------------\n message : webwhatsapi.Message()\n Objeto da mensagem coletada.\n group_name : str\n Nome do grupo em que a mensagem foi enviada.\n chat_id : str\n Id do grupo em que a mensagem foi enviada.\n msg_id : str\n Id da mensagem coletada.\n file_name : str\n Nome do arquivo da mídia possivelmente contida na mensagem.\n msg_id_path : str\n Caminho da pasta em que os arquivos de mensagens por grupo\n serão escritos.\n \"\"\"\n\n if not message.sender:\n return\n item = dict()\n sender = message.sender.id\n sender = sender.replace(' ', '').strip()\n sender = sender.split('@')[0]\n sender = ('+'+sender)\n\n try:\n phone = phonenumbers.parse(sender)\n except Exception:\n phone = phonenumbers.parse('+'+sender)\n country_code = phone.country_code\n country = phonenumbers.phonenumberutil.region_code_for_country_code(\n country_code)\n\n mid = smart_str(msg_id)\n gid = smart_str(chat_id)\n\n try:\n content = message.content\n content = smart_str(content)\n content = smart_str(content.replace('\\n', ' '))\n except Exception:\n content = ''\n\n t = str(message)\n index = t.find(' at ') + 4\n index2 = index + 19\n date = str(t[index:index2])\n date = smart_str(date.replace(' ', '\\t').strip())\n\n filename = ''\n mediatype = 'application/json'\n if (isinstance(message, MESSAGE.MediaMessage) or\n isinstance(message, MESSAGE.MMSMessage)):\n mediatype = smart_str(message.type)\n try:\n filename = message.filename\n content = '<'+filename+'>'\n except Exception:\n filename = ''\n if hasattr(message, 'caption'):\n content = smart_str(message.caption)\n\n if 'text' in mediatype:\n mediatype = 'application/json'\n phash = ''\n checksum = ''\n\n if ((mediatype == 'image' and self.process_image_hashes) or\n (mediatype == 'video' and self.process_video_hashes) or\n (mediatype == 'audio' and self.process_audio_hashes)):\n dir = \"\"\n if mediatype == 'image':\n dir = self.data_path+\"image\"\n if mediatype == 'video':\n dir = self.data_path+\"video\"\n if mediatype == 'audio':\n dir = self.data_path+\"audio\"\n\n try:\n checksum = hash_functions.get_hash_from_method(os.path.join(\n dir, message.filename), \"checksum\")\n except Exception:\n print(\"Couldn't process checksum for file %s.\" % (\n message.filename))\n\n if mediatype == 'image':\n try:\n phash = hash_functions.get_hash_from_method(os.path.join(\n dir, message.filename), \"phash\")\n except Exception:\n print(\"Couldn't process phash for file %s.\" % (\n message.filename))\n\n item['mensagem_id'] = mid\n item['identificador'] = mid\n item['grupo_id'] = gid\n item['titulo'] = group_name\n item['pais'] = country\n item['enviado_por'] = smart_str(sender)\n item['criado_em'] = smart_str(date)\n item['tipo'] = mediatype\n item['arquivo'] = smart_str(filename)\n item['datalake'] = join(self.data_path, smart_str(filename))\n item['texto'] = smart_str(content)\n if (mediatype == 'video' or mediatype == 'image'\n or mediatype == 'audio'):\n item['checksum'] = checksum\n if mediatype == 'image':\n item['phash'] = phash\n\n messageLine = '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%r\\t%s\\t%s' % \\\n (mid, gid, group_name, country, smart_str(sender),\n smart_str(date), mediatype, checksum, smart_str(filename),\n self._process_string(content))\n print(messageLine)\n\n # Save message on kafka\n \n if self.save_kafka:\n topic = self.kafka.get_topic('whatsapp' , 'mensagem')\n json_dump_object = json.dumps(item)\n self.kafka.publish_kafka_message(self.producer, topic, 'raw', json_dump_object)\n \n if self.save_file:\n # Save message on group ID file\n if self.write_mode == 'group' or self.write_mode == 'file' or self.write_mode == 'both':\n message_group_filename = '%smensagens_grupo_%s.json' % (msg_id_path, gid)\n with open(message_group_filename, 'a') as json_file:\n json.dump(item, json_file)\n print('', file=json_file)\n\n if self.write_mode == 'day' or self.write_mode == 'file' or self.write_mode == 'both':\n message_day_filename = file_name\n\n # Save message on file for all messages of the day\n with open(message_day_filename, 'a') as json_file:\n json.dump(item, json_file)\n print('', file=json_file)\n \n \n # Always save mid reference for future checks\n reference_mid_filename = '/data/mids/%s.txt' % (gid)\n with open(reference_mid_filename, 'a') as fmid:\n messageLine = '%s\\t%s\\t%s' % (mid, gid, smart_str(date))\n print(messageLine, file=fmid)\n\n return item\n\n def run(self, profile_path=\"/data/firefox_cache\"):\n \n profile_path = self.profile\n \"\"\"\n Faz a coleta das mensagens de grupos de Whatsapp de acordo\n com os parâmetros fornecidos na criação do objeto de coleta.\n\n Parâmetros\n ------------\n profile_path : str\n Caminho para um profile alternativo do navegador\n utilizado na coleta.\n \"\"\"\n if not os.path.exists(self.data_path):\n os.makedirs(self.data_path)\n \n if not os.path.exists(profile_path):\n os.makedirs(profile_path)\n driver = WhatsAPIDriver(loadstyles=True, profile=profile_path,\n client=\"remote\",\n command_executor=os.environ[\"SELENIUM\"])\n\n pathlib.Path(self.data_path+\"mensagens\").mkdir(parents=True, exist_ok=True)\n pathlib.Path(self.data_path+\"image\").mkdir(parents=True, exist_ok=True)\n pathlib.Path(self.data_path+\"audio\").mkdir(parents=True, exist_ok=True)\n pathlib.Path(self.data_path+\"video\").mkdir(parents=True, exist_ok=True)\n pathlib.Path(self.data_path+\"mensagens_grupo\").mkdir(parents=True, exist_ok=True)\n pathlib.Path(self.data_path+\"notificacoes\").mkdir(parents=True, exist_ok=True)\n pathlib.Path(self.data_path+\"all_notificacoes\").mkdir(parents=True, exist_ok=True)\n pathlib.Path(\"/data/mids\").mkdir(parents=True, exist_ok=True)\n\n min_date = self.start_date\n max_date = self.end_date\n include_notf = self.collect_notifications\n looping = True\n if (self.collection_mode == 'period') and (min_date < '2020-01-01'):\n raise Exception(\"Can't start collection without a start and end\"\n \" date.\")\n \n check_group_w = False\n check_group_b = False\n if len(self.group_whitelist) > 0: check_group_w = True\n if len(self.group_blacklist) > 0: check_group_b = True\n \n while looping:\n\n if self.collection_mode == 'continuous':\n looping = True\n else:\n looping = False\n\n try:\n print(\"Waiting for WhatsApp Web Login\")\n driver.wait_for_login()\n print(\"Saving session\")\n driver.save_firefox_profile(remove_old=False)\n print(\"Bot started\")\n\n print('>>>>>>>>>>> Loading previous saved Messages')\n messagesID = self._get_load_messages()\n notificationsID = self._get_load_notifications()\n\n today_date = datetime.date.today().strftime(\"%Y-%m-%d\")\n date_format = \"%Y-%m-%d\"\n file_name = self.data_path+\"mensagens/mensagens_\" + today_date + \".json\"\n start_date = min_date\n\n print('>>>>>>>>>>>>Getting Groups Messages...', end=' ')\n chats = driver.get_all_chats()\n count = 0\n all_chats = list(chats)\n\n print(' DONE! %d chats loaded!' % (len(all_chats)))\n random.shuffle(all_chats)\n\n for chat in (all_chats):\n # Does not collect direct messages, only group chats\n if not chat._js_obj['isGroup']:\n continue\n\n gid = chat.id\n gid = gid.split('@')[0]\n s_name = self._process_string(chat.name)\n\n if check_group_w and (gid not in self.group_whitelist):\n if check_group_w and (s_name not in self.group_whitelist):\n continue\n if check_group_b and (gid in self.group_blacklist or s_name in self.group_blacklist):\n print('Group',gid, str(s_name), 'in blacklist and will not be collected! Next group')\n continue\n \n # Skip group if it is on blacklist (can be name or groupID)\n if (s_name in self.group_blacklist or\n gid in self.group_blacklist):\n continue\n\n # PRINT CHAT INFORMATION\n members = chat._js_obj['groupMetadata']['participants']\n timestamp = gid.split('-')[-1]\n date = convert_data_from_timestamp(float(timestamp))\n str_date = date.strftime('%Y-%m-%d %H:%M:%S')\n\n chat_print = \"\".format(\n name=s_name, id=gid, participants=len(members),\n time=str_date)\n print('>>>>>Loading messages from', chat_print)\n\n if gid not in messagesID:\n messagesID[gid] = dict()\n messagesID[gid]['messages'] = set()\n messagesID[gid]['date'] = '2000-01-01'\n\n # PROCESS PREVIOUS LOADED MESSAGES ID AND LAST DATE\n if self.collection_mode == 'continuous':\n if messagesID[gid]['date'] > max_date:\n continue\n if messagesID[gid]['date'] > min_date:\n start_date = messagesID[gid]['date']\n till_date = datetime.datetime.strptime(start_date,\n date_format)\n else:\n start_date = min_date\n till_date = datetime.datetime.strptime(start_date,\n date_format)\n\n # LOAD MESSAGES FROM WHATSAPP SINCE MIN_DATE\n messages = chat.load_earlier_messages_till(till_date)\n messages = driver.get_all_message_ids_in_chat(\n chat, include_notifications=include_notf)\n\n elif self.collection_mode == 'period':\n till_date = datetime.datetime.strptime(start_date,\n date_format)\n # LOAD MESSAGES FROM WHATSAPP SINCE MIN_DATE\n messages = chat.load_earlier_messages_till(till_date)\n messages = driver.get_all_message_ids_in_chat(\n chat, include_notifications=include_notf)\n\n elif self.collection_mode == 'unread':\n # LOAD UNREAD MESSAGES FROM WHATSAPP\n messages = chat.get_unread_messages(\n include_me=False,\n include_notifications=include_notf)\n\n print('>>>>>Total messages %d' % (len(messages)))\n count += 1\n\n for msg in messages:\n count += 1\n gid = gid.split('@')[0]\n mid = msg\n\n if self._is_notification(mid):\n if gid not in notificationsID.keys():\n notificationsID[gid] = set()\n if mid.strip() in notificationsID[gid]:\n continue\n j = driver.get_message_by_id(mid)\n self._save_notification_(j, gid)\n continue\n\n if mid.strip() in messagesID[gid]['messages']:\n print('Message: %d >>> %s from %s was CHECKED' %\n (count, mid, gid))\n continue\n\n else:\n try:\n j = driver.get_message_by_id(mid)\n except Exception as e:\n print('Error getting a message >>', e)\n continue\n if not j:\n continue\n \n if not self.check_user(j): continue\n \n try:\n date = self._get_date_from_message(j)\n except Exception:\n continue\n\n if (date > max_date) and (self.collection_mode == 'period'):\n break\n if (date < start_date):\n continue\n\n # Update day\n if today_date != date:\n today_date = date\n file_name = self.data_path+\"mensagens/mensagens_\" + today_date + \".json\"\n\n if self.collect_images:\n try:\n self._get_image_from_message(j, self.data_path+\"image\")\n except Exception as ei:\n print('!!!!Error getting image!!!! ', ei)\n\n if self.collect_videos:\n try:\n self._get_video_from_message(j, self.data_path+\"video\")\n except Exception as ev:\n print('!!!!Error getting video!!!! ', ev)\n\n if self.collect_audios:\n try:\n self._get_audio_from_message(j, self.data_path+\"audio\")\n except Exception as ea:\n print('!!!!Error getting audio!!!! ', ea)\n\n if self.collect_messages:\n self._save_message(j, s_name, gid, mid, file_name)\n\n driver.close()\n except Exception as e:\n print(e)\n driver.close()\n raise Exception(e)\n\n if looping:\n print('Waiting code to start again...')\n time.sleep(3600)\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 main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-m\", \"--collection_mode\", type=str,\n help=\"Modo de coleção a ser utilizado (\\'period\\'\"\n \" ou \\'unread\\' ou \\'continuous\\').\",\n default='continuous')\n\n parser.add_argument(\"-p\", \"--profile\", type=str,\n help=\"Perfil de usuario\",\n default='/data/firefox_cache')\n\n parser.add_argument(\"-s\", \"--start_date\", type=str,\n help=\"Data de início do período de coleta (Modo\"\n \" \\'period\\').\", default='2000-01-01')\n\n parser.add_argument(\"-e\", \"--end_date\", type=str,\n help=\"Data de término do período de coleta (Modo\"\n \" \\'period\\').\", default='2999-12-31')\n\n parser.add_argument(\"-w\", \"--write_mode\", type=str,\n help=\"Modo de salvamento das mensagens no arquivos de saída(\\'both\\', \\'day\\', \\'group\\', \\'kafka\\'). \", default='kafka')\n\n parser.add_argument(\"--collect_messages\", type=str2bool,\n help=\"Se mensagens de texto devem ser coletadas\"\n \" durante a execução.\", default=True)\n\n parser.add_argument(\"--collect_audios\", type=str2bool,\n help=\"Se audios devem ser coletadas durante a\"\n \" execução.\", default=True)\n\n parser.add_argument(\"--collect_videos\", type=str2bool,\n help=\"Se videos devem ser coletadas durante a\"\n \" execução.\", default=True)\n\n parser.add_argument(\"--collect_images\", type=str2bool,\n help=\"Se imagens devem ser coletadas durante a\"\n \" execução.\", default=True)\n\n parser.add_argument(\"--collect_notifications\", type=str2bool,\n help=\"Se as notificações devem ser coletadas durante a\"\n \" execução.\", default=True)\n\n parser.add_argument(\"--process_audio_hashes\", type=str2bool,\n help=\"Se hashes de audios devem ser calculados durante\"\n \" a execução.\", default=True)\n\n parser.add_argument(\"--process_image_hashes\", type=str2bool,\n help=\"Se hashes de imagens devem ser calculados\"\n \" durante a execução.\", default=True)\n\n parser.add_argument(\"--process_video_hashes\", type=str2bool,\n help=\"Se hashes de videos devem ser calculados durante\"\n \" a execução.\", default=True)\n\n parser.add_argument(\"--group_blacklist\", nargs=\"+\",\n help=\"Lista de ids de grupos que devem ser excluídos da\"\n \" coleta\", default=[])\n \n parser.add_argument(\"--user_blacklist\", nargs=\"+\",\n help=\"Lista de ids de grupos que devem ser excluídos da\"\n \" coleta\", default=[])\n\n parser.add_argument(\"--group_whitelist\", nargs=\"+\",\n help=\"Lista de ids de grupos que devem ser incluidos da\"\n \" coleta\", default=[])\n\n parser.add_argument(\"--user_whitelist\", nargs=\"+\",\n help=\"Lista de usuarios que devem ser incluidos da\"\n \" coleta\", default=[])\n\n parser.add_argument(\"--datalake\", type=str,\n help=\"Local onde sao salvas as midias\",\n default='/datalake/ufmg/whatsapp/')\n \n parser.add_argument(\"--session_name\", type=str,\n help=\"Nome de secao para autenticacao da API do Telegram. Gera um arquivo .session autorizando a conta a usar a API\",\n default='telegram_api')\n\n parser.add_argument(\"--bootstrap_servers\", nargs=\"+\",\n help=\"Lista de endereço para conexão dos servers Kafka\"\n \" (Brokers)\", default=[])\n\n parser.add_argument(\"-j\", \"--json\", type=str,\n help=\"Caminho para um arquivo json de configuração de \"\n \"execução. Individualmente, as opções presentes no \"\n \"arquivo sobescreveram os argumentos de linha de \"\n \"comando, caso eles sejam fornecidos.\")\n\n parser.add_argument(\"--json_string\", type=str,\n help=\"String contendo um json de configuração de\"\n \" execução. Individualmente, as opções presentes no \"\n \"arquivo sobescreveram os argumentos de linha de \"\n \"comando, caso eles sejam fornecidos.\")\n\n args = parser.parse_args()\n\n try:\n collector = WhatsappCollector(args)\n collector.run( )\n except Exception as e:\n error_time = str(datetime.datetime.now())\n error_msg = str(e).strip()\n with open('/data/log.txt', 'w') as ferror:\n print(\"%s >> Error:\\t%s\" % (error_time, error_msg))\n print(\"%s >> Error:\\t%s\" % (error_time, error_msg), file=ferror)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"whatsapp/source/get_messages.py","file_name":"get_messages.py","file_ext":"py","file_size_in_byte":41592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"156018254","text":"import cv2\nimport numpy as np\nfrom copy import deepcopy\n\ndrawing = False # true if mouse is pressed\nmode = True # if True, draw rectangle. Press 'm' to toggle to curve\nn = 0\nlist1 = []\n# mouse callback function\n\n\ndef draw_circle(event, x, y, flags, param):\n global drawing, mode, n, list1\n if event == cv2.EVENT_LBUTTONDOWN:\n drawing = True\n list1.append((x, y))\n elif event == cv2.EVENT_MOUSEMOVE:\n if drawing:\n if mode:\n list1.append((x, y))\n cv2.circle(img, (x, y), 4, (0, 255, 0), -1)\n cv2.circle(img2, (x, y), 3, (255, 255, 255), -1)\n # cv2.line(img, list1[n], list1[n+1], (0, 255, 0), thickness=5)\n # cv2.line(img2, list1[n], list1[n + 1], (0, 255, 0), thickness=5)\n n = n + 1\n else:\n img[y - 25:y + 25, x - 25:x + 25, :] = img_copy[y - 25:y + 25, x - 25:x + 25, :]\n img2[y - 25:y + 25, x - 25:x + 25, :] = img2_copy[y - 25:y + 25, x - 25:x + 25, :]\n\n elif event == cv2.EVENT_LBUTTONUP:\n drawing = False\n list1 = []\n n = 0\n\n\nimg = cv2.imread(r'D:\\teleguience\\teleguidence\\time\\piuture\\mode.png')\nprint(img.shape)\nimg_copy = deepcopy(img)\nimg2 = np.zeros((1024,1920,3), np.uint8)\nimg2_copy = deepcopy(img2)\n# cv2.namedWindow('image_cp',cv2.WINDOW_NORMAL)\n# cv2.resizeWindow('image_cp',640,480)\ncv2.namedWindow('image',cv2.WINDOW_NORMAL)\ncv2.resizeWindow('image',640,480)\ncv2.namedWindow('image2',cv2.WINDOW_NORMAL)\ncv2.resizeWindow('image2',640,480)\n# cv2.namedWindow('image2_cp',cv2.WINDOW_NORMAL)\n# cv2.resizeWindow('image2_cp',640,480)\ncv2.setMouseCallback('image',draw_circle)\n\n\nwhile(1):\n cv2.imshow('image',img)\n # cv2.imshow('image_cp',img_copy)\n cv2.imshow('image2',img2)\n # cv2.imshow('image2_cp', img2)\n k = cv2.waitKey(1) & 0xFF\n if k == ord('m'):\n mode = not mode\n elif k == ord('q'):\n break\ncv2.destroyAllWindows()","sub_path":"test/mian-3.py","file_name":"mian-3.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513968913","text":"class MiningTopicalTerms ( object ):\n \"\"\"\n :param documents: Collection of documents that will be analysed. This documents must\n be in raw format to normalize them in the 'find_topics' method.\n \"\"\"\n def __init__ ( self, documents ):\n self.documents = documents\n\n def find_potential_terms ( self ):\n \"\"\"\n This method will calculate which words (terms) are the most potential to be Topics\n using the 'tf_idf' method in InformationRetrieval class. With the value of tf-idf\n will be easy to know the importance of a term in a document.\n \"\"\"\n from ParadigmaticRelation import InformationRetrieval\n from RawText import ProcessRawText\n\n terms = [ ]\n prt = ProcessRawText ( plane_text = \"\" )\n prt.load_lemmatization_file ( language = \"es\", encode = \"latin-1\" )\n prt.load_stopwords_file ( language = \"es\", encode = \"latin-1\" )\n for document in self.documents:\n prt.plane_text = document\n prt.html_parser ( )\n prt.remove_special_characters ( )\n text_tokenized = prt.tokenize_text ( )\n text_tokenized = prt.word_lemmatize ( text_tokenized = text_tokenized )\n text_tokenized = prt.remove_stopwords ( text_tokenized = text_tokenized )\n vocabulary = prt.create_vocabulary ( text_tokenized )\n ir = InformationRetrieval ( documents = self.documents, vocabulary = vocabulary )\n terms += ir.tf_idf ( )\n terms.sort ( key = lambda x : x [ 1 ] )\n return terms\n\n\n def html_doc2articles ( self, html_tag = \"\" ):\n \"\"\"\n If we have as input a list and its only element it's a single html document then,\n we can split this document into articles based in an specific html tag. This method\n will return a list of lists were each element is an article of the html document.\n Also will modify the attribute self.documents since now we don't want to work with\n several documents, indeed we are working know with articles of the entry document.\n\n :param html_tag: Flag that will help the program to split the html document.\n \"\"\"\n articles, temp = [ ], \"\"\n for document in self.documents:\n for term in document.split ( ):\n if ( term == \"\" and temp != \"\" ):\n articles.append ( temp )\n temp = \"\"\n continue;\n temp += \" \" + term\n articles.append ( temp )\n self.documents = articles\n return self.documents\n\n\nclass TopicsCoverage ( object ):\n \"\"\"\n To find the topic coverage in an article, document or a corpus etc. It's necessary to define\n a collection of 'n' texts: C = {d1, d2, ..., dn}, then, parse each text in C to obtain candidate\n terms (e.g., term = word) to be topics by desingning a scoring function to measure how good each\n term is as a topic. Finally, pick 'k' terms with the highest score: k-topics = {Θ1, Θ2, ..., Θk}.\n\n :param documents: Collection of documents, texts or articles, to find the topic coverage.\n \"\"\"\n def __init__ ( self, plane_text = \"\" ):\n self.plane_text = plane_text\n\n # Prototype only: This method isn't very exact.\n def term_as_topic ( self, document, topics ):\n \"\"\"\n This method finds the probability of document/article 'di' covering topic 'Θj'. This is defined\n by the following math equation: πij = count ( Θj, di ) / Σ count ( ΘL, di ) where the sum goes\n from L = 1 to 'k', where 'k' is the number of k-topics. For the implementetion, 'count ( Θj, di )'\n will be stored in the variable 'counts' and 'Σ count ( ΘL, di )' in 'sum_counts'. Each 'πij'\n probability will be stored in the list 'topics_coverage_prob', and the sum of this list must be '1'.\n\n Note: This method needs a list of topics previously selected by the user according to the value throwed\n by some Information Retrieval Analysis, in this case we use TF-IDF statistic.\n\n :param document: Document or article to parse.\n :param topics: List of k-topics.\n \"\"\"\n counts = list ( map ( lambda topic : ( topic, document.count ( topic ) ), topics ) )\n sum_counts = sum ( list ( map ( lambda count : count [ 1 ], counts ) ) )\n topics_coverage_prob = list ( map ( lambda count : ( count [ 0 ], count [ 1 ] / sum_counts ) if ( sum_counts != 0 ) else ( count [ 0 ], 0 ), counts ) )\n topics_coverage_prob.sort ( key = lambda x : x [ 1 ] )\n print ( \"\\nProbability of the document covering the following topics:\" )\n print ( \"\\n{}... {}\".format ( \" \".join ( document [ :100 ] ), topics_coverage_prob ) )\n\n def lda_model ( self, documents ):\n \"\"\"\n This function uses the LDA (Latent Dirichlet Allocation) model implemented in the gensim module.\n For more information about this method read 'Text Data Management and Analysis by ChengXiang Zhai Chapter 17'.\n\n :param documents: Documents of which we want to know what topics they are covering.\n \"\"\"\n import gensim\n\n documents_tokenized = [ document.split ( ) for document in documents ]\n dictionary = gensim.corpora.Dictionary ( documents_tokenized )\n doc_term_matrix = [ dictionary.doc2bow ( document_tokenized ) for document_tokenized in documents_tokenized ]\n lda = gensim.models.ldamodel.LdaModel ( doc_term_matrix, num_topics = 20, id2word = dictionary, passes = 50 )\n words_distribution = lda.print_topics ( num_topics = 20, num_words = 20 )\n print ( \"\\nDocuments topic coverage: {}\\n\".format ( words_distribution ) )\n\n\n\"\"\" def print_lda_topics ( self, documents, topics, regular_expression = \"[a-záéíóúüñ]+\", left_margin = 6, right_margin = 6 ):\n \"\"\"\"\"\"\n :param documents: Documents of which we want to know what topics they are covering.\n \"\"\"\"\"\"\n import re\n\n topics = \" \".join ( list ( map ( lambda x : x [ 1 ], topics ) ) )\n topics = set ( re.findall ( regular_expression, topics ) )\n print ( topics )\n for topic in topics:\n for i in range ( len ( documents ) ):\n text_tokenized = documents [ i ].split ( )\n for j in range ( len ( text_tokenized ) ):\n if ( topic == text_tokenized [ j ] ):\n right = \" \".join ( text_tokenized [ j + 1 : right_margin + j + 1 ] )\n left = \" \".join ( text_tokenized [ j - left_margin : j ] )\n print ( \"Topic '{0:}' found in document {1:}:\\n{2:} {3:} {4:}...\\n\".format ( topic, i, left, topic, right ) )\n\"\"\"\n\n\ndef demo ( ):\n from ParadigmaticRelation import InformationRetrieval\n from collections import defaultdict\n from RawText import ProcessRawText\n import codecs, re, nltk, bs4\n\n # //////////////////////////////////////////////////////////////\n # Load a document from the local Excelsior Corpus.\n # //////////////////////////////////////////////////////////////\n corpus_root = \"./excelsior_corpus/e960401.htm\"\n f = codecs.open ( corpus_root, \"r\", \"latin-1\" )\n plane_text = f.read ( ).lower ( )\n f.close ( )\n\n # ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n # The MiningTopicalTerms class will find the potential candidates terms to be topics, this class will receive as parameter a collection of\n # documents ( list of lists ) in raw format to work with in specific situations. In this demo we are working with a single HTML document so,\n # we will split this single document into articles with the help of the method 'html_doc2articles', the return of this will be a list of\n # list where each element it's a set of articles for each document. To find the potential terms we implement the method 'find_potential_terms'.\n # Once we have this list of potential terms it's in out choice to choose which terms will be treated as topics.\n # ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n print ( \"\\nClass MiningTopicalTerms:\\n\" )\n mtt = MiningTopicalTerms ( [ plane_text ] )\n print ( \"\\t- Function html_doc2articles:\\n\" )\n documents = mtt.html_doc2articles ( )\n #print ( \"\\t- Function find_potential_terms:\" )\n #potential_terms = mtt.find_potential_terms ( )\n #topics = potential_terms [ :100 ]\n #print ( \"\\nPotential terms to be topics: {}\".format ( topics ) )\n topics = [ \"gobierno\", \"empresa\", \"banco\", \"político\", \"política\", \"dinero\", \"muerte\", \"internet\", \"droga\", \"finanzas\" ]\n\n # //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n # The ProcessRawText class in RawText module will receive a raw text to work with. For the HTML documents topics analysis we will normalize\n # each article in the 'documents_articles' list. Then we will find the vocabulary for this articles.\n # /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n prt = ProcessRawText ( plane_text = \"\" )\n prt.load_lemmatization_file ( language = \"es\", encode = \"latin-1\" )\n prt.load_stopwords_file ( language = \"es\", encode = \"latin-1\" )\n for i in range ( len ( documents ) ):\n prt.plane_text = documents [ i ]\n prt.html_parser ( )\n prt.remove_special_characters ( )\n text_tokenized = prt.tokenize_text ( )\n text_tokenized = prt.remove_stopwords ( text_tokenized = text_tokenized )\n text_tokenized = prt.word_lemmatize ( text_tokenized = text_tokenized )\n documents [ i ] = prt.plane_text\n\n # ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n # The TopicsCoverage class implements some methods to find the probability of a document covering an specific topic.\n # //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n print ( \"\\nClass TopicsCoverage:\\n\" )\n tc = TopicsCoverage ( )\n print ( \"\\t- Function term_as_topic:\" )\n for document in documents:\n tc.term_as_topic ( document.split ( ), topics )\n print ( \"\\n\\t- Function lda_model:\" )\n tc.lda_model ( documents )\n\n\nif ( __name__ == \"__main__\" ):\n demo ( )\n\n__all__ = [ \"MiningTopicalTerms\",\n \"TopicsCoverage\" ]\n","sub_path":"TopicAnalysis.py","file_name":"TopicAnalysis.py","file_ext":"py","file_size_in_byte":10678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"237848572","text":"# -*- coding: utf-8 -*-\r\n\r\n# 구구단 전체를 출력할 수 있는 \r\n# gugudan_all 함수를 선언하고 \r\n# 호출 결과를 확인하세요\r\n\r\ndef gugudan_all() :\r\n for dan in range(2,10) :\r\n print(f\"{dan}단을 출력합니다.\")\r\n \r\n for mul in range(1,10) :\r\n \r\n print(f\"{dan} * {mul} = {dan*mul}\")\r\n \r\ngugudan_all()\r\n\r\n# 매개변수로 전달된 숫자에 해당되는\r\n# 구구단을 출력할 수 있도록\r\n# gugudan_one 함수를 선언하고\r\n# 호출 결과를 확인하세요.\r\ndef gugudan_one(dan) :\r\n print(f\"{dan}단을 출력합니다.\")\r\n for mul in range(1, 10) :\r\n print(f\"{dan} * {mul} = {dan*mul}\")\r\n\r\ngugudan_one(7)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"day_04/function_02_EX.py","file_name":"function_02_EX.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"103283400","text":"# /bin/python\nimport os\nimport random\nimport multiset as ms\nimport numpy as np\nimport copy\nimport traceback\nimport pandas as pd\nfrom collections import defaultdict\nfrom tqdm import tqdm\nimport sys\n\n\n\nclass Duel :\n def __init__(self):\n global decks, hands, normal_summon, cemetary\n hands, cemetary, fields = [], [], []\n self.cards = {\n \"封印されし者の左足\" : 1,\n \"封印されし者の左腕\" : 1,\n \"封印されし者の右腕\" : 1,\n \"封印されし者の右足\" : 1,\n \"封印されしエグゾディア\" : 1,\n \"ブルーアイズ・トゥーン・ドラゴン\" : 1,\n \"魔導書士バテル\" : 1,\n \"一時休戦\" : 1,\n \"ルドラの魔導書\" : 1,\n \"トゥーンのもくじ\" : 3,\n \"トレード・イン\" : 1,\n \"成金ゴブリン\" : 3,\n \"テラ・フォーミング\" : 1,\n \"チキン・レース\" : 3,\n \"擬似空間\" : 3\n }\n self.win_hands = np.array([\"封印されし者の左足\", \"封印されし者の左腕\",\n \"封印されし者の右足\", \"封印されし者の右腕\", \"封印されしエグゾディア\"])\n\n def start(self) :\n global decks, fields, hands, normal_summon, cemetary\n cemetary = []\n normal_summon = 1\n fields = []\n decks = sum([[k]*self.cards[k] for k in self.cards], [])\n hands = [self.draw() for i in range(5)]\n #self.Deck_num = len(self.Decks)\n\n\n def draw(self) :\n global decks, hands, normal_summon, cemetary\n draw_card = random.choice(decks)\n decks.remove(draw_card)\n # if self.win_hands in np.array(hands) :\n # print(\"Win! Exodia was completed\")\n return(draw_card)\n\n def choose_target(self, targets) :\n if len(targets) == 0 :\n #print(chr(27) + \"[2J\")\n print(\"===========================================\")\n print(\"There are no targets\")\n sys.exit()\n\n #print(chr(27) + \"[2J\")\n print(\"===========================================\")\n print(\"Choose the target card\")\n for i in range(len(targets)) : print(f\"{i} : {targets[i]}\")\n index = int(input())\n target = targets[index]\n return(target)\n\n def search(self, target) :\n hands.append(target)\n decks.remove(target)\n\n\n\nclass Monster(Duel) :\n def __init__(self) :\n self.name = None\n self.category = \"monster\"\n\n def summon(self) :\n global decks, hands, normal_summon, cemetary\n normal_summon -= 1\n if normal_summon < 0 :\n #print(chr(27) + \"[2J\")\n print(\"=============================\")\n raise Exception(\"ImplementError\")\n\n elif self.level <= 4 :\n fields.append(self.name)\n hands.remove(self.name)\n\n self.summoned_effect()\n\n def summoned_effect(self) :\n print(\"\")\n\n\nclass NormalMagic(Duel) :\n def __init__(self) :\n self.name = None\n self.category = \"magic\"\n self.magic_type = \"normal\"\n\n def activate(self) :\n hands.remove(self.name)\n self.normal_effect()\n cemetary.append(self.name)\n\n\n def normal_effect(self) :\n print(\"\")\n\n\n\nclass FieldMagic(Duel) :\n global cards, hands, fields, cemetary, decks\n def __init__(self) :\n self.name = None\n self.category = \"magic\"\n self.magic_type = \"field\"\n\n def activate(self) :\n for k in fields :\n c = cards[k]()\n if c.category == \"magic\" :\n if c.magic_type == \"field\" :\n fields.remove(k)\n cemetary.append(k)\n\n hands.remove(self.name)\n fields.append(self.name)\n self.fields_effect()\n\n def fields_effect(self) :\n print(\"\")\n\n\nclass exodia(Monster) :\n def __init__(self) :\n super(exodia, self).__init__()\n self.tribe = \"magician\"\n self.level = 3\n self.attribute = \"darkness\"\n self.name = \"封印されしエグゾディア\"\n self.atk = 1000\n self.dfc = 1000\n\nclass exodia_left_hand(Monster) :\n def __init__(self) :\n super(exodia_left_hand, self).__init__()\n self.tribe = \"magician\"\n self.level = 1\n self.attribute = \"darkness\"\n self.name = \"封印されし者の左腕\"\n self.atk = 200\n self.dfc = 300\n\nclass exodia_right_hand(Monster) :\n def __init__(self) :\n super(exodia_right_hand, self).__init__()\n self.category = \"monster\"\n self.tribe = \"magician\"\n self.level = 1\n self.attribute = \"darkness\"\n self.name = \"封印されし者の右腕\"\n self.atk = 200\n self.dfc = 300\n\nclass exodia_left_leg(Monster) :\n def __init__(self) :\n super(exodia_left_leg, self).__init__()\n self.tribe = \"magician\"\n self.level = 1\n self.attribute = \"darkness\"\n self.name = \"封印されし者の左足\"\n self.atk = 200\n self.dfc = 300\n\n\nclass exodia_right_leg(Monster) :\n def __init__(self) :\n super(exodia_right_leg, self).__init__()\n self.tribe = \"magician\"\n self.level = 1\n self.attribute = \"darkness\"\n self.name = \"封印されし者の右足\"\n self.atk = 200\n self.dfc = 300\n\n\n\nclass blue_eyes_toon(Monster) :\n def __init__(self) :\n super(blue_eyes_toon, self).__init__()\n self.tribe = \"dragon\"\n self.level = 8\n self.attribute = \"lightness\"\n self.name = \"ブルーアイズ・トゥーン・ドラゴン\"\n self.atk = 3000\n self.dfc = 2500\n\n\nclass spellbook_of_magician_of_prophecy(Monster) :\n def __init__(self) :\n super(spellbook_of_magician_of_prophecy, self).__init__()\n self.tribe = \"magician\"\n self.level = 2\n self.attribute = \"water\"\n self.name = \"魔導書士バテル\"\n self.atk = 500\n self.dfc = 200\n\n def summoned_effect(self) :\n global decks, hands, normal_summon, cemetary\n targets = []\n for k in decks :\n if \"魔導書\" in cards[k]().name :\n targets.append(k)\n\n if len(targets) == 0 :\n print(\"There are no cards to search\")\n\n else :\n target = self.choose_target(targets)\n self.search(target)\n\n\nclass rest_for_a_while(NormalMagic) :\n def __init__(self) :\n super(rest_for_a_while, self).__init__()\n self.name = \"一時休戦\"\n\n def normal_effect(self) :\n global decks, hands, normal_summon, cemetary\n hands.append(self.draw())\n\n\nclass upstart_goblin(NormalMagic) :\n def __init__(self) :\n super(upstart_goblin, self).__init__()\n self.name = \"成金ゴブリン\"\n\n def normal_effect(self) :\n global decks, hands, normal_summon, cemetary\n hands.append(self.draw())\n\n\nclass teraforming(NormalMagic) :\n def __init__(self) :\n super(teraforming, self).__init__()\n self.name = \"テラ・フォーミング\"\n\n def normal_effect(self) :\n global cards, decks, hands, normal_summon, cemetary\n targets = []\n for k in decks :\n c = cards[k]()\n if c.category == \"magic\" :\n if c.magic_type == \"field\" :\n targets.append(k)\n #raise Exception(\"ImplementError\")\n target = self.choose_target(targets)\n self.search(target)\n\n\nclass toon_content(NormalMagic) :\n def __init__(self) :\n super(toon_content, self).__init__()\n self.name = 'トゥーンのもくじ'\n\n def normal_effect(self) :\n global decks, hands, normal_summon, cemetary\n toon_cards = list(set([k for k in decks if \"トゥーン\" in cards[k]().name]))\n target = self.choose_target(toon_cards)\n self.search(target)\n\n\nclass trade_in(NormalMagic) :\n def __init__(self) :\n super(trade_in, self).__init__()\n self.name = 'トレード・イン'\n\n def normal_effect(self) :\n global cards, decks, hands, normal_summon, cemetary\n\n targets = []\n for k in hands :\n if cards[k]().category == \"monster\" :\n if cards[k]().level == 8 :\n targets.append(k)\n\n target = self.choose_target(targets)\n hands.remove(target)\n hands.append(self.draw())\n hands.append(self.draw())\n\n\n\nclass chicken_race(FieldMagic) :\n def __init__(self) :\n super(chicken_race, self).__init__()\n self.name = 'チキン・レース'\n\n def fields_effect(self) :\n global decks, hands, normal_summon, cemetary\n hands.append(self.draw())\n\n\nclass pseudo_space(FieldMagic) :\n def __init__(self) :\n super(pseudo_space, self).__init__()\n self.name = '擬似空間'\n\n def fields_effect(self) :\n global cards, decks, hands, normal_summon, cemetary\n targets = []\n for k in cemetary :\n c = cards[k]()\n if c.category == \"magic\" :\n if c.magic_type == \"field\" :\n targets.append(k)\n\n target = self.choose_target(targets)\n cards[target]().fields_effect()\n cemetary.remove(target)\n\n\n\nclass spellbook_of_knowledge(NormalMagic) :\n def __init__(self) :\n super(spellbook_of_knowledge, self).__init__()\n self.category = \"magic\"\n self.name = 'ルドラの魔導書'\n\n def normal_effect(self) :\n global decks, hands, normal_summon, cemetary\n\n targets = []\n hands_fields = []\n for k in fields :\n if cards[k]().category == \"monster\" :\n if cards[k]().tribe == \"magician\" :\n targets.append(k)\n hands_fields.append(\"fields\")\n\n for k in hands :\n if \"魔導書\" in cards[k]().name :\n targets.append(k)\n hands_fields.append(\"hands\")\n\n for i in range(len(targets)) : print(f\"{i} : {targets[i]}\")\n index = int(input())\n target = targets[index]\n if hands_fields[index] == \"hands\" :\n hands.remove(target)\n elif hands_fields[index] == \"fields\" :\n fields.remove(target)\n cemetary.append(target)\n\n hands.append(self.draw())\n hands.append(self.draw())\n\n\ncards = {\n \"封印されし者の左足\" : exodia_left_leg,\n \"封印されし者の左腕\" : exodia_left_hand,\n \"封印されし者の右腕\" : exodia_right_hand,\n \"封印されし者の右足\" : exodia_right_leg,\n \"封印されしエグゾディア\" : exodia,\n \"擬似空間\" : pseudo_space,\n \"ブルーアイズ・トゥーン・ドラゴン\" : blue_eyes_toon,\n \"魔導書士バテル\" : spellbook_of_magician_of_prophecy,\n \"ルドラの魔導書\" : spellbook_of_knowledge,\n \"一時休戦\" : rest_for_a_while,\n \"トレード・イン\" : trade_in ,\n \"トゥーンのもくじ\" : toon_content,\n \"成金ゴブリン\" : upstart_goblin,\n \"テラ・フォーミング\" : teraforming,\n \"チキン・レース\" : chicken_race}\n\n\n\ndef complete_exodia() :\n global hands\n win_hands = [\"封印されし者の左足\", \"封印されし者の左腕\",\n \"封印されし者の右足\", \"封印されし者の右腕\", \"封印されしエグゾディア\"]\n tf = (len(hands) >= 5) and (set(win_hands) <= set(hands))\n return(tf)\n\n\ndef get_actions() :\n global hands, cards, normal_summon\n action_dict = defaultdict()\n\n for k in hands : #k=hands[0]\n action = None\n card = cards[k]()\n if card.category == \"magic\" :\n action = cards[k]().activate\n elif card.category == \"monster\" :\n if normal_summon >= 1 :\n action = cards[k]().summon\n\n if action : action_dict[card.name] = action\n else : continue\n return(action_dict)\n\n\n\ndef show_actions(action_dict) :\n keys = list(action_dict.keys())\n for i in range(len(keys)) :\n print(f\"{i} : {keys[i]}\")\n\n\n\ndef get_states() :\n global hands, fields, cemetary, decks, normal_summon\n states = defaultdict()\n states[\"hands\"] = hands\n states[\"fields\"] = fields\n states[\"cemetary\"] = cemetary\n states[\"normal_summon\"] = normal_summon\n states[\"decks\"] = decks\n return(states)\n\n\ndef main() :\n duel = Duel()\n duel.start()\n\n tf = True\n while tf :\n print(\"The states : \")\n states = get_states()\n\n for k in states :\n if k!= \"decks\" :\n print(f\" {k} : {states[k]}\")\n if complete_exodia() :\n #print(chr(27) + \"[2J\")\n print(\"====================================================\")\n print(\"Exodia Completed !\")\n print(hands)\n sys.exit()\n\n action_dict = get_actions()\n keys = list(action_dict.keys())\n if len(keys) == 0 :\n #print(chr(27) + \"[2J\")\n print(\"====================================================\")\n print(\"There are no actions\")\n sys.exit()\n\n #print(chr(27) + \"[2J\")\n print(\"====================================================\")\n print(\"Choose the action : \")\n show_actions(action_dict)\n action = int(input())\n\n if complete_exodia() :\n #print(chr(27) + \"[2J\")\n print(\"====================================================\")\n print(\"Exodia Completed !\")\n print(hands)\n sys.exit()\n\n key = keys[action]\n action_dict[key]()\n tf = len(decks) != 0\n\n\n\nif __name__ == '__main__' :\n main()\n","sub_path":"src/exodia_mini_CLI.py","file_name":"exodia_mini_CLI.py","file_ext":"py","file_size_in_byte":13813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"56791874","text":"#!/usr/bin/python3\nimport itertools\nimport math\nimport threading\n\nN = 0\nm = 0\n\nDIRECT = 0\nINFERIOR = 1\nINVERSE = 2\nSUPERIOR = 3\nBLOCK_TYPES = [DIRECT, INFERIOR, INVERSE, SUPERIOR]\n\nresult = None\n\nTHREADS = 4\n\n\ndef generate_all_posibilities(nr_of_blocks):\n \"\"\"\n Generates all possible block types variations\n :param nr_of_blocks: the total number of blocks in the network\n :return: generated possibilities\n \"\"\"\n blocks = [BLOCK_TYPES] * nr_of_blocks\n product = itertools.product(*blocks)\n\n return product\n\n\ndef go_through_level(start, values, blocks):\n \"\"\"\n Simulates the shuffled input going through a level\n :param start: index or first block from level\n :param values: shuffled values\n :param blocks: all blocks\n :return: input processed through level\n \"\"\"\n output = [0] * N\n\n for i in range(int(start), int(start + (N / 2))):\n j = int(2 * (i - start))\n\n if blocks[i] == DIRECT:\n output[j] = values[j]\n output[j + 1] = values[j + 1]\n elif blocks[i] == INFERIOR:\n output[j] = values[j + 1]\n output[j + 1] = values[j + 1]\n elif blocks[i] == INVERSE:\n output[j] = values[j + 1]\n output[j + 1] = values[j]\n elif blocks[i] == SUPERIOR:\n output[j] = values[j]\n output[j + 1] = values[j]\n\n return output\n\n\ndef shuffle(i):\n \"\"\"\n Shuffling\n :param i: number of input value before shuffle\n :return: position of value after shuffle\n \"\"\"\n return int((int(2 * i) + int(2 * i / N)) % N)\n\n\ndef print_output(INPUT, OUTPUT, steps, nr_of_rows, nr_of_blocks):\n \"\"\"\n :param INPUT: input values\n :param OUTPUT: output values\n :param steps: steps in each level\n :param nr_of_rows: N/2\n :param nr_of_blocks: N/2*log(N)\n \"\"\"\n global result\n\n # Print result\n print(\"N: {}\\nk: {}\\n\".format(N, m))\n print(\"Input: {}\\nOutput: {}\\n\".format(INPUT, OUTPUT))\n\n print(\"Block types (as seen on the scheme):\")\n network = []\n for i in range(nr_of_rows):\n blocks = []\n for j in range(0 + i, nr_of_blocks + i, nr_of_rows):\n if result[j] == DIRECT:\n blocks.append(\"DIRECT\")\n elif result[j] == INFERIOR:\n blocks.append(\"INFERIOR\")\n elif result[j] == INVERSE:\n blocks.append(\"INVERSE\")\n elif result[j] == SUPERIOR:\n blocks.append(\"SUPERIOR\")\n network.append(blocks)\n col_width = max(len(word) for row in network for word in row) + 2\n for row in network:\n padded_row = [word.ljust(col_width) for word in row]\n blocks_to_string = \"\"\n for block in padded_row:\n blocks_to_string += str(block)\n print(blocks_to_string)\n\n print(\"\\nDetailed steps per level:\")\n col_width = max(len(steps[step]) for step in steps) + 2\n step_nr = 0\n for step in steps:\n if step_nr % 3 == 0:\n print(\"Level {}:\".format(int(step_nr / 3 + 1)))\n step_nr += 1\n print(\"{}: {}\".format(str(step).ljust(col_width), str(steps[step]).ljust(col_width)))\n\n\ndef check_possibility(INPUT, OUTPUT, possibilities, start, end, nr_of_rows, nr_of_blocks):\n global result\n\n shuffled_values = [0] * N\n output_values = [0] * N\n\n # Find block types\n count = -1\n steps = {}\n for possibility in possibilities:\n if result is not None: # other thread might have found the solution\n return\n count += 1\n if count not in range(start, end):\n continue\n input_values = INPUT.copy()\n for level in range(m):\n for i in range(N):\n shuffled_value = shuffle(i)\n shuffled_values[shuffled_value] = input_values[i]\n output_values = go_through_level(level * N / 2, shuffled_values, list(possibility)).copy()\n steps[\"{}_Input\".format(level)] = input_values.copy()\n steps[\"{}_Shuffled\".format(level)] = shuffled_values.copy()\n steps[\"{}_Output\".format(level)] = output_values.copy()\n input_values = output_values.copy()\n\n # Here we check if we found the result.\n # If we want to also check for networks with another number of `shuffle` connections (different than log(N)),\n # then this `if` section should be inside the `for` loop: `for level in range(m):` - so just \\tab this `if`\n if output_values == OUTPUT:\n result = list(possibility)\n print_output(INPUT, OUTPUT, steps, nr_of_rows, nr_of_blocks)\n return\n return\n\n\ndef set_input_output_values():\n \"\"\"\n Here you can choose/set the input values for this program\n :return: INPUT and OUTPUT values for Omega network\n \"\"\"\n \"\"\" !!!!!!!!!!!!!!!! MODIFY HERE THE INPUT AND OUTPUT VALUES !!!!!!!!!!!!!!!!!!!!!! \"\"\"\n # these should give only DIRECT blocks - easy computation\n INPUT = [0, 1, 2, 3, 4, 5, 6, 7]\n OUTPUT = [0, 1, 2, 3, 4, 5, 6, 7]\n\n # # this should give an INFERIOR block - bottom right - easy computation\n # INPUT = [0, 1, 2, 3, 4, 5, 6, 7]\n # OUTPUT = [0, 1, 2, 3, 4, 5, 7, 7]\n\n # # this should give an INVERSE block - top right - hard computation, goes through many possibilities\n # INPUT = [0, 1, 2, 3, 4, 5, 6, 7]\n # OUTPUT = [1, 0, 2, 3, 4, 5, 6, 7]\n\n # # this should give an error - no possibility for this - very hard computation, goes through all the possibilities\n # INPUT = [0, 1, 2, 3, 4, 5, 6, 7]\n # OUTPUT = [0, 1, 2, 3, 4, 5, 6, 8]\n\n return INPUT, OUTPUT\n\n\ndef main():\n \"\"\"\n Gives INPUT and OUTPUT and computes all the block types that connect the INPUT to the OUTPUT\n :return:\n \"\"\"\n global N, m\n\n INPUT, OUTPUT = set_input_output_values()\n\n # Computing N and m\n N = len(INPUT)\n assert math.log2(N) == int(math.log2(N)) # check if the number of inputs is power of 2\n m = int(math.log2(N))\n\n # Computing network values\n nr_of_levels = int(math.log2(N))\n nr_of_rows = int(N / 2)\n nr_of_blocks = nr_of_levels * nr_of_rows\n\n # Generating all possibilities\n possibilities = generate_all_posibilities(nr_of_blocks)\n\n # Testing all possibilities\n nr_of_possibilities = len(BLOCK_TYPES) ** nr_of_blocks\n threads = []\n for thread in range(THREADS):\n start = int(nr_of_possibilities / THREADS * len(threads))\n end = int(nr_of_possibilities / THREADS * (len(threads) + 1))\n threads.append(threading.Thread(target=check_possibility, args=(INPUT, OUTPUT, possibilities, start, end, nr_of_rows, nr_of_blocks)))\n\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n if result is None:\n print(\"There is no Omega network of size {0}x{0} that can convert {1} to {2}!\".format(N, INPUT, OUTPUT))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"SM/Laboratoare/Lab3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141685096","text":"\"\"\"\nswap min/max module\n\"\"\"\n\nfrom typing import List\n\n\ndef get_position_min_num(lst: List[int]) -> int:\n \"\"\"\n Return position index of minimum number from list.\n :param lst: List[int]\n :return: int\n \"\"\"\n min_num = lst[0]\n min_num_idx = 0\n for idx, num in enumerate(lst):\n if lst[idx] < min_num:\n min_num_idx = idx\n return min_num_idx\n\n\ndef get_position_max_num(lst: List[int]) -> int:\n \"\"\"\n Return position index of maximum number from list.\n :param lst: List[int]\n :return: int\n \"\"\"\n max_num = lst[0]\n max_num_idx = 0\n for idx, num in enumerate(lst):\n if lst[idx] > max_num:\n max_num_idx = idx\n return max_num_idx\n\n\ndef swap_minmax(lst: List[int]) -> List[int]:\n \"\"\"\n Swapping minimal and maximal elements of a list.\n :param lst: List[int]\n :return: List[int]\n \"\"\"\n if len(lst) > 0:\n min_num_idx = get_position_min_num(lst)\n max_num_idx = get_position_max_num(lst)\n else:\n return lst\n min_max_nums = lst[min_num_idx], lst[max_num_idx]\n lst[max_num_idx], lst[min_num_idx] = min_max_nums\n return lst\n\n\ndef swap_minmax_den_solution(lst: List[int]) -> List[int]:\n if not lst:\n return lst\n\n minv, mini = lst[0], 0\n maxv, maxi = lst[0], 0\n\n for i, el in enumerate(lst):\n if el < minv:\n minv = el\n mini = i\n if el > maxv:\n maxv = el\n maxi = i\n lst[mini], lst[maxi] = maxv, minv\n return lst","sub_path":"swap_minmax.py","file_name":"swap_minmax.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361313840","text":"def Graph_read(file_name):\n G = {}\n G_rev = {}\n with open(file_name) as f:\n count =0\n handle = open('SCC_test.txt','w')\n for line in f:\n handle.write(line)\n count = count + 1\n if count > 1000:\n break\nGraph_read('SCC.txt')\n","sub_path":"Graph(Course2)/week1_SCCs/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"9552805","text":"from django.contrib import admin\nfrom django.urls import path, re_path\nfrom covidapp import views\nfrom django.conf.urls import url\nfrom django.views.decorators.http import require_POST\n\nurlpatterns = [\n path('index/', views.index, name='index'),\n path('patient_new/', views.patient_new, name='patient_new'),\n path('location_new/', views.location_new, name='location_new'),\n path('location_list/', views.location_temps, name='location_list'),\n re_path('patient/(?P\\d+)$', views.PatientDetailView.as_view(), name='patient_detail'),\n re_path('location/(?P\\d+)$', views.LocationDetailView.as_view(), name='location_detail'),\n re_path('patient/(?P\\d+)/edit/$', views.PatientUpdateView.as_view(), name='patient_edit'),\n re_path('my_form/$', require_POST(views.MyFormView.as_view()), name='my_form_view_url'),\n re_path('patient/(?P\\d+)/remove/$', views.PatientDeleteView.as_view(), name='patient_remove'),\n re_path('patient/(?P\\d+)/query/$', views.profile_search, name='query'),\n #re_path('patient/(?P\\d+)/query/$', views.QueryView.as_view(), name='query'),\n re_path('location/(?P\\d+)/edit/$', views.LocationUpdateView.as_view(), name='location_edit'),\n re_path('location/(?P\\d+)/remove/$', views.LocationDeleteView.as_view(), name='location_remove'),\n re_path('location/(?P\\d+)/plocation/$', views.PLocationDetailView.as_view(), name='plocation_detail'),\n #re_path('location/(?P\\d+)/editPL/$', views.PLocationUpdateView.as_view(), name='plocation_edit'),\n path('location//editPL/',views.PLocationUpdateView.as_view(), name='plocation_edit'),\n re_path('location/(?P\\d+)/removePL/$', views.PLocationDeleteView.as_view(), name='plocation_remove'),\n]\n","sub_path":"covidapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"32026115","text":"from urllib.request import urlopen as uReq\r\nfrom bs4 import BeautifulSoup as soup\r\nimport csv\r\nimport numpy as np\r\nimport pandas as pd\r\nimport plotly.graph_objects as go\r\nimport plotly.express as px\r\nimport os\r\nimport webbrowser\r\n\r\n'''\r\nSI 507 F19 Final Project\r\nMariluD\r\n'''\r\n\r\n# Declaring a class to store data of a single movie\r\nclass MovieData:\r\n def __init__(self):\r\n # Declaring the variables\r\n self.title = \"\"\r\n self.rating = \"\"\r\n self.rating_count = \"\"\r\n self.director = \"\"\r\n self.director_bio = \"\"\r\n self.genre = \"\"\r\n self.year = \"\"\r\n self.runtime = \"\"\r\n self.budget = \"\"\r\n self.stars = \"\"\r\n self.summary = \"\"\r\n\r\n # Creating /calling clasess\r\n def get_title(self):\r\n return self.title\r\n\r\n def get_rating(self):\r\n return self.rating\r\n\r\n def get_rating_count(self):\r\n return self.rating_count\r\n\r\n def get_director(self):\r\n return self.director\r\n\r\n def get_director_bio(self):\r\n return self.director_bio\r\n\r\n def get_genre(self):\r\n return self.genre\r\n\r\n def get_year(self):\r\n return self.year\r\n\r\n def get_runtime(self):\r\n return self.runtime\r\n\r\n def get_budget(self):\r\n return self.budget\r\n\r\n def get_stars(self):\r\n return self.stars\r\n\r\n def get_summary(self):\r\n return self.summary\r\n\r\n # Getting a single row to save in the CSV file\r\n def get_details_csv_list(self):\r\n try:\r\n # Preparing a list from the class data.\r\n csv_list = [self.title.replace(\",\", \"\").replace(\"\\n\", \"\"), self.rating.replace(\",\", \"\").replace(\"\\n\", \"\"),\r\n self.rating_count.replace(\",\", \"\").replace(\"\\n\", \"\"), self.director.replace(\",\", \"\").replace(\"\\n\", \"\"),\r\n self.director_bio.replace(\",\", \"\").replace(\"\\n\", \"\"), self.genre.replace(\",\", \"\").replace(\"\\n\", \"\"),\r\n self.year.replace(\",\", \"\").replace(\"\\n\", \"\"), self.runtime.replace(\",\", \"\").replace(\"\\n\", \"\"),\r\n self.budget.replace(\",\", \"\").replace(\"\\n\", \"\"), self.stars.replace(\",\", \"\").replace(\"\\n\", \"\"),\r\n self.summary.replace(\",\", \"\").replace(\"\\n\", \"\")]\r\n\r\n except Exception as e:\r\n # Class already processed\r\n csv_list = [self.title, self.rating, self.rating_count, self.director, self.director_bio, self.genre, self.year, self.runtime,\r\n self.budget, self.stars, self.summary]\r\n\r\n # Returning the list\r\n return csv_list\r\n\r\n\r\n# Declaring an IMDB scrapper class\r\nclass IMDBWebScraper:\r\n def __init__(self):\r\n # Initializing the IMDB links\r\n self.imdb_url = \"https://www.imdb.com\"\r\n self.top_rated_movies_url = \"https://www.imdb.com/chart/top/?ref_=nv_mv_250\"\r\n\r\n # Getting the titles for the data scrapped\r\n def get_csv_title(self):\r\n csv_title = [\"Title\", \"Rating\", \"Rating Count\", \"Director\", \"Director Bio\", \"Genre\", \"Year\",\r\n \"Runtime\", \"Budget\", \"Stars\", \"Summary\"]\r\n return csv_title\r\n\r\n # Converting the url to a soup document\r\n def url_to_soup(self, url):\r\n # Reading the url\r\n u_client = uReq(url)\r\n # Getting the page html\r\n page_html = u_client.read()\r\n # Closing the connection\r\n u_client.close()\r\n # Converting into valid html\r\n page_soup = soup(page_html, \"html.parser\")\r\n # Returning the parsed html\r\n return page_soup\r\n\r\n # Analyze a single movie page\r\n def analyze_movie_page(self, movie_soup):\r\n # Creating a class object\r\n movie_data = MovieData()\r\n # Exception handling\r\n try:\r\n try:\r\n # Getting the title and year data\r\n year_span = movie_soup.find(\"span\", {\"id\": \"titleYear\"})\r\n # Getting the year span\r\n title_span = year_span.find_parent(\"h1\")\r\n # Extracting title the div\r\n movie_data.title = str(title_span.text).split(\"(\")[0]\r\n # Extracting year from the div\r\n movie_data.year = year_span.text\r\n except Exception:\r\n pass\r\n\r\n try:\r\n # Getting the rating data\r\n rating_span = movie_soup.find(\"span\", {\"itemprop\": \"ratingValue\"})\r\n movie_data.rating = rating_span.text\r\n rating_count_span = movie_soup.find(\"span\", {\"itemprop\": \"ratingCount\"})\r\n movie_data.rating_count = rating_count_span.text\r\n except Exception:\r\n pass\r\n try:\r\n # Getting the plot summary data\r\n plot_summary = str(movie_soup.find(\"div\", {\"class\": \"summary_text\"}).text)\r\n movie_data.summary = \" \".join(plot_summary.split())\r\n except Exception:\r\n pass\r\n\r\n try:\r\n # getting the director and stars data\r\n credit_items_blocks = movie_soup.find_all(\"div\", {\"class\": \"credit_summary_item\"})\r\n movie_data.director = credit_items_blocks[0].a.text\r\n movie_director_bio_link = \"https://www.imdb.com/\" + credit_items_blocks[0].a[\"href\"] + \"bio?ref_=nm_ov_bio_sm\"\r\n try:\r\n bio_soup = self.url_to_soup(movie_director_bio_link)\r\n bio = bio_soup.find(\"div\", {\"class\": \"soda odd\"}).p.text\r\n bio = bio.replace(\",\", \"\").replace(\"\\n\", \"\").replace(\"\\\"\", \"\").replace(\" \", \"\").strip()\r\n if len(bio) > 1500:\r\n bio = bio[:1500]\r\n movie_data.director_bio = bio\r\n except Exception as e:\r\n pass\r\n\r\n try:\r\n movie_stars_list = credit_items_blocks[2].find_all(\"a\")\r\n movie_stars_list = movie_stars_list[:len(movie_stars_list) - 1]\r\n movie_stars = \"\"\r\n for movie_star in movie_stars_list:\r\n movie_stars += str(movie_star.text) + \"|\"\r\n movie_data.stars = movie_stars[:len(movie_stars) - 1]\r\n except Exception:\r\n pass\r\n except Exception:\r\n pass\r\n\r\n try:\r\n # Getting the genre data\r\n genere_div = movie_soup.find(\"h4\", text=\"Genres:\")\r\n genere_parent_div = genere_div.find_parent(\"div\")\r\n movie_data.genre = \" \".join(str(genere_parent_div.a.text).split())\r\n except Exception:\r\n pass\r\n\r\n try:\r\n # Getting the budget data\r\n budget_div = movie_soup.find(\"h4\", text=\"Budget:\")\r\n budget_parent_div = budget_div.find_parent(\"div\")\r\n movie_data.budget = \" \".join(str(budget_parent_div.text).split())\r\n except Exception:\r\n pass\r\n\r\n try:\r\n # Getting the runtime data\r\n runtime_div = movie_soup.find(\"h4\", text=\"Runtime:\")\r\n runtime_parent_div = runtime_div.find_parent(\"div\")\r\n runtime = \" \".join(str(runtime_parent_div.text).split())\r\n movie_data.runtime = runtime.split(\"|\")[0]\r\n except Exception:\r\n pass\r\n\r\n # Returning single movie data\r\n return movie_data\r\n except Exception as e:\r\n return None\r\n\r\n # Scraping the entire top rated movies dataset\r\n def scrape_data(self):\r\n # Getting main page html\r\n page_soup = self.url_to_soup(self.top_rated_movies_url)\r\n # Getting the list of movies\r\n movies_container = page_soup.find(\"tbody\", {\"class\": \"lister-list\"})\r\n movies_list = movies_container.findChildren(\"tr\", recursive=False)\r\n\r\n scraped_movies_data = []\r\n counter = 1\r\n # Traversing the movies list\r\n print(\"-\" * 50, \"SCRAPING MOVIES\", \"-\" * 50)\r\n for movie in movies_list:\r\n # Getting the url for the current movie\r\n movie_url = self.imdb_url + movie.td.a[\"href\"]\r\n # Getting the html from url\r\n movie_soup = self.url_to_soup(movie_url)\r\n # Getting current movie data\r\n curr_movie_data = self.analyze_movie_page(movie_soup)\r\n if curr_movie_data is not None:\r\n # Adding it into the list\r\n scraped_movies_data.append(curr_movie_data)\r\n print(\"Movie Scraped:(\" + str(counter) + \"/250)\")\r\n counter += 1\r\n # Saving the scraped data\r\n self.save_data(scraped_movies_data, \"raw_movie_data.csv\")\r\n # Processing the data\r\n self.process_data()\r\n\r\n # Saving data into csv file/ new database\r\n def save_data(self, movies_data, file_name):\r\n # Opening the file\r\n with open(file_name, \"w\", newline='') as csv_file:\r\n # Getting the csv writer\r\n csv_writer = csv.writer(csv_file, delimiter=\",\")\r\n # Writing the data row by row into the file\r\n csv_writer.writerow(self.get_csv_title())\r\n for movie in movies_data:\r\n csv_writer.writerow(movie.get_details_csv_list())\r\n\r\n # Processing the data\r\n def process_data(self):\r\n file_name = \"raw_movie_data.csv\"\r\n\r\n # Loading the raw data\r\n with open(file_name, \"r\") as csv_file:\r\n csv_reader = csv.reader(csv_file)\r\n processed_data = []\r\n title_row = True\r\n # Processing data row by row\r\n for row in csv_reader:\r\n if title_row:\r\n title_row = False\r\n else:\r\n # Crating a movie object for processed data\r\n movie_data = MovieData()\r\n movie_data.title = row[0].strip()\r\n movie_data.rating = float(row[1])\r\n movie_data.rating_count = int(row[2])\r\n movie_data.director = row[3].strip()\r\n movie_data.director_bio = row[4]\r\n movie_data.genre = row[5].strip()\r\n # Processing the columns\r\n movie_data.year = ''.join(i for i in row[6] if i.isdigit()).strip()\r\n movie_data.runtime = ''.join(i for i in row[7] if i.isdigit()).strip()\r\n movie_data.budget = ''.join(i for i in row[8] if i.isdigit()).strip()\r\n movie_data.stars = row[9].strip()\r\n movie_data.summary = row[10].strip()\r\n if movie_data.budget != \"\":\r\n processed_data.append(movie_data)\r\n # Saving data into processed file/new database to pull from.\r\n self.save_data(processed_data, \"processed_movie_data.csv\")\r\n\r\n\r\n# Function to print the menu\r\ndef menu():\r\n # Printing the menu\r\n print()\r\n print(\"-\" * 50, \"Data From Top 250 IMDB Movies: MENU\", \"-\" * 50)\r\n print(\"The following commands are available, replace with an actual space\")\r\n print(\"Command 1: Type \\\"scrape\\\" to scrape the data.\")\r\n print(\"Command 2: Type \\\"movies\\\" to get a list of movies.\")\r\n print(\"Command 3: Type \\\"movie_name name\\\" to get details of a specific movie.\")\r\n print(\"Command 4: Type \\\"movie_genre genre\\\" to get a list movies within a specific genre.\")\r\n print(\"Command 5: Type \\\"graph genre_pie\\\" to get a pie chart of the movies based on their genre.\")\r\n print(\"Command 6: Type \\\"movie_year year\\\" to get a list of movies within a specific year.\")\r\n print(\"Command 7: Type \\\"graph year_rating\\\" to get a scatter plot between year and rating.\")\r\n print(\"Command 8: Type \\\"directors\\\" to get a list of directors.\")\r\n print(\"Command 9: Type \\\"director_bio name\\\" to get the bio of that director.\")\r\n print(\"Command 10: Type \\\"graph director_rating\\\" to get a scatter plot between director and rating.\")\r\n print(\"Command 11: Type \\\"top_rating n\\\" to get a list of top n movies by rating (n is an integer)\")\r\n print(\"Command 12: Type \\\"top_budget n\\\" to get a list of top n movies by budget, (n is an integer)\")\r\n print(\"Command 13: Type \\\"graph run_budget\\\" to get a line plot between runtime and budget.\")\r\n print(\"Command 14: Type \\\"table\\\" to view the full database of all the movies in plain HTML.\")\r\n print(\"Command 15: Type \\\"help\\\" to get a list of instructions.\")\r\n print(\"Command 16: Type \\\"quit\\\" to quit the application.\")\r\n print()\r\n\r\n\r\n# The main function\r\ndef main():\r\n # The data file name\r\n file_name = \"processed_movie_data.csv\"\r\n df = None\r\n try:\r\n # Loading the data\r\n df = pd.read_csv(file_name, encoding=\"latin\")\r\n except Exception:\r\n # File not found\r\n print(\"Scraped data not found! Please scrape data before continuing\")\r\n option = input(\"Scrape data? y/n: \")\r\n if option == \"y\":\r\n scraper = IMDBWebScraper()\r\n scraper.scrape_data()\r\n else:\r\n return\r\n\r\n if df is None:\r\n df = pd.read_csv(file_name, encoding=\"latin\")\r\n\r\n menu()\r\n # Main loop\r\n while True:\r\n print()\r\n print(\"-\" * 45, \"USER COMMAND\", \"-\" * 45)\r\n # Asking the user to input a command\r\n user_option = input(\"Enter Command: \")\r\n user_option = user_option.split(\" \", 1)\r\n # Making choice based on the users command\r\n if len(user_option) == 1:\r\n # Checking if length of input is 1\r\n user_option = user_option[0]\r\n # Checking which option user selected\r\n if user_option == \"scrape\":\r\n scraper = IMDBWebScraper()\r\n scraper.scrape_data()\r\n elif user_option == \"movies\":\r\n df_movies = df[\"Title\"]\r\n print()\r\n print(\"-\" * 40, \"THE LIST OF MOVIES ARE\", \"-\" * 40)\r\n for movie in df_movies:\r\n print(movie)\r\n elif user_option == \"directors\":\r\n df_directors = df[\"Director\"].unique()\r\n print(\"-\" * 40, \"THE LIST OF DIRECTORS ARE\", \"-\" * 40)\r\n for director in df_directors:\r\n print(director)\r\n\r\n elif user_option == \"table\":\r\n webbrowser.open('file://' + os.path.realpath('raw_movie_data.html'))\r\n print(\"Table Has Opened In Browser\")\r\n\r\n elif user_option == \"help\":\r\n menu()\r\n elif user_option == \"quit\":\r\n return\r\n else:\r\n print(\"Invalid Command, Type \\\"help\\\" to get a list of valid commands.\")\r\n elif len(user_option) == 2:\r\n # If length of the input is more than two\r\n user_option1 = user_option[0]\r\n user_option2 = user_option[1]\r\n # Checking which option the user has selected\r\n if user_option1 == \"movie_name\":\r\n df_movie = df[df[\"Title\"].str.lower() == user_option2.lower()]\r\n if not df_movie.empty:\r\n df_movie = df_movie.iloc[0]\r\n # Printing the details of the movie\r\n print()\r\n print(\"-\" * 40, \"MOVIE DETAILS ARE\", \"-\" * 40)\r\n print(\"Title:\", df_movie[\"Title\"])\r\n print(\"Rating:\", df_movie[\"Rating\"])\r\n print(\"Rating Count:\", df_movie[\"Rating Count\"])\r\n print(\"Director:\", df_movie[\"Director\"])\r\n print(\"Genre:\", df_movie[\"Genre\"])\r\n print(\"Year:\", df_movie[\"Year\"])\r\n print(\"Runtime:\", df_movie[\"Runtime\"], \"mins\")\r\n print(\"Budget:\", \"$\", df_movie[\"Budget\"])\r\n print(\"Movie Stars:\", df_movie[\"Stars\"].replace(\"|\", \" ,\"))\r\n print(\"Summary:\", df_movie[\"Summary\"])\r\n else:\r\n print()\r\n print(\"No movies found!\")\r\n elif user_option1 == \"movie_genre\":\r\n df_movies = df[df[\"Genre\"].str.lower() == user_option2.lower()]\r\n if not df_movies.empty:\r\n print()\r\n print(\"-\" * 40, \"MOVIES ARE\", \"-\" * 40)\r\n print(\"{:80s}{:15s}{:10s}{:10s}\".format(\"Title\", \"Genre\", \"Rating\", \"Year\"))\r\n for index, row in df_movies.iterrows():\r\n print(\"{:80s}{:15s}{:10s}{:10s}\".format(row[\"Title\"], row[\"Genre\"], str(row[\"Rating\"]), str(row[\"Year\"])))\r\n else:\r\n print()\r\n print(\"No movies found!\")\r\n elif user_option1 == \"movie_year\":\r\n # Converting year into integer\r\n user_option2 = np.int64(user_option2)\r\n # Getting row from the data frame\r\n df_movies = df[df[\"Year\"] == user_option2]\r\n if not df_movies.empty:\r\n print()\r\n print(\"-\" * 40, \"MOVIES ARE\", \"-\" * 40)\r\n print(\"{:80s}{:15s}{:10s}{:10s}\".format(\"Title\", \"Genre\", \"Rating\", \"Year\"))\r\n # Iterating rows of same year and displaying the results\r\n for index, row in df_movies.iterrows():\r\n print(\"{:80s}{:15s}{:10s}{:10s}\".format(row[\"Title\"], row[\"Genre\"], str(row[\"Rating\"]),\r\n str(row[\"Year\"])))\r\n else:\r\n print()\r\n print(\"No movies found!\")\r\n elif user_option1 == \"director_bio\":\r\n # Getting row with the director name\r\n director_row = df[df[\"Director\"] == user_option2]\r\n print()\r\n print(\"-\" * 25, \"DIRECTOR BIO\", \"-\" * 25)\r\n if len(director_row) > 0:\r\n # Printing the director bio\r\n print(director_row.iloc[0][\"Director Bio\"])\r\n else:\r\n print(\"No such director found\")\r\n elif user_option1 == \"top_rating\":\r\n # Sorting the data frame\r\n sorted_df = df.sort_values(by=[\"Rating\"], ascending=False)\r\n df_movies = sorted_df.iloc[:int(user_option2)]\r\n # Printing the top movies\r\n if not df_movies.empty:\r\n print()\r\n print(\"-\" * 40, \"TOP MOVIES ARE\", \"-\" * 40)\r\n print(\"{:60s}{:15s}\".format(\"Title\", \"Rating\"))\r\n for index, row in df_movies.iterrows():\r\n print(\"{:60s}{:15s}\".format(row[\"Title\"], str(row[\"Rating\"])))\r\n else:\r\n print()\r\n print(\"No movies found!\")\r\n elif user_option1 == \"top_budget\":\r\n # Sorting the data frame\r\n sorted_df = df.sort_values(by=[\"Budget\"], ascending=False)\r\n df_movies = sorted_df.iloc[:int(user_option2)]\r\n # Printing the top movies\r\n if not df_movies.empty:\r\n print()\r\n print(\"-\" * 40, \"TOP MOVIES ARE\", \"-\" * 40)\r\n print(\"{:60s}{:15s}\".format(\"Title\", \"Budget\"))\r\n for index, row in df_movies.iterrows():\r\n print(\"{:60s}{:15s}\".format(row[\"Title\"], str(row[\"Budget\"])))\r\n else:\r\n print()\r\n print(\"No movies found!\")\r\n elif user_option1 == \"graph\":\r\n # Printing the graphs\r\n if user_option2 == \"genre_pie\":\r\n genre_list = list(df[\"Genre\"])\r\n genre_dict = {}\r\n for genre in genre_list:\r\n if genre in genre_dict.keys():\r\n genre_dict[genre] += 1\r\n else:\r\n genre_dict[genre] = 1\r\n\r\n labels = list(genre_dict.keys())\r\n values = list(genre_dict.values())\r\n\r\n fig = go.Figure(data=[go.Pie(labels=labels, values=values)])\r\n fig.show()\r\n elif user_option2 == \"director_rating\":\r\n fig = px.scatter(df, x=\"Director\", y=\"Rating\")\r\n fig.show()\r\n elif user_option2 == \"year_rating\":\r\n fig = px.bar(df, x=\"Year\", y=\"Rating\")\r\n fig.show()\r\n elif user_option2 == \"run_budget\":\r\n fig = px.line(df, x=\"Title\", y=\"Budget\")\r\n fig.show()\r\n\r\n else:\r\n print(\"Invalid Command, Type \\\"help\\\" to get a list of valid commands.\")\r\n else:\r\n print(\"Invalid Command, Type \\\"help\\\" to get a list of valid commands.\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n#Have a good break!\r\n","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":21050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"471827802","text":"\"\"\"Collection of functions that will be used by the pysts module.\"\"\"\n\n\nfrom os import urandom\nfrom time import time\nfrom fractions import gcd as euclid_gcd\n\nfrom Crypto.Util import number as nutil\n\nfrom pysts.constants import GENERAL, SOCK, LEHMER_GCD\n\n\ndef primality_test(number):\n \"\"\"Test if recived number is a prime number\"\"\"\n if GENERAL.PRIME == \"deterministic\":\n return is_pseudoprime(number)\n\n elif GENERAL.PRIME == \"naive\":\n return is_prime(number)\n\n else:\n raise ValueError(\"Invalid value provided for GENERAL.PRIME !\")\n\n\ndef is_prime(number):\n \"\"\"Check if :param number: is prime\"\"\"\n\n number = abs(number)\n\n if number == 2 or number == 3:\n return True\n\n if int(number & 1) == 0 or number % 3 == 0:\n return False\n\n index = 5\n increment = 2\n limit = int(number ** 0.5) + 1\n start = time()\n\n while index < limit:\n if number % index == 0:\n return False\n\n index = index + increment\n increment = 6 - increment\n if int(time() - start) > 10:\n return True\n\n return True\n\n\ndef is_pseudoprime(number):\n \"\"\"\n Test whether recived number is prime using a variety of pseudoprime\n tests.\n \"\"\"\n\n if number in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]:\n return True\n\n test = euler_pseudoprime(number, 2)\n if not test:\n return False\n\n test = euler_pseudoprime(number, 3)\n if not test:\n return False\n\n test = euler_pseudoprime(number, 5)\n return test\n\n\ndef fermat_pseudoprime(number, base):\n \"\"\"\n Test whether recived number is prime or a Fermat pseudoprime to base base.\n \"\"\"\n return (pow(base, number - 1, number) == 1)\n\n\ndef euler_pseudoprime(number, base):\n \"\"\"\n Test whether number is prime or an Euler pseudoprime to base base.\n \"\"\"\n if not fermat_pseudoprime(number, base):\n return False\n\n power = number - 1\n while (power % 2 == 0):\n power //= 2\n\n test = pow(base, power, number)\n if (test == 1):\n return True\n\n while (1):\n if (test == 1):\n return False\n if (test == number - 1):\n return True\n test = pow(test, 2, number)\n\n\ndef pollard_rho(number):\n \"\"\"\n Pollard Rho is an integer factorization algorithm, which is quite fast\n for large numbers.\n \"\"\"\n\n if number % 2 == 0:\n return 2\n\n rand_y = nutil.getRandomRange(1, number - 1, urandom)\n rand_c = nutil.getRandomRange(1, number - 1, urandom)\n copy_y = rand_y\n\n index_g = 1\n\n while index_g == 1:\n rand_y = ((rand_y * rand_y) % number + rand_c) % number\n copy_y = ((copy_y * copy_y) % number + rand_c) % number\n copy_y = ((copy_y * copy_y) % number + rand_c) % number\n index_g = gcd(abs(rand_y - copy_y), number)\n\n return index_g\n\n\ndef brent_rho(number):\n \"\"\"\n Richard Brent variant of the rho algorithm\n\n Pollard's rho algorithm is a general-purpose integer factorization\n algorithm. It is particularly effective at splitting composite\n numbers with small factors.\n \"\"\"\n\n if number % 2 == 0:\n return 2\n\n rand_y = nutil.getRandomRange(1, number - 1, urandom)\n rand_c = nutil.getRandomRange(1, number - 1, urandom)\n rand_m = nutil.getRandomRange(1, number - 1, urandom)\n\n index_g, index_r, index_q = 1, 1, 1\n\n while index_g == 1:\n copy_y = rand_y\n index_k = 0\n\n index = 0\n while index < index_r:\n rand_y = ((rand_y * rand_y) % number + rand_c) % number\n index += 1\n\n while (index_k < index_r and index_g == 1):\n y_copy2 = rand_y\n index = 0\n limit = min(rand_m, index_r - index_k)\n\n while index < limit:\n rand_y = ((rand_y * rand_y) % number + rand_c) % number\n index_q = index_q * (abs(copy_y - rand_y)) % number\n index += 1\n\n index_g = gcd(index_q, number)\n index_k = index_k + rand_m\n\n index_r = index_r * 2\n\n if index_g == number:\n while True:\n y_copy2 = ((y_copy2 * y_copy2) % number + rand_c) % number\n index_g = gcd(abs(copy_y - y_copy2), number)\n if index_g > 1:\n break\n\n return index_g\n\n\ndef lehmer_gcd(first_val, second_val):\n \"\"\"Is a fast GCD algorithm, an improvement on the simpler but slower\n Euclidean algorithm. It is mainly used for big integers that have a\n representation as a string of digits relative to some chosen numeral\n system base\"\"\"\n\n if first_val < second_val:\n first_val, second_val = second_val, first_val\n\n while second_val >= LEHMER_GCD.BASE:\n size = len(\"{0:b}\".format(first_val)) - LEHMER_GCD.DIGIT_BITS\n\n copy_f = int(first_val >> size)\n copy_s = int(second_val >> size)\n\n temp_a, temp_b, temp_c, temp_d = 1, 0, 0, 1\n\n while True:\n if copy_s + temp_c == 0 or copy_s + temp_d == 0:\n break\n\n test = (copy_f + temp_a) // (copy_s + temp_c)\n if test != (copy_f + temp_b) // (copy_s + temp_d):\n break\n\n temp_a = temp_c\n temp_b = temp_d\n temp_c = temp_a - test * temp_c\n temp_d = temp_b - test * temp_d\n\n copy_f = copy_s\n copy_s = copy_f - test * copy_s\n\n if temp_b:\n first_val = temp_a * first_val + temp_b * second_val\n second_val = temp_c * first_val + temp_d * second_val\n else:\n first_val, second_val = second_val, first_val % second_val\n\n while second_val:\n first_val, second_val = int(second_val), int(first_val % second_val)\n\n return first_val\n\n\ndef phi(number):\n \"\"\"\n Euler's totient or phi function is an arithmetic function that counts\n the totatives of number\n \"\"\"\n amount = 0\n index = 1\n while index < number:\n if gcd(number, index) == 1:\n amount += 1\n return amount\n\n\ndef gcd(first_val, second_val):\n \"\"\"Returns GCD\"\"\"\n\n if GENERAL.GCD == \"euclid\":\n return euclid_gcd(first_val, second_val)\n elif GENERAL.GCD == \"lehmer\":\n return lehmer_gcd(first_val, second_val)\n else:\n raise ValueError(\"Invalid value for GENERAL.GCD\")\n\n\ndef read_data(connection):\n \"\"\"Read information from connection\"\"\"\n\n message, message_size = [], 0\n\n while message_size < SOCK.MAX_BUFFER_SIZE:\n chunk = connection.recv(SOCK.BUFFER_SIZE)\n if chunk:\n message.append(chunk)\n\n if len(chunk) < SOCK.BUFFER_SIZE:\n message = \"\".join(message)\n break\n\n else:\n # The buffer is too large\n raise ValueError(\"Request Entity Too Large\")\n\n if not message:\n raise ValueError(\"No response recived !\")\n\n return message\n\n\ndef debug(message):\n \"\"\"If debug flag is set will print message\"\"\"\n if GENERAL.DEBUG:\n print(message)\n","sub_path":"Licență/Anul III/SI/Station-to-Station Protocol & 3DES/pysts/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"582778196","text":"from dna_features_viewer import BiopythonTranslator, CircularGraphicRecord\nfrom Bio import Entrez, SeqIO\nimport moviepy.editor as mpe\nfrom moviepy.video.io.bindings import mplfig_to_npimage\nimport matplotlib.pyplot as plt\n\n\ncolor_map = {\n \"rep_origin\": \"yellow\",\n \"CDS\": \"orange\",\n \"regulatory\": \"red\",\n \"misc_recomb\": \"darkblue\",\n \"misc_feature\": \"lightblue\",\n}\n\ntranslator = BiopythonTranslator(\n features_filters=(lambda f: f.type not in [\"gene\", \"source\"],),\n features_properties=lambda f: {\"color\": color_map.get(f.type, \"white\")},\n)\n\ntranslator.max_line_length = 15\ngraphic_record = translator.translate_record(\n \"Genome.gb\", record_class=CircularGraphicRecord\n)\n\ngraphic_record.labels_spacing = 15\n\n\nax, _ = graphic_record.plot(figure_width=6, figure_height=6)\nax.figure.savefig(\"ACM_Circular_Genome_Representation.png\")\n\nduration = 5\n\n\ndef make_frame(t):\n top_nucleotide_index = t * graphic_record.sequence_length / duration\n graphic_record.top_position = top_nucleotide_index\n ax, _ = graphic_record.plot(figure_width=8, figure_height=8)\n ax.set_ylim(top=2)\n np_image = mplfig_to_npimage(ax.figure)\n plt.close(ax.figure)\n return np_image\n\nclip = mpe.VideoClip(make_frame, duration=duration)\nsmall_clip = clip.crop(x1=60, y1=180, x2=-60, y2=-100)\nsmall_clip.write_gif(\"circular_animation.gif\", fps=60)","sub_path":"python-gnome-visualizer.py","file_name":"python-gnome-visualizer.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610781019","text":"from imutils import face_utils\nimport dlib\nimport cv2\n# initialize dlib's face detector (HOG-based) and then create\n# the facial landmark predictor\n\ndetector = dlib.get_frontal_face_detector()\n\n# load the input image and convert it to grayscale\nimage = cv2.imread(\"grp9.jpg\")\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n# detect faces in the grayscale image\nrects = detector(gray, 0)\n\n# loop over the face detections\nfor (i, rect) in enumerate(rects):\n\t# determine the facial landmarks for the face region, then\n\t# convert the facial landmark (x, y)-coordinates to a NumPy\n\t# array\n\tprint(i, rect)\n\t\n\t# Window name in which image is displayed \n\twindow_name = 'Image'\n\t \n\t# Start coordinate, here (5, 5) \n\t# represents the top left corner of rectangle \n\tlis = []\n\tlis.append(rect.left())\n\tlis.append(rect.top())\n\tstart_point = tuple(map(int, lis))\n\t\n\t \n\t# Ending coordinate, here (220, 220) \n\t# represents the bottom right corner of rectangle \n\tlis = []\n\tlis.append(rect.right())\n\tlis.append(rect.bottom())\n\tend_point = tuple(map(int, lis))\n\n\t# Blue color in BGR \n\tcolor = (255, 0, 0) \n\t \n\t# Line thickness of 2 px \n\tthickness = 2\n\t \n\t# Using cv2.rectangle() method \n\t# Draw a rectangle with blue line borders of thickness of 2 px \n\t# i added this line for cropping the detected image\n\tcrop_img = image[start_point[1]:end_point[1], start_point[0]:end_point[0]]\n\t#image = cv2.rectangle(image, start_point, end_point, color, thickness) \n\n\n\nstatus = cv2.imwrite(r'C:\\Users\\ELCOT\\Desktop\\chan3.png', crop_img)\nif status:\n\tprint(\"Image saved sucessful\")\nelse:\n\tprint(\"Image save failed\")","sub_path":"Day/Day3/face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"603653598","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /tmp/pip-install-6brxc_kc/websockets/websockets/utils.py\n# Compiled at: 2020-03-24 13:42:06\n# Size of source mod 2**32: 376 bytes\nimport itertools\n__all__ = [\n 'apply_mask']\n\ndef apply_mask(data: bytes, mask: bytes) -> bytes:\n \"\"\"\n Apply masking to the data of a WebSocket message.\n\n :param data: Data to mask\n :param mask: 4-bytes mask\n\n \"\"\"\n if len(mask) != 4:\n raise ValueError('mask must contain 4 bytes')\n return bytes((b ^ m for b, m in zip(data, itertools.cycle(mask))))","sub_path":"pycfiles/pytigon-0.98-py3-none-any/utils.cpython-37.py","file_name":"utils.cpython-37.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"608110785","text":"# Copyright 2014 Deutsche Telekom AG\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\n\nimport mock\n\nfrom tempest import config\nimport tempest.test as test\nfrom tempest.tests import base\nfrom tempest.tests import fake_config\n\n\nclass TestNegativeAutoTest(base.TestCase):\n # Fake entries\n _interface = 'json'\n _service = 'compute'\n\n fake_input_desc = {\"name\": \"list-flavors-with-detail\",\n \"http-method\": \"GET\",\n \"url\": \"flavors/detail\",\n \"json-schema\": {\"type\": \"object\",\n \"properties\":\n {\"minRam\": {\"type\": \"integer\"},\n \"minDisk\": {\"type\": \"integer\"}}\n },\n \"resources\": [\"flavor\", \"volume\", \"image\"]\n }\n\n def setUp(self):\n super(TestNegativeAutoTest, self).setUp()\n self.useFixture(fake_config.ConfigFixture())\n self.stubs.Set(config, 'TempestConfigPrivate', fake_config.FakePrivate)\n\n def _check_prop_entries(self, result, entry):\n entries = [a for a in result if entry in a[0]]\n self.assertIsNotNone(entries)\n self.assertIs(len(entries), 2)\n for entry in entries:\n self.assertIsNotNone(entry[1]['schema'])\n\n def _check_resource_entries(self, result, entry):\n entries = [a for a in result if entry in a[0]]\n self.assertIsNotNone(entries)\n self.assertIs(len(entries), 3)\n for entry in entries:\n self.assertIsNotNone(entry[1]['resource'])\n\n @mock.patch('tempest.test.NegativeAutoTest.load_schema')\n def test_generate_scenario(self, open_mock):\n open_mock.return_value = self.fake_input_desc\n scenarios = test.NegativeAutoTest.\\\n generate_scenario(None)\n\n self.assertIsInstance(scenarios, list)\n for scenario in scenarios:\n self.assertIsInstance(scenario, tuple)\n self.assertIsInstance(scenario[0], str)\n self.assertIsInstance(scenario[1], dict)\n self._check_prop_entries(scenarios, \"prop_minRam\")\n self._check_prop_entries(scenarios, \"prop_minDisk\")\n self._check_resource_entries(scenarios, \"inv_res\")\n\n def test_load_schema(self):\n json_schema = json.dumps(self.fake_input_desc)\n with mock.patch('tempest.test.open',\n mock.mock_open(read_data=json_schema),\n create=True):\n return_file = test.NegativeAutoTest.load_schema('filename')\n self.assertEqual(return_file, self.fake_input_desc)\n return_dict = test.NegativeAutoTest.load_schema(self.fake_input_desc)\n self.assertEqual(return_file, return_dict)\n","sub_path":"tempest/tests/negative/test_negative_auto_test.py","file_name":"test_negative_auto_test.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"35478188","text":"'''\nHandler module for interacting with the mastermind API.\n\nBy separating this into its own module, we can keep things clear by\n\tkeeping the actual solving logic abstracted away from the\n\trequests, and by keeping the code clean.\n\nThe base of this module was provided by Praetorian on their\n\tmastermind page, but it was heavily edited by myself.\n\nAuthor:\tBlake Luther\n\t\tbluther@utexas.edu\n\t\tgithub.com/bluther\n'''\n\nimport requests\nimport json\n\nbaseurl = 'https://mastermind.praetorian.com/'\nemail = 'bluther@utexas.edu' # Change this!\n\nr = requests.post(baseurl + 'api-auth-token/', data={'email':email})\n# > {'Auth-Token': 'AUTH_TOKEN'}\nheaders = r.json()\nheaders['Content-Type'] = 'application/json'\n\n# Interacting with the game\n\ndef reset_game():\n\treseturl = baseurl + '/reset/'\n\tr = requests.post(reseturl, headers=headers)\n\tj = r.json()\n\treturn j\n\ndef get_new_level(levelnum):\n\t'''\n\tBegins a new game at level number levelnum, and \n\treturns the API's reponse as a dict.\n\t'''\n\tlevelurl = baseurl + 'level/' + str(levelnum) + '/'\n\tr = requests.get(levelurl, headers=headers)\n\t# > {'numGladiators': 4, 'numGuesses': 8, 'numRounds': 1, 'numWeapons': 6}\n\treturn r.json()\n\ndef submit_guess(levelnum, guess):\n\t'''\n\tTakes a list, guess, and submits that as the guess.\n\tReturns the API's response as a dict.\n\t'''\n\tlevelurl = baseurl + 'level/' + str(levelnum) + '/'\n\tr = requests.post(levelurl, headers=headers, data=json.dumps({'guess':guess}))\n\t# > {'response': [2, 1]}\n\treturn r.json()\n\ndef get_hash():\n\t'''\n\tChecks if the hash is available. If so, returns it.\n\tIf not available, returns None\n\t'''\n\thashurl = baseurl + 'hash/'\n\tr = requests.get(hashurl, headers=headers)\n\tj = r.json()\n\tif 'hash' in j.keys():\n\t\treturn j['hash']\n\telse:\n\t\treturn None","sub_path":"mastermindapi.py","file_name":"mastermindapi.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11989454","text":"'''A collection of tools for drawing and annotating mass spectra\n'''\n# pragma: no cover\nimport math\nimport itertools\n\nimport numpy as np\ntry:\n from matplotlib import pyplot as plt, gridspec\n from ms_peak_picker.plot import draw_peaklist, draw_raw\n has_plot = True\nexcept ImportError:\n import warnings\n warnings.warn(\"Could not import matplotlib, plotting tools will not work\")\n pyplot = None\n gridspec = None\n has_plot = False\n\n\ndef _default_color_cycle():\n c = plt.rcParams['axes.prop_cycle']\n colors = c.by_key().get(\"color\")\n if not colors:\n colors = [\n '#1f77b4',\n '#ff7f0e',\n '#2ca02c',\n '#d62728',\n '#9467bd',\n '#8c564b',\n '#e377c2',\n '#7f7f7f',\n '#bcbd22',\n '#17becf'\n ]\n return colors\n\n\ndef annotate_scan(scan, products, nperrow=4, ax=None, label=True):\n '''Given an MS1 :class:`~.ScanBase` ``scan`` and a :class:`~.Sequence` of\n :class:`~.ScanBase` product scans, draw the MS1 spectrum in full profile,\n and then in a subplot grid below it, draw a zoomed-in view of the MS1 spectrum\n surrounding the area around each precursor ion that gave rise to the scans in\n ``products``, with monoisotopic peaks and isolation windows marked.\n\n .. plot::\n :include-source:\n\n import ms_deisotope\n from ms_deisotope import plot\n from ms_deisotope.test.common import datafile\n\n reader = ms_deisotope.MSFileLoader(datafile(\"20150710_3um_AGP_001_29_30.mzML.gz\"))\n bunch = next(reader)\n\n bunch.precursor.pick_peaks()\n bunch.precursor.deconvolute(\n scorer=ms_deisotope.PenalizedMSDeconVFitter(20., 2.0),\n averagine=ms_deisotope.glycopeptide, use_quick_charge=True)\n\n ax = plot.annotate_scan(bunch.precursor, bunch.products, nperrow=2)\n ax.figure.set_figwidth(12)\n ax.figure.set_figheight(16)\n\n\n Parameters\n ----------\n scan: ScanBase\n The precursor MS1 scan\n products: :class:`~.Sequence` of :class:`~.ScanBase`\n The collection of MSn scans based upon ``scan``\n nperrow: int\n The number of precursor ion subplots to draw per row\n of the grid. Defaults to :const:`4`.\n ax: :class:`matplotlib._axes.Axes`\n An :class:`~.Axes` object to use to find the figure to\n draw the plot on.\n\n Returns\n -------\n :class:`matplotlib._axes.Axes`:\n The axes of the full MS1 profile plot\n '''\n if ax is None:\n figure = plt.figure()\n else:\n figure = ax.figure\n n = len(products)\n if n > 0:\n gs = gridspec.GridSpec(1 + max(int(math.ceil(n / float(nperrow))), 1), nperrow)\n else:\n gs = gridspec.GridSpec(1 + (n / nperrow), nperrow)\n ax = figure.add_subplot(gs[0, :])\n if scan.is_profile:\n draw_raw(scan.arrays, ax=ax)\n if scan.peak_set is None:\n scan.pick_peaks()\n draw_peaklist(scan.peak_set, ax=ax, lw=0.5, alpha=0.75)\n if scan.deconvoluted_peak_set:\n draw_peaklist(scan.deconvoluted_peak_set, ax=ax, lw=0.5, alpha=0.75)\n ax.set_title(scan.id)\n k = -1\n # for the ith row of the grid\n for i in range(int(n // nperrow) + 1):\n # for the jth column of the row\n for j in range(nperrow):\n # the kth MS^n scan\n k += 1\n try:\n product_scan = products[k]\n except IndexError:\n # the number of MS^n scans is not a multiple of nperrow\n # so the last row has fewer than nperrow\n break\n # add the subplot from the grid spec using i + 1 instead of i\n # because the MS1 scan is drawn across the row at i = 0\n ax = figure.add_subplot(gs[i + 1, j])\n if scan.is_profile:\n draw_raw(scan.arrays, ax=ax, alpha=0.8)\n # obtain the interval around the precursor\n pinfo = product_scan.precursor_information\n if not product_scan.isolation_window.is_empty():\n lower, upper = (product_scan.isolation_window.lower_bound - 2,\n product_scan.isolation_window.upper_bound + 2)\n else:\n lower = pinfo.mz - 4\n upper = pinfo.mz + 4\n try:\n peak = max(scan.peak_set.between(lower + 1.2, upper - 1.2), key=lambda x: x.intensity)\n local_intensity = peak.intensity\n except ValueError:\n if scan.deconvoluted_peak_set:\n try:\n peak = max(scan.deconvoluted_peak_set.between(lower + 1.2, upper - 1.2),\n key=lambda x: x.intensity, use_mz=True)\n local_intensity = peak.intensity\n except ValueError:\n local_intensity = 1e3\n else:\n local_intensity = 1e3\n\n # get the monoisotopic peak for the precursor, or the isolation center depending\n # upon whether the precursor has been deconvoluted and what the instrument reports\n if pinfo.extracted_charge != 0:\n target_mz = pinfo.extracted_mz\n else:\n target_mz = pinfo.mz\n\n draw_peaklist(scan.peak_set, ax=ax, alpha=0.5, lw=0.5)\n if scan.deconvoluted_peak_set:\n draw_peaklist(\n scan.deconvoluted_peak_set.between(\n lower - 1.2, upper + 1.2, use_mz=True),\n ax=ax, alpha=0.9, color='blue')\n\n if label:\n label_peaks(scan, lower, upper, ax=ax,\n is_deconvoluted=bool(scan.deconvoluted_peak_set))\n ax.set_ylim(0, local_intensity * 1.25)\n ax.set_xlim(lower, upper)\n upper_intensity = local_intensity\n\n # draw the precursor isolation annotations\n ax.vlines(target_mz, 0, upper_intensity * 1.5, alpha=0.50,\n color='red', lw=1)\n if product_scan.isolation_window.lower != 0:\n ax.vlines(product_scan.isolation_window.lower_bound, 0,\n upper_intensity * 1.5, linestyle='--', alpha=0.5)\n if product_scan.isolation_window.upper != 0:\n ax.vlines(product_scan.isolation_window.upper_bound, 0,\n upper_intensity * 1.5, linestyle='--', alpha=0.5)\n ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n ax.set_ylabel(\"\")\n ax.set_xlabel(\"\")\n if pinfo.extracted_charge == 0:\n if pinfo.charge == \"ChargeNotProvided\":\n charge = '?'\n else:\n charge = str(pinfo.charge)\n else:\n charge = str(pinfo.extracted_charge)\n ax.set_title(\"%0.3f @ %s\" % (target_mz, charge))\n fig = figure\n # this should probably be a function of figwidth and number of rows\n fig.set_figheight(fig.get_figheight() * 2)\n fig.tight_layout()\n return ax\n\n\ndef annotate_scan_single(scan, product_scan, ax=None, label=True, standalone=True):\n '''Draw a zoomed-in view of the MS1 spectrum ``scan`` surrounding the\n area around each precursor ion that gave rise to ``product_scan``\n with monoisotopic peaks and isolation windows marked.\n\n .. plot::\n :include-source:\n\n import ms_deisotope\n from ms_deisotope import plot\n from ms_deisotope.test.common import datafile\n\n reader = ms_deisotope.MSFileLoader(datafile(\"20150710_3um_AGP_001_29_30.mzML.gz\"))\n bunch = next(reader)\n\n bunch.precursor.pick_peaks()\n bunch.precursor.deconvolute(\n scorer=ms_deisotope.PenalizedMSDeconVFitter(20., 2.0),\n averagine=ms_deisotope.glycopeptide, use_quick_charge=True)\n\n ax = plot.annotate_scan_single(bunch.precursor, bunch.products[0])\n ax.figure.set_figwidth(12)\n\n\n\n Parameters\n ----------\n scan: ScanBase\n The MS1 scan to annotate\n product_scan: ScanBase\n The product scan to annotate the precursor ion of\n ax: :class:`matplotlib._axes.Axes`\n An :class:`~.Axes` object to draw the plot on\n\n Returns\n -------\n :class:`matplotlib._axes.Axes`\n '''\n if ax is None:\n _, ax = plt.subplots(1)\n\n if scan.is_profile:\n draw_raw(scan.arrays, ax=ax)\n if scan.peak_set is None:\n scan.pick_peaks()\n draw_peaklist(scan.peak_set, ax=ax, lw=0.5, alpha=0.75)\n if scan.deconvoluted_peak_set:\n draw_peaklist(scan.deconvoluted_peak_set, ax=ax, lw=0.5, alpha=0.75)\n\n pinfo = product_scan.precursor_information\n if not product_scan.isolation_window.is_empty():\n lower, upper = (product_scan.isolation_window.lower_bound - 2,\n product_scan.isolation_window.upper_bound + 2)\n else:\n lower = pinfo.mz - 4\n upper = pinfo.mz + 4\n\n peak_set = scan.peak_set\n try:\n peak = max(peak_set.between(lower + 1.2, upper - 1.2), key=lambda x: x.intensity)\n local_intensity = peak.intensity\n except ValueError:\n if scan.deconvoluted_peak_set:\n try:\n peak = max(scan.deconvoluted_peak_set.between(lower + 1.2, upper - 1.2),\n key=lambda x: x.intensity, use_mz=True)\n local_intensity = peak.intensity\n except ValueError:\n local_intensity = 1e3\n else:\n local_intensity = 1e3\n\n # get the monoisotopic peak for the precursor, or the isolation center depending\n # upon whether the precursor has been deconvoluted and what the instrument reports\n if pinfo.extracted_charge != 0:\n target_mz = pinfo.extracted_mz\n else:\n target_mz = pinfo.mz\n\n draw_peaklist(scan.peak_set, ax=ax, alpha=0.5, lw=0.5)\n if scan.deconvoluted_peak_set:\n draw_peaklist(\n scan.deconvoluted_peak_set.between(\n lower - 1.2, upper + 1.2, use_mz=True),\n ax=ax, alpha=0.9, color='blue')\n\n if label:\n label_peaks(scan, lower, upper, ax=ax,\n is_deconvoluted=bool(scan.deconvoluted_peak_set))\n\n ax.set_ylim(0, local_intensity * 1.25)\n ax.set_xlim(lower, upper)\n upper_intensity = local_intensity\n\n # draw the precursor isolation annotations\n ax.vlines(target_mz, 0, upper_intensity * 1.5, alpha=0.50,\n color='red', lw=1)\n if product_scan.isolation_window.lower != 0:\n ax.vlines(product_scan.isolation_window.lower_bound, 0,\n upper_intensity * 1.5, linestyle='--', alpha=0.5)\n if product_scan.isolation_window.upper != 0:\n ax.vlines(product_scan.isolation_window.upper_bound, 0,\n upper_intensity * 1.5, linestyle='--', alpha=0.5)\n ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n ax.set_ylabel(\"\")\n ax.set_xlabel(\"\")\n if pinfo.extracted_charge == 0:\n if pinfo.charge == \"ChargeNotProvided\":\n charge = '?'\n else:\n charge = str(pinfo.charge)\n else:\n charge = str(pinfo.extracted_charge)\n ax.set_title(\"%0.3f @ %s\" % (target_mz, charge))\n\n return ax\n\n\ndef annotate_isotopic_peaks(scan, ax=None, color_cycle=None, **kwargs):\n '''Mark distinct isotopic peaks from the :class:`~.DeconvolutedPeakSet`\n in ``scan``.\n\n .. plot::\n :include-source:\n\n import ms_deisotope\n from ms_deisotope import plot\n from ms_deisotope.test.common import datafile\n\n reader = ms_deisotope.MSFileLoader(datafile(\"20150710_3um_AGP_001_29_30.mzML.gz\"))\n bunch = next(reader)\n\n bunch.precursor.pick_peaks()\n bunch.precursor.deconvolute(\n scorer=ms_deisotope.PenalizedMSDeconVFitter(20., 2.0),\n averagine=ms_deisotope.glycopeptide, use_quick_charge=True)\n\n ax = plot.draw_peaklist(bunch.precursor, color='black')\n ax = plot.annotate_isotopic_peaks(bunch.precursor, ax=ax)\n ax.set_xlim(1160, 1165)\n ax.figure.set_figwidth(12)\n\n\n Parameters\n ----------\n scan: ScanBase\n The scan to annotate\n color_cycle: :class:`~.Iterable`\n An iterable to draw isotopic cluster colors from\n ax: :class:`matplotlib._axes.Axes`\n An :class:`~.Axes` object to draw the plot on\n\n Returns\n -------\n :class:`matplotlib._axes.Axes`\n '''\n from .peak_set import DeconvolutedPeakSet\n\n if ax is None:\n _, ax = plt.subplots(1)\n if color_cycle is None:\n color_cycle = _default_color_cycle()\n color_cycle = itertools.cycle(color_cycle)\n if isinstance(scan, DeconvolutedPeakSet):\n peaks = scan\n else:\n peaks = getattr(scan, \"deconvoluted_peak_set\", [])\n for peak in peaks:\n color = next(color_cycle)\n draw_peaklist(peak.envelope, ax=ax, color=color, alpha=0.75, **kwargs)\n ax.scatter(*zip(*peak.envelope), color=color, alpha=0.75)\n return ax\n\n\ndef label_peaks(scan, min_mz=None, max_mz=None, ax=None, is_deconvoluted=None, threshold=None, **kwargs):\n \"\"\"Label a region of the peak list, marking centroids with their m/z or mass. If the peaks\n of `scan` have been deconvoluted, the most abundant peak will be annotated with\n \" ()\", otherwise just \"\".\n\n Parameters\n ----------\n scan : :class:`~.ScanBase`\n The scan to annotate\n min_mz : float, optional\n The minimum m/z to annotate\n max_mz : float, optional\n The maximum m/z to annotate\n ax: :class:`matplotlib._axes.Axes`\n An :class:`~.Axes` object to draw the plot on\n is_deconvoluted : bool, optional\n Whether or not to always use :attr:`Scan.deconvoluted_peak_set`\n threshold : float, optional\n The intensity threshold under which peaks will be ignored\n\n Returns\n -------\n ax: :class:`matplotlib._axes.Axes`\n The axes the plot was drawn on\n annotations: :class:`list` of :class:`matplotlib.text.Text`\n The list of :class:`matplotlib.text.Text` annotations\n \"\"\"\n if ax is None:\n # when no axes are provided, draw all the peak data\n _, ax = plt.subplots(1)\n if scan.is_profile:\n draw_raw(scan, ax)\n if scan.peak_set is not None:\n draw_peaklist(scan.peak_set, ax)\n if scan.deconvoluted_peak_set is not None:\n draw_peaklist(scan.deconvoluted_peak_set, ax)\n if is_deconvoluted is None:\n is_deconvoluted = scan.deconvoluted_peak_set is not None\n if min_mz is None:\n min_mz = 0\n if max_mz is None:\n if is_deconvoluted:\n max_mz = max(peak.mz for peak in scan.deconvoluted_peak_set)\n else:\n max_mz = max(peak.mz for peak in scan.peak_set)\n annotations = []\n # select the peak sub range\n if is_deconvoluted:\n subset = scan.deconvoluted_peak_set.between(\n min_mz, max_mz, use_mz=True)\n else:\n subset = scan.peak_set.between(\n min_mz, max_mz)\n if not subset:\n return\n # guess the threshold\n if threshold is None:\n threshold = 0.0\n if is_deconvoluted:\n threshold_list = ([max(i.intensity for i in p.envelope)\n for p in subset])\n else:\n threshold_list = ([p.intensity for p in subset])\n if threshold_list:\n threshold = np.mean(threshold_list)\n threshold_list = [v > threshold for v in threshold_list]\n if threshold_list:\n threshold = np.mean(threshold_list)\n # draw the actual labels\n kwargs.setdefault(\"clip_on\", True)\n kwargs.setdefault(\"fontsize\", 10)\n if is_deconvoluted:\n for peak in subset:\n if peak.intensity > threshold:\n label = '%0.2f (%d)' % (peak.neutral_mass, peak.charge)\n # set the y-position to the highest peak in the isotopic\n # pattern\n pt = max(peak.envelope, key=lambda x: x.intensity)\n y = pt.intensity * 1.05\n # set the x-position to the weighted average m/z in the\n # isotopic pattern\n x = np.average(\n [p.mz for p in peak.envelope],\n weights=[p.intensity for p in peak.envelope])\n annotations.append(\n ax.text(x, y, label, ha='center', **kwargs))\n else:\n for peak in subset:\n if peak.intensity > threshold:\n label = \"%0.2f\" % (peak.mz, )\n y = peak.intensity * 1.05\n x = peak.mz\n annotations.append(\n ax.text(x, y, label, ha='center', **kwargs))\n return annotations, ax\n\n\ndef draw_spectrum_paths(graph, edge_color='red', peak_color='orange', alpha=0.8, fontsize=12, ax=None, **kwargs):\n \"\"\"Draw all the paths given by `graph` over a rendered peak list.\n\n This function will draw all peaks which an edge connects in `peak_color`, and\n draws edges as lines connecting peaks in `edge_color`, with their annotations\n written across them.\n\n If a peak is not connected to an edge, it will not be drawn.\n\n Parameters\n ----------\n graph : :class:`~.SpectrumGraph` or :class:`list` of :class:`~.spectrum_graph.Path`\n The paths to annotate. If a :class:`~.SpectrumGraph` is given, the top 100 longest\n paths will be enumerated from it.\n edge_color : str, optional\n The color to draw the edge lines in (the default is 'red')\n peak_color : str, optional\n The color to draw the connected peaks in (the default is 'orange')\n alpha : float, optional\n The alpha channel value for peaks (the default is 0.8)\n fontsize : int, optional\n The font size to use for edge annotations (the default is 12)\n ax : :class:`matplotlib._axes.Axes`, optional\n The axes to draw the plot on (the default is None, which will cause a new figure with a\n single axes to be created)\n\n Returns\n -------\n :class:`matplotlib._axes.Axes`\n \"\"\"\n if ax is None:\n _, ax = plt.subplots(1)\n try:\n paths = graph.longest_paths(limit=100)\n except AttributeError:\n paths = list(graph)\n\n for path in paths:\n for edge in path:\n for p1 in edge.start:\n for p2 in edge.end:\n _draw_peak_pair(\n (p1, p2), edge_color, peak_color, alpha, fontsize,\n label=edge.annotation, ax=ax, **kwargs)\n\n\ndef _draw_peak_pair(pair, edge_color='red', peak_color='orange', alpha=0.8, fontsize=12, label=None, rotation=45,\n ax=None, **kwargs):\n p1, p2 = pair\n ax.plot((p1.mz, p2.mz), (p1.intensity, p2.intensity),\n color=edge_color, alpha=alpha, **kwargs)\n kwargs.setdefault(\"clip_on\", False)\n clip_on = kwargs['clip_on']\n draw_peaklist(pair, ax=ax, alpha=0.4, color=peak_color)\n if label:\n midx = (p1.mz + p2.mz) / 2\n # interpolate the midpoint's height\n midy = (p1.intensity * (p2.mz - midx) +\n p2.intensity * (midx - p1.mz)) / (p2.mz - p1.mz)\n\n # find the angle of the line connecting the two peaks\n xlo = min(p1.mz, p2.mz)\n xhi = max(p1.mz, p2.mz)\n adj = xhi - xlo\n ylo = min(p1.intensity, p2.intensity)\n yhi = max(p1.intensity, p2.intensity)\n opp = yhi - ylo\n hypot = np.hypot(adj, opp) # pylint: disable=assignment-from-no-return\n rotation = np.arccos(adj / hypot) # pylint: disable=assignment-from-no-return\n\n if isinstance(label, (list, tuple)):\n label = '-'.join(map(str, label))\n else:\n label = str(label)\n ax.text(midx, midy, label, fontsize=fontsize,\n ha='center', va='bottom', rotation=rotation, clip_on=clip_on)\n","sub_path":"ms_deisotope/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":19903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115922063","text":"import wave\nimport struct\nfrom scipy import fromstring, int16\nimport numpy as np\n\nwav = '01 Flyers!!!.wav'\nwr = wave.open(wav, 'r')\n\nch = wr.getnchannels()\nwidth = wr.getsampwidth()\nfr = wr.getframerate()\nfn = wr.getnframes()\n\ndata = wr.readframes(wr.getnframes())\nwr.close()\n\nX = fromstring(data, dtype=int16)\n\nsongs = {'flyers':0.50039}\n\ntime = songs['flyers']\nframes = int(ch * fr * time)\n\noutf = \"test.wav\"\nY = np.concatenate((np.zeros(frames,dtype=int16),X))\noutd = struct.pack('h' * len(Y), *Y)\n\nww = wave.open(outf, 'w')\nww.setnchannels(ch)\nww.setsampwidth(width)\nww.setframerate(fr)\nww.writeframes(outd)\nww.close()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616713462","text":"\"\"\"\nConcatenate measures with different parameters in one dataframe\n\"\"\"\n\nimport sys\nimport pandas as pd\n\ndelay_mode_intra = \"null\"\ndelay_mode_inter = \"null\"\nintra_params = [1.5]\ninter_params = [1.5]\nv_stim = 4.0\nmetric = \"training\"\nnetworks = [\"topo\", \"random\"]\n\n# use the homogeneous delay condition as the control condition\ndfs = []\n# df = pd.read_csv(\"data/sum/pre/{}_intra=null_inter=null.csv\".format(metric))\nfor network in networks:\n # df = pd.read_csv('data/sum/pre/{}_intra={}_inter={}.csv'.format(metric,delay_mode_intra,delay_mode_inter))\n df = pd.read_csv('data/sum/diff_v_stim/{}_{}_intra=1.5_inter=1.5_v_stim={}.csv'.\n format(metric, network, v_stim), keep_default_na=False)\n df[\"intra type\"] = delay_mode_intra\n df[\"inter type\"] = delay_mode_inter\n df[\"intra params\"] = \"null\"\n df[\"inter params\"] = \"null\"\n df['double conn'] = 'null'\n df['skip delays'] = 'null'\n df['skip weights'] = 'null'\n dfs.append(df)\n\n# add all the other datas\nfor network_mode in networks:\n for intra_p in intra_params:\n for inter_p in inter_params:\n # df = pd.read_csv('data/sum/{}_{}_intra={}{}_inter={}{}.csv'.\n # format(metric, network_mode, delay_mode_intra, intra_p, delay_mode_inter, inter_p),\n # keep_default_na=False)\n for skip_double in [str(True), str(False)]:\n for skip_p in [1.5, 3.0]:\n for skip_w in [1.0, 0.5]:\n df = pd.read_csv('data/sum/{}_{}_intra={}{}_inter={}{}_skip_double={}_d={}_w={}.csv'.\n format(metric, network_mode, delay_mode_intra, intra_p, delay_mode_inter, inter_p, skip_double, skip_p, skip_w))\n df[\"intra type\"] = delay_mode_intra\n df[\"inter type\"] = delay_mode_inter\n df[\"intra params\"] = intra_p\n df[\"inter params\"] = inter_p\n df['double conn'] = skip_double\n df['skip delays'] = skip_p\n df['skip weights'] = skip_w\n dfs.append(df)\n\n# # noise condition does not depend on v_stim\n# df = pd.read_csv('data/sum/pre/{}_intra={}_inter={}.csv'.format(metric, delay_mode_intra, delay_mode_inter),\n# keep_default_na=False)\n# df = df[df['network type']=='noise']\n# dfs.append(df)\n\n# concatenate all dataframes into one and save them\nultimate = pd.concat(dfs, sort=False)\nultimate.to_csv(\"data/sum/{}_intra={}_inter={}.csv\".format(metric, delay_mode_intra, delay_mode_inter), index=False)","sub_path":"concat.py","file_name":"concat.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"441945441","text":"import nlp_model_v3 as rev_sent\n\n\ndef run_one(input_text):\n\tsent, conf = rev_sent.sentiment(input_text)\n\tif sent == 'pos':\n\t\tresult = 'positive'\n\telse:\n\t\tresult = 'negative'\n\tprint(\n\t\t\"The review was %s, with a confidence of: %s %%\" % (result, str(conf * 100)))\n\nwhile True:\n\tuser_input = input(\"Enter review: \")\n\tif user_input != '':\n\t\trun_one(user_input)\n\telse:\n\t\tbreak\n","sub_path":"review_tester.py","file_name":"review_tester.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354936458","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/archetypes/schematuning/tests/test_storage.py\n# Compiled at: 2010-01-22 07:59:46\n\"\"\"\n\"\"\"\nfrom Products.Archetypes.tests.attestcase import ATTestCase\nfrom Products.Archetypes.atapi import *\nfrom Products.Archetypes.tests.test_classgen import Dummy\nfrom Products.Archetypes.tests.test_classgen import gen_dummy\nfrom DateTime import DateTime\nfrom archetypes.schematuning.tests.base import SchemaTuningTestCase\n\nclass ChangeStorageTest(SchemaTuningTestCase):\n __module__ = __name__\n\n def afterSetUp(self):\n gen_dummy()\n self._dummy = dummy = Dummy(oid='dummy')\n self._dummy.initializeArchetype()\n self._old_storages = {}\n\n def test_changestorage(self):\n dummy = self._dummy\n dummy.setAtextfield('sometext', mimetype='text/plain')\n dummy.setAdatefield('2003-01-01')\n dummy.setAlinesfield(['bla', 'bla', 'bla'])\n dummy.setAnobjectfield('someothertext')\n out = ('bla', 'bla', 'bla')\n self.failUnlessEqual(str(dummy.getAtextfield()), 'sometext')\n self.failUnlessEqual(dummy.getAdatefield(), DateTime('2003-01-01'))\n self.failUnlessEqual(dummy.getAlinesfield(), out)\n self.failUnlessEqual(dummy.getAnobjectfield(), 'someothertext')\n for field in dummy.schema.fields():\n if field.getName() in ['atextfield', 'adatefield', 'alinesfield', 'anobjectfield']:\n self._old_storages[field.getName()] = field.getStorage()\n field.setStorage(dummy, AttributeStorage())\n self.failUnlessEqual(field.getStorage().getName(), 'AttributeStorage')\n field.setStorage(dummy, MetadataStorage())\n self.failUnlessEqual(field.getStorage().getName(), 'MetadataStorage')\n\n dummy.invalidateSchema()\n self.failUnlessEqual(str(dummy.getAtextfield()), 'sometext')\n self.failUnlessEqual(dummy.getAdatefield(), DateTime('2003-01-01'))\n self.failUnlessEqual(dummy.getAlinesfield(), out)\n self.failUnlessEqual(dummy.getAnobjectfield(), 'someothertext')\n\n def test_unset(self):\n dummy = self._dummy\n dummy.setAtextfield('sometext')\n field = dummy.getField('atextfield')\n field.setStorage(dummy, AttributeStorage())\n self.failUnless(hasattr(dummy, 'atextfield'))\n field.setStorage(dummy, MetadataStorage())\n self.failIf(hasattr(dummy, 'atextfield'))\n self.failUnless(dummy._md.has_key('atextfield'))\n field.setStorage(dummy, AttributeStorage())\n self.failIf(dummy._md.has_key('atextfield'))\n self.failUnless(hasattr(dummy, 'atextfield'))\n\n\nclass MetadataStorageTest(ATTestCase):\n __module__ = __name__\n\n def afterSetUp(self):\n gen_dummy()\n self._dummy = dummy = Dummy(oid='dummy')\n self._dummy.initializeArchetype()\n for field in dummy.schema.fields():\n if field.getName() in ['atextfield', 'adatefield', 'alinesfield', 'anobjectfield']:\n field.setStorage(dummy, MetadataStorage())\n\n\nclass AttributeStorageTest(ATTestCase):\n __module__ = __name__\n\n def afterSetUp(self):\n gen_dummy()\n self._dummy = dummy = Dummy(oid='dummy')\n self._dummy.initializeArchetype()\n for field in dummy.schema.fields():\n if field.getName() in ['atextfield', 'adatefield', 'alinesfield', 'anobjectfield']:\n field.setStorage(dummy, AttributeStorage())\n\n\ndef test_suite():\n from unittest import TestSuite, makeSuite\n suite = TestSuite()\n suite.addTest(makeSuite(ChangeStorageTest))\n suite.addTest(makeSuite(MetadataStorageTest))\n suite.addTest(makeSuite(AttributeStorageTest))\n return suite","sub_path":"pycfiles/archetypes.schematuning-1.2-py2.4/test_storage.py","file_name":"test_storage.py","file_ext":"py","file_size_in_byte":3858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"587730861","text":"from commonfunctions import *\n\n\ndef getNearestLine(y, lines):\n diff = lines - y\n # get min difference disregarding the sign\n min_pos = np.argmin(np.abs(diff))\n #get closes line position\n closest_line = lines[min_pos]\n #get line above if negative and below if positive \n distance = diff[min_pos]\n \n closest_line_pos = np.where(lines == closest_line)[0][0] % 5\n \n return closest_line, closest_line_pos, distance\n\ndef getBeamNoteHeads(img, boundingRect, staffHeight, spaceHeight):\n \n (min_x,min_y,max_x,max_y) = boundingRect\n w = max_x - min_x\n h = max_y - min_y\n \n contourImage = img[min_y:max_y, min_x:max_x]\n \n kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(staffHeight * 2, 1))\n contourImage = cv2.morphologyEx(contourImage, cv2.MORPH_OPEN, kernel)\n \n \n # hist[i,0] -> size, hist[i,1] -> x, hist[i,2] -> min y, hist[i,3] -> max y \n hist = np.zeros((w,4), dtype=np.uint32)\n \n for i in range(w):\n window = contourImage[:, i: min(i + 1, w)]\n # show_images([window])\n # xprojection = np.sum(window, axis=1)\n xprojection = window\n # xprojection = np.where(xprojection>spaceHeight//4, 1,0)\n\n starts = np.array((xprojection[:-1] == 0) & (xprojection[1:] != 0))\n starts_ix = np.where(starts)[0] + 1\n ends = np.array((xprojection[:-1] != 0) & (xprojection[1:] == 0))\n ends_ix = np.where(ends)[0]\n\n if xprojection[0] != 0:\n starts_ix = np.append(0, starts_ix)\n\n if xprojection[-1] != 0:\n ends_ix = np.append(ends_ix, xprojection.size-1)\n\n if starts_ix.size != 0:\n index = np.argmax(ends_ix - starts_ix)\n hist[i,1] = min_x + i\n hist[i,2] = min_y + starts_ix[index]\n hist[i,3] = min_y + ends_ix[index]\n length = hist[i,3] - hist[i,2]\n if 0.75*spaceHeight < length < spaceHeight*1.5:\n hist[i,0] = length\n \n peaks, _ = find_peaks(hist[:,0], distance=spaceHeight)\n \n hists = hist[peaks]\n mean_y = np.mean((hists[:,2] + hists[:,3])//2) - min_y\n beams = 0\n if mean_y > h/2:\n beams = getNumberOfBeams(contourImage[:np.min(hists[:,2])-min_y])\n else:\n beams = getNumberOfBeams(contourImage[np.max(hists[:,3]) - min_y:])\n \n# print(mean_y, h)\n# print(hists)\n return hists, beams\n\ndef getHeadCharacter(top, distanceTop, bottom, distanceBottom, spaceHeight):\n# print(top,bottom,distanceTop,distanceBottom)\n if top == 3 and bottom == 4:\n if -distanceBottom >= 0.25 * spaceHeight:\n return 'e'\n if distanceTop >= 0.25 * spaceHeight:\n return 'g'\n return 'f'\n elif top == 2 and bottom == 3:\n if -distanceBottom >= 0.25 * spaceHeight:\n return 'g'\n if distanceTop >= 0.25 * spaceHeight:\n return 'b'\n return 'a'\n elif top == 1 and bottom == 2:\n if -distanceBottom >= 0.25 * spaceHeight:\n return 'b'\n if distanceTop >= 0.25 * spaceHeight:\n return 'd2'\n return 'c2'\n elif top == 0 and bottom == 1:\n if -distanceBottom >= 0.25 * spaceHeight:\n return 'd2'\n if distanceTop >= 0.25 * spaceHeight:\n return 'f2'\n return 'e2'\n \n if top == 3 and bottom == 3 and distanceTop > 0 and distanceBottom < 0:\n return 'g'\n elif top == 2 and bottom == 2 and distanceTop > 0 and distanceBottom < 0:\n return 'b'\n elif top == 1 and bottom == 1 and distanceTop > 0 and distanceBottom < 0:\n return 'd2'\n \n if top == 4 and bottom == 4:\n if distanceTop >= 0.25 * spaceHeight:\n return 'e'\n else:\n if -distanceTop <= 0.25 * spaceHeight:\n return 'd'\n else:\n return 'c'\n \n if top == 0 and bottom == 0:\n if -distanceBottom >= 0.25 * spaceHeight:\n return 'f2'\n if distanceTop <= 1.35 * spaceHeight:\n return 'g2'\n if distanceBottom <= 0.75 * spaceHeight:\n return 'a2'\n else:\n return 'b2'\n\n if top == 0 and bottom == 2:\n return 'd2'\n elif top == 1 and bottom == 3:\n return 'b'\n elif top == 2 and bottom == 4:\n return 'g'\n \n \ndef getNumberOfBeams(contour):\n# show_images([contour])\n width = contour.shape[1]\n height = contour.shape[0]\n\n hist = np.zeros((height//2,), dtype=np.uint32)\n for i in range(width):\n a = contour[:,i]\n starts = np.array((a[:-1] == 0) & (a[1:] != 0))\n starts_ix = np.where(starts)[0] + 2\n ends = np.array((a[:-1] != 0) & (a[1:] == 0))\n ends_ix = np.where(ends)[0] + 2\n\n if a[0] != 0:\n starts_ix = np.append(1, starts_ix)\n\n if a[-1] != 0:\n ends_ix = np.append(ends_ix, a.size+1)\n \n runs = ends_ix - starts_ix\n hist[runs.size] += 1 \n \n return np.argmax(hist)\n\ndef getNoteCharacter(originalImage, boundingRect, noteClass, lines, staffHeight, spaceHeight):\n img = originalImage.copy()\n \n (min_x,min_y,max_x,max_y) = boundingRect\n w = max_x - min_x\n h = max_y - min_y\n \n contourImage = img[min_y:max_y, min_x:max_x]\n \n\n character = ''\n \n if noteClass == 'a_1':\n noteTop = min_y\n noteBottom = max_y\n _, top, distanceTop = getNearestLine(noteTop,lines)\n _, bottom, distanceBottom = getNearestLine(noteBottom,lines)\n character = getHeadCharacter(top, distanceTop, bottom, distanceBottom, spaceHeight)\n character += '/1'\n\n elif noteClass == 'a_2':\n yprojection = np.sum(contourImage//255, axis=0)\n yprojection = np.where(yprojection>spaceHeight + 2*staffHeight)\n contourImage[:,yprojection] = 0\n \n a = np.sum(contourImage//255, axis=1)\n \n starts = np.array((a[:-1] == 0) & (a[1:] != 0))\n starts_ix = np.where(starts)[0] + 1\n ends = np.array((a[:-1] != 0) & (a[1:] == 0))\n ends_ix = np.where(ends)[0]\n\n if a[0] != 0:\n starts_ix = np.append(0, starts_ix)\n\n if a[-1] != 0:\n ends_ix = np.append(ends_ix, a.size-1)\n\n if starts_ix.size != 0:\n index = np.argmax(ends_ix - starts_ix)\n noteTop = min_y + starts_ix[index]\n noteBottom = min_y + ends_ix[index]\n \n _, top, distanceTop = getNearestLine(noteTop,lines)\n _, bottom, distanceBottom = getNearestLine(noteBottom,lines)\n character = getHeadCharacter(top, distanceTop, bottom, distanceBottom, spaceHeight)\n character += '/2'\n\n elif noteClass == 'a_4' or noteClass == 'a_8' or noteClass == 'a_16' or noteClass == 'a_32':\n# show_images([contourImage])\n yprojection = np.sum(contourImage//255, axis=0)\n yprojection = np.where(yprojection>spaceHeight+2*staffHeight)\n contourImage[:,yprojection] = 0\n \n hist = np.zeros((w,4), dtype=np.uint32)\n \n for i in range(w):\n window = contourImage[:, i: min(i + 1, w)]\n # show_images([window])\n # xprojection = np.sum(window, axis=1)\n xprojection = window\n # xprojection = np.where(xprojection>spaceHeight//4, 1,0)\n\n starts = np.array((window[:-1] == 0) & (window[1:] != 0))\n starts_ix = np.where(starts)[0] + 1\n ends = np.array((window[:-1] != 0) & (window[1:] == 0))\n ends_ix = np.where(ends)[0]\n\n if window[0] != 0:\n starts_ix = np.append(0, starts_ix)\n\n if window[-1] != 0:\n ends_ix = np.append(ends_ix, window.size-1)\n\n if starts_ix.size != 0:\n index = np.argmax(ends_ix - starts_ix)\n hist[i,1] = i\n hist[i,2] = starts_ix[index]\n hist[i,3] = ends_ix[index]\n length = hist[i,3] - hist[i,2]\n if 0.75*spaceHeight < length < spaceHeight*1.5:\n hist[i,0] = length\n \n peaks, _ = find_peaks(hist[:,0], distance=spaceHeight)\n widths = peak_widths(hist[:,0], peaks)[0]\n \n peakIndex = np.argmax(widths)\n peak = peaks[peakIndex]\n h = hist[peak]\n noteTop = min_y + h[2]\n noteBottom = min_y + h[3]\n _, top, distanceTop = getNearestLine(noteTop,lines)\n _, bottom, distanceBottom = getNearestLine(noteBottom,lines)\n character = getHeadCharacter(top, distanceTop, bottom, distanceBottom, spaceHeight)\n if noteClass == 'a_4':\n character += '/4'\n elif noteClass == 'a_8':\n character += '/8'\n elif noteClass == 'a_16':\n character += '/16'\n else:\n character += '/32'\n elif noteClass == \"beam\":\n heads, noOfBeams = getBeamNoteHeads(img, boundingRect, staffHeight, spaceHeight)\n division = int(8*noOfBeams)\n for h in heads:\n _, top, distanceTop = getNearestLine(h[2],lines)\n _, bottom, distanceBottom = getNearestLine(h[3],lines)\n character += getHeadCharacter(top, distanceTop, bottom, distanceBottom, spaceHeight)\n character += '/' + str(division) + ' '\n character = character[:-1]\n \n return character","sub_path":"notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":9318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"19056355","text":"from ths.nn.sequences.processcnnw import ProcessTweetsCNN\n\ndef main():\n print(\"Working:\")\n #P = ProcessTweetsWord2VecOnePass2DCNNv2_1(\"data/cleantextlabels3.csv\", \"trained/embedding3.csv\")\n P = ProcessTweetsCNN(\"data/cleantextlabels7.csv\", \"data/glove.6B.50d.txt\")\n #P = ProcessTweetsWord2VecTwoPassLSTMv2_1(\"data/cleantextlabels4.csv\", \"trained/embedding3-50d.csv\")\n\n #Bueno el model12cnnv2\n # Excelente el de modellstmatt1 con attention\n # El mejor fue modellstmatt2 con attention\n # also good modellstmatt3\n # el 4 con dropout\n # 2, 3 y 4 son buenos\n P.process(\"trained/modelcnnincepw6.json\", \"trained/modelcnnincepw6.h5\", plot=False, epochs=20)\n#joderme\nif __name__ == \"__main__\":\n main()","sub_path":"ths/test/testcnnw.py","file_name":"testcnnw.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88950603","text":"import time\nfrom selenium.webdriver.common.by import By\nfrom driver.browser import chrome_driver\nfrom page.base_page import BasePage\nfrom page.login_page import LoginCase\nfrom test_case.test_login import LoginTestCase\n\nclass BusinessCase(BasePage):\n def __init__(self,driver):\n # super().__init__()\n self.driver = driver\n # self.url = \"http://192.168.1.120/index.php?m=user&a=login\"\n # self.driver.get(url=self.url)\n\n #元素定位符\n self.dw_into_bus = (By.LINK_TEXT,'商机') #进入商机页面\n self.dw_add_bus = (By.CSS_SELECTOR,'div[class=\"pull-right\"]>a') #添加商机\n self.dw_bus_name = (By.ID,'name') #商机名\n self.dw_yprice = (By.ID, 'estimate_price') #预计成交价\n self.dw_customer = (By.ID, 'customer_name') #点击选择客户\n self.dw_customer_xz = (By.XPATH, '//tbody[@id=\"datas\"]/tr[4]/td[1]/input[1]') #选择客户\n self.dw_customer_ok = (By.CSS_SELECTOR, 'div[id=\"dialog-message\"]+div>div :nth-child(1)') #点击ok\n self.dw_responsible = (By.ID, 'owner_name') #点击选择负责人\n self.dw_responsible_xz = (By.XPATH, '//tbody[@id=\"d_content\"]/tr[1]/td[1]/input') #选择负责人\n self.dw_responsible_ok = (By.CSS_SELECTOR, 'div[id=\"dialog-role-list\"]+div>div :nth-child(1)') #点击ok\n self.dw_product = (By.XPATH, '//form[@id=\"form1\"]/table/tbody/tr[12]/th/input') #点击添加产品\n self.dw_product_xz = (By.XPATH, '//tbody[@id=\"data\"]/tr[1]/td[1]/input[1]') #选择产品\n self.dw_product_ok = (By.CSS_SELECTOR, 'div[id=\"dialog-product-list\"]+div>div :nth-child(1)') #点击ok\n self.dw_preservation = (By.XPATH, '//form[@id=\"form1\"]/table/tfoot/tr/td/input[1]') #保存\n self.dw_duanyan = (By.XPATH, '/html/body/div[5]/div[2]')\n\n def ele_into_bus(self):\n self.driver.find_element(*self.dw_into_bus).click()\n\n def ele_add_bus(self):\n self.driver.find_element(*self.dw_add_bus).click()\n\n def ele_bus_name(self,bus_name):\n self.driver.find_element(*self.dw_bus_name).send_keys(bus_name)\n\n def ele_yprice(self,yprice):\n self.driver.find_element(*self.dw_yprice).send_keys(yprice)\n\n def ele_customer(self):\n self.driver.find_element(*self.dw_customer).click() # 选择客户\n self.driver.find_element(*self.dw_customer_xz).click()\n self.driver.find_element(*self.dw_customer_ok).click()\n\n def ele_responsible(self):\n self.driver.find_element(*self.dw_responsible).click() # 选择负责人\n self.driver.find_element(*self.dw_responsible_xz).click()\n self.driver.find_element(*self.dw_responsible_ok).click() # 点击OK\n\n def ele_add_product(self):\n self.driver.find_element(*self.dw_product).click() # 添加产品\n self.driver.find_element(*self.dw_product_xz).click()\n self.driver.find_element(*self.dw_product_ok).click() # 点击OK\n\n def ele_preservation(self):\n self.driver.find_element(*self.dw_preservation).click() # 点击保存\n\n def add_bus_opp(self,bus_name,yprice):\n self.ele_into_bus()\n self.ele_add_bus()\n self.ele_bus_name(bus_name)\n self.ele_yprice(yprice)\n self.ele_customer()\n self.ele_responsible()\n self.ele_add_product()\n self.ele_preservation()\n time.sleep(2)\n shiji = self.driver.find_element(*self.dw_duanyan).text\n time.sleep(1)\n# self.quit()\n return shiji\n\n# bus = BusinessCase()\n# bus.add_bus_opp(\"王辉商机4号\",\"13322\")","sub_path":"page/business_page.py","file_name":"business_page.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"501131616","text":"#-------------------------------菜单项如下: 1. 求五个数的和; 2. 求五个数的平均值; ... (X). 退出------------------\n#-------------------------------由用户输入选择, 程序执行相应的功能----------------------\nimport os\nimport time\n\n#接收五个数字-1\ndef fiveN():\n print(\"Please Enter Five Number:\")\n num = 0\n i = 0\n while i<5:\n num+=int(input())\n i+=1\n return num\n#接收五个数字-2\ndef fiven():\n #raw_input()是定义在python2中的python3不兼容\n s = input(\"Please Enter Five number:\")\n l = []\n ls = s.split(\" \")\n i = 0\n print(len(ls))\n while i <= len(ls)+2:\n print(l)\n print(i)\n l.append(int(ls.pop()))\n i+=1\n i = 0\n num = 0\n while i <= len(l)+1:\n num+=l[i]\n i+=1\n return num\n\nwhile True:\n print(\"*****************************************************\")\n print(\"*************** 1. 求五个数的和 ***************\")\n print(\"*************** 2. 求五个数的平均值 ***************\")\n print(\"*************** x. 退出 **************\")\n print(\"*****************************************************\")\n n = input(\"请选择:\")\n if n == '1':\n num = fiven()\n print(\"五个数的和为:\"+str(num))\n time.sleep(1) \n os.system(\"cls\")\n elif n == '2':\n num = fiven()\n print(\"这五个数的平均值为:\"+str(num/5))\n time.sleep(0.5) \n os.system(\"cls\")\n elif n=='x':\n print(\"Bye Bye!\")\n time.sleep(1) \n os.system(\"cls\")\n break\n else:\n n = input(\"Sorry Enter Error,Enter Again:\")\n time.sleep(1) \n os.system(\"cls\")\n continue\n ","sub_path":"Python/10_28/带文本的.py","file_name":"带文本的.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"328061665","text":"# -*- coding: utf-8 -*-\nimport sys,os\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../support'))\nimport mongodb_util, mysql_util\n\ndef check_funding_gongshang(keyWord,investorIds):\n gongshang_companies=[] #[{code,id,name}]\n for company in mongodb_util.get_companyFullname_by_gongshang(keyWord):\n fullName = company['name']\n companies = mysql_util.get_company_by_fullName(fullName)\n for i in companies:\n if i not in gongshang_companies:gongshang_companies.append(i)\n\n funding_companies=[]\n if not isinstance(investorIds, list):investorIds=[investorIds]\n for investorId in investorIds:\n for company in mysql_util.get_company_by_funding_investor(investorId):\n if company not in funding_companies: funding_companies.append(company)\n\n cnt=0\n result=[]\n for company in gongshang_companies:\n if company not in funding_companies:\n # print 'code:%s,name:%s,companyId:%s,'%(company['code'],company['name'],company['companyId'])\n result.append(company['companyId'])\n cnt+=1\n\n # print 'gongshang_companies has %s, funding_companies has %s'%( len(gongshang_companies),len(funding_companies))\n # print cnt\n return result\n\n# return companyid list\nif __name__ == \"__main__\":\n check_funding_gongshang('戈壁',149)\n","sub_path":"data/spider2/aggregator/gongshang/check_gongshang.py","file_name":"check_gongshang.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"321530781","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# sample SAM/NSRDB code available here:\n# https://sam.nrel.gov/samples\n# https://developer.nrel.gov/docs/solar/pvwatts-v5/\n# https://nsrdb.nrel.gov/api-instructions\n# https://sam.nrel.gov/sdk\n\n# note: this script can be run piecemeal from iPython/Jupyter, or all-at-once from the command line\n\n# NOTE: this uses pandas DataFrames for most calculations, and breaks the work into batches\n# to avoid exceeding available memory (e.g., do one load zone worth of projects at a time,\n# then calculate one grid cell at a time and add it to the relevant projects). However, this\n# makes the code complex and the logic unclear, so it would probably be better to use a database,\n# where everything can be calculated at once in one query. (e.g. get a list of grid cells for all\n# projects from the database, then calculate cap factor for each grid cell and store it incrementally\n# in a cell cap factor table, then run one query which joins project -> project cell -> cell to\n# get hourly cap factors for all projects. This could use temporary tables for the cells, which\n# are then discarded.\n\n# NOTE: this stores all the hourly capacity factors in the postgresql database. That makes it\n# difficult to share with others. An alternative would be to store a separate text file for each\n# technology for each day and sync those via github. Disadvantages of that: querying is more complex\n# and we have to specify a reference time zone before saving the data (day boundaries are time zone\n# specific). Alternative: store in postgresql and publish a dump of the database.\n\nfrom __future__ import print_function, division\nfrom __future__ import absolute_import\nimport os, re, sys, struct, ctypes, datetime, time\nfrom collections import OrderedDict\nimport numpy as np\nimport pandas as pd\nimport dateutil.tz # should be available, since pandas uses it\nimport sqlalchemy\n\nfrom k_means import KMeans\nfrom util import execute, executemany, switch_db, pg_host, copy_dataframe_to_table\nimport shared_tables\n\n# number of digits that latitude and longitude should be rounded to before matching\n# to the nsrdb files\nlat_lon_digits = 2\n# location of main database directory relative to this script file\ndatabase_rel_dir = '../Resource Assessment'\n# location of nsrdb hourly data files relative to the main database directory\n# all subdirectories of this one will be scanned for data files\nnsrdb_dir = 'NSRDB Hourly Irradiance Data'\n# pattern to match lat and lon in nsrdb file name (all matching files will\n# be read for that site, e.g., for multiple years); this should specify\n# named groups for at least 'lat' and 'lon'.\n# note: we don't try too hard to match an exact pattern of digits and symbols\n# (just use .* for each group). If the expressions can't be parsed, we let them\n# generate errors later.\nnsrdb_file_regex = re.compile(r'^(?P.*)_(?P.*)_(?P.*)_(?P.*)[.]csv$')\n\n# load zone for which data is being prepared\n# TODO: add load zone to cluster input file\n# TODO: make tracking_pv code work with multiple load_zones\nload_zone = 'Oahu'\nload_zones = [load_zone]\n\n\n# Set PV system parameters\n# module_type: 0=standard, 1=premium, 2=thin film; we use a reasonable value (probably default)\n# pre-inverter losses and inverter efficiency from NREL 2019 ATB, pp. 22, 28 and 38 of\n# https://www.nrel.gov/docs/fy19osti/72399.pdf\n# degradation is effect of 0.75%/year losses (from NREL 2019 ATB), averaged over 30 years\n# (see \"Generator Info/PSIP 2016-12 ATB 2019 generator data.xlsx\")\nstd_pv_config = dict(\n module_type=0,\n inv_eff=98,\n losses=100 * (1 -\n (1 - 0.095) # pre-inverter\n * (1 - 0.1015) # average degradation over panel life\n )\n)\ndef pv_settings(d):\n # add data from dict-like object d to std_pv_config, and return the resulting dict\n result = std_pv_config.copy()\n result.update(d)\n return result\n# These system-specific settings will be assigned below:\n# azimuth: degrees from north (0)\n# tilt: in degrees from flat (0)\n# array_type: 0=fixed rack, 1=fixed roof, 2=single-axis, 3=single-axis backtracked\n# gcr: ground cover ratio (may be used for backtrack and shading calculations)\n# dc_ac_ratio: DC (panel) rating vs. AC (inverter) rating of system\n\n# def dict_add(d, **kwargs):\n# d = d.copy()\n# d.update(kwargs)\n# return d\n\n# Available roof area calibrated to Project Sunroof data for Oahu:\n# our roof inventory from Google map images gives 60208422 m2 in Oahu,\n# [all_cells.reset_index().query(\"load_zone=='Oahu'\")['roof_area'].sum()]\n# and Google Sunroof reports 25991040 m2 of panel potential on Oahu\n# So we assume that share (43.17%) of roof areas could have panels.\nroof_panel_frac = 25991040. / 60208422.\n# Within this, Project Sunroof reports roof directions as shown below (see\n# \"Switch-Hawaii/data/Resource Assessment/GIS/Rooftop PV/Project Sunroof/\n# project sunroof Oahu slope analysis.ipynb\"). The dataframe also shows\n# the central angle for the azimuth quadrant (0=North), the assumed tilt\n# of panels and the assumed ground cover ratio (gcr) for PVWatts. Note that\n# gcr is only used to calculate shading, not coverage/capacity. This is\n# appropriate since it is the percent coverage within the panel-covered regions,\n# but isn't meant to account for other regions of the roof that have no panels.\n# roof_panel_frac shows the percent coverage of all roof area.\n\n# We assume panels on flat roofs are sloped at 5 degrees and panels on sloped\n# roofs are tilted at 25 degrees, matching 2019 ATB\n# (https://atb.nrel.gov/electricity/2019/index.html?t=sd and\n# https://atb.nrel.gov/electricity/2019/index.html?t=sr)\n# (can use np.nan here to assign latitude instead, probably need gcr=0.7 then).\n# NREL 2019 ATB gets parameters from Fu et al. 2018 (https://www.nrel.gov/docs/fy19osti/72399.pdf).\n# We assume a DC/AC ratio of 1.15, based on pp. 22 and 28 of Fu et al. 2018 and\n# panel efficiency for commercial and residential systems from pp. 17 and 25 of Fu et al. 2018.\n\n# (based on California systems installed in 2016), from pp. 28 and 19 of\n# https://www.nrel.gov/docs/fy17osti/68925.pdf\n\nconfigs = pd.DataFrame.from_records(\n [\n ('FlatDistPV', 'f', 0.406397, 0.191, 180, 0, 5, 0.9, 1.15),\n ('SlopedDistPV', 'n', 0.133257, 0.172, 0, 1, 25, 0.9, 1.15),\n ('SlopedDistPV', 'e', 0.143570, 0.172, 90, 1, 25, 0.9, 1.15),\n ('SlopedDistPV', 's', 0.163764, 0.172, 180, 1, 25, 0.9, 1.15),\n ('SlopedDistPV', 'w', 0.153012, 0.172, 270, 1, 25, 0.9, 1.15)\n ],\n columns=[\n 'technology', 'orientation', 'roof_fraction', 'panel_efficiency',\n 'azimuth', 'array_type', 'tilt', 'gcr', 'dc_ac_ratio'\n ]\n).set_index('technology')\n\n# We assume that panels within each quadrant are evenly distributed between the cardinal\n# direction and +/- 30 degrees from that. (Oahu has street grids oriented in a variety of\n# directions, with no clear preference for any particular azimuth.)\ndist_pv_configs = pd.concat([configs] * 3).sort_values('orientation')\ndist_pv_configs['azimuth'] = (\n dist_pv_configs['azimuth'] + np.tile([-30, 0, 30], configs.shape[0])\n).mod(360)\n# account for actual coverage and splitting each quadrant into 3 tranches\ndist_pv_configs['roof_fraction'] = roof_panel_frac * dist_pv_configs['roof_fraction'] / 3\n# convert SAM settings into a dictionary and drop other columns\ndist_pv_configs['settings'] = \\\n dist_pv_configs.loc[:, 'azimuth':'dc_ac_ratio'].apply(pv_settings, axis=1)\ndist_pv_configs = \\\n dist_pv_configs.loc[:, ['orientation', 'roof_fraction', 'panel_efficiency', 'settings']]\n\n# Notes for utility-scale PV:\n# TODO: calculate performance for each 10m cell separately, then aggregate\n# (allows use of exact slopes, but requires much more calculation;\n# better to use current approach, with 1% slope bands)\n# TODO: use southward ground slope for tracking PV, latitude as slope for fixed PV\n# TODO: calculate rooftop PV in all areas with roofs (similar to fixed PV, but\n# using roof area instead of suitable land, and more different slope bands;\n# flat-roof systems seem to be tilted to match latitude -\n# http://www.recsolar.com/commercial-solar-project-examples/)\n\n# tuple of technology name and array_type for pvwatts\n# note: Appendix F of 2016-04-01 PSIP uses 2 for tracking, but 3 (backtracking) seems like a better choice.\n# note: p. v of http://www.nrel.gov/docs/fy13osti/56290.pdf says projects < 20 MW use 7.6/8.7 acres/MWac,\n# but Waianae Solar project on Oahu uses 4/5 acres per MW(DC), which equates to 6/7.5 acres per MW(AC)\n# with dc/ac ratio of 1.5 (they may be using less). See e-mail from M Fripp to Todd Kanja 12:47 2016-07-08 HST.\n# These densities correspond roughly to the lower quartile of land-use intensity for small projects, shown on\n# p. 11 of http://www.nrel.gov/docs/fy13osti/56290.pdf, so we also use the upper-quartile of the ground cover ratio\n# (GCR, packing factor) for all PV projects, shown on p. 13.\n# note: Appendix F uses 7.6/8.7 acres per MW(AC) (fixed/tracking)(?) and gcr=0.4, which seems less valid for Oahu.\n# We assume a DC/AC ratio of 1.3, based on p. 38 of https://www.nrel.gov/docs/fy19osti/72399.pdf\n# and https://atb.nrel.gov/electricity/2019/index.html?t=su\n# Also note: Aloha Solar on Oahu uses 22 acres for a 5 MWac project (4.4 acres/MWac): https://dbedt.hawaii.gov/hcda/files/2017/12/KAL-17-017-ASEF-II-Development-Permit-Application.pdf\ncentral_solar_techs = pd.DataFrame.from_records(\n [\n # ('CentralFixedPV', 6, 180, 0, np.nan, 0.68, 1.3), # not used so far, omit for speed\n ('CentralTrackingPV', 7.5, 180, 3, 0, 0.45, 1.3),\n ],\n columns=[\n 'technology', 'acres_per_mw', 'azimuth', 'array_type', 'tilt', 'gcr', 'dc_ac_ratio'\n ]\n)\n# note: tilt=np.nan means use cell latitude\n\n# 1 / [(m2/acre) * (acre/mw)]\ncentral_solar_techs['mw_per_m2'] = (1.0 / (4046.86 * central_solar_techs['acres_per_mw']))\n# convert SAM settings into a dictionary and drop other columns\ncentral_solar_techs['settings'] = (\n central_solar_techs.loc[:, 'azimuth':'dc_ac_ratio'].apply(pv_settings, axis=1)\n)\ncentral_solar_techs = central_solar_techs.loc[:, ['technology', 'mw_per_m2', 'settings']]\ncentral_solar_techs.set_index('technology', inplace=True)\n#central_solar_techs.loc['CentralTrackingPV', 'settings']['gcr']\n\n# find the database directory and System Advisor Model\ntry:\n curdir = os.path.dirname(__file__)\nexcept NameError:\n # no __file__ variable; we're copying and pasting in an interactive session\n curdir = os.getcwd()\n pd.set_option('display.width', 200)\n\ndatabase_dir = os.path.normpath(os.path.join(curdir, database_rel_dir))\nif not os.path.exists(database_dir):\n raise RuntimeError(\"Unable to find database directory at \" + database_dir)\n\n\ndef module_setup():\n # run code that is needed to setup the module\n # We call it from here so it can be at the top of the file, but still executed\n # after all the functions below are defined. It can't be called from main()\n # because sometimes functions from this module are imported into other scripts, and\n # main() is never called.\n\n # setup database\n global db_engine\n db_engine = sqlalchemy.create_engine('postgresql://' + pg_host + '/' + switch_db)\n\n # make lists of all available NSRDB data files\n # and years to accumulate data for\n global nsrdb_file_dict, years\n nsrdb_file_dict, years = get_nsrdb_file_dict()\n # years = [2007, 2008]\n\n # load System Advisor Model components\n global ssc, pvwatts\n ssc, pvwatts = load_sam()\n\n\ndef main():\n tracking_pv()\n distributed_pv()\n\n\ndef load_sam():\n # # location of System Advisor Model SDK relative to this script file\n # sam_sdk_rel_dir = 'System Advisor Model'\n # sam_sdk_dir = os.path.normpath(os.path.join(curdir, sam_sdk_rel_dir))\n # if not os.path.exists(sam_sdk_dir):\n # raise RuntimeError(\"Unable to find System Advisor Model (SAM) SDK directory at \" + sam_sdk_dir)\n\n # # Load the System Advisor Model (SAM) SDK API\n # # Note: SAM SDK can be downloaded from https://sam.nrel.gov/sdk\n # # nsrdb/sam code is based on examples in sscapi.py itself\n # # Also see https://nsrdb.nrel.gov/api-instructions and sam-sdk/ssc_guide.pdf\n #\n # # preload ssc library, so sscapi won't fail if it's not in the library search path\n # if sys.platform == 'win32' or sys.platform == 'cygwin':\n # if 8 * struct.calcsize(\"P\") == 64:\n # path = ['win64', 'ssc.dll']\n # else:\n # path = ['win32', 'ssc.dll']\n # elif sys.platform == 'darwin':\n # path = ['osx64', 'ssc.dylib']\n # elif sys.platform == 'linux2':\n # path = ['linux64', 'ssc.so']\n # else:\n # raise RuntimeError('Unsupported operating system: {}'.format(sys.platform))\n # ssc_dll = ctypes.CDLL(os.path.join(sam_sdk_dir, *path))\n #\n # # add search path to sscapi.py\n # sys.path.append(os.path.join(sam_sdk_dir, 'languages', 'python'))\n # import sscapi\n # ssc = sscapi.PySSC()\n # pvwatts5 = ssc.module_create(\"pvwattsv5\")\n # ssc.module_exec_set_print(0)\n\n # note: PySAM (requires Python 3.5+) is available via\n # conda install -c nrel nrel-pysam\n # or pip install nrel-pysam\n # currently using 1.2.1 and pvwattsv5\n # could upgrade to 2.1.4 and pvwattsv7\n from PySAM.PySSC import PySSC\n ssc = PySSC()\n pvwatts = ssc.module_create(b\"pvwattsv5\")\n ssc.module_exec_set_print(0)\n\n return ssc, pvwatts\n\n\ndef tracking_pv():\n # note: this uses global nsrdb_file_dict and years variables\n\n cluster_cell = pd.read_csv(\n db_path('GIS/Utility-Scale Solar Sites/solar_cluster_nsrdb_grid_final.csv'),\n index_col='gridclstid'\n )\n cluster_cell = cluster_cell[cluster_cell['solar_covg']>0]\n cell = cluster_cell.groupby('nsrdb_id')\n cluster = cluster_cell.groupby('cluster_id')\n cluster_total_solar_area = cluster['solar_area'].sum()\n\n cluster_ids = list(cluster.groups.keys()) # list of all cluster ids, for convenience\n cluster_id_digits = len(str(max(cluster_ids))) # max number of digits for a cluster id\n # site_ids for each cluster_id (these distinguish PV sites from wind sites that may have the same number)\n site_ids = ['PV_' + str(cluster_id).zfill(cluster_id_digits) for cluster_id in cluster_ids]\n\n # calculate weighted average lat and lon for each cluster\n # (note: the axis=0 and axis=1 keep pandas from generating lots of nans due to\n # trying to match column name in addition to row index)\n cluster_coords = pd.concat([\n cluster_cell['cluster_id'],\n cluster_cell[['solar_lat', 'solar_lon']].multiply(cluster_cell['solar_area'], axis=0)\n ], axis=1).groupby('cluster_id').sum().div(cluster_total_solar_area, axis=0)\n cluster_coords.columns=['latitude', 'longitude']\n\n # get list of technologies to be defined\n technologies = central_solar_techs.index.values\n\n # calculate capacity factors for all projects\n\n # This dict will hold vectors of capacity factors for each cluster for each year and technology.\n # This arrangement is simpler than using a DataFrame because we don't yet know the\n # indexes (timesteps) of the data for each year.\n cluster_cap_factors = dict()\n for tech in technologies:\n # go through all the needed nsrdb cells and add them to the capacity factor for the\n # relevant cluster and year\n print(\"Calculating capacity factors for {} cells (abt 1 min.).\".format(tech))\n for i, (cell_id, grp) in enumerate(cell):\n # print('{}/{}'.format(i, len(cell)))\n # grp has one row for each cluster that uses data from this cell\n lat = round_coord(grp['nsrdb_lat'].iloc[0])\n lon = round_coord(grp['nsrdb_lon'].iloc[0])\n settings = central_solar_techs.loc[tech, 'settings'].copy()\n if np.isnan(settings['tilt']):\n # nan flag set for tilt; use latitude\n settings['tilt'] = lat\n\n for year in years:\n cap_factors = get_cap_factors(nsrdb_file_dict[lat, lon, year], settings)\n # note: iterrows() would convert everything to a single (float) series, but itertuples doesn't\n for clst in grp.itertuples():\n contrib = cap_factors * clst.solar_area / cluster_total_solar_area[clst.cluster_id]\n key = (tech, clst.cluster_id, year)\n if key in cluster_cap_factors:\n cluster_cap_factors[key] += contrib\n else:\n cluster_cap_factors[key] = contrib\n\n # get timesteps for each year (based on lat and lon of first cell in the list)\n timesteps = dict()\n lat = round_coord(cluster_cell['nsrdb_lat'].iloc[0])\n lon = round_coord(cluster_cell['nsrdb_lon'].iloc[0])\n for year in years:\n timesteps[year] = get_timesteps(nsrdb_file_dict[(lat, lon, year)])\n\n # make an index of all timesteps\n timestep_index = pd.concat([pd.DataFrame(index=x) for x in timesteps.values()]).index.sort_values()\n\n # make a single dataframe to hold all the data\n cap_factor_df = pd.DataFrame(\n index=timestep_index,\n columns=pd.MultiIndex.from_product([technologies, site_ids]),\n dtype=float\n )\n\n # assign values to the dataframe\n for ((tech, cluster_id, year), cap_factors) in cluster_cap_factors.items():\n cap_factor_df.update(pd.DataFrame(\n cap_factors,\n index=timesteps[year],\n columns=[(tech, 'PV_' + str(cluster_id).zfill(cluster_id_digits))]\n ))\n cap_factor_df.columns.names = ['technology', 'site']\n cap_factor_df.index.names=['date_time']\n\n # add load_zone and orientation to the index\n cap_factor_df['load_zone'] = load_zone\n cap_factor_df['orientation'] = 'na'\n cap_factor_df.set_index(['load_zone', 'orientation'], append=True, inplace=True)\n # convert to database orientation, with natural order for indexes,\n # but also keep as a DataFrame\n cap_factor_df = pd.DataFrame(\n {'cap_factor': cap_factor_df.stack(cap_factor_df.columns.names)}\n )\n # sort table, then switch to using z, t, s, o as index (to match with project table)\n cap_factor_df = cap_factor_df.reorder_levels(\n ['load_zone', 'technology', 'site', 'orientation', 'date_time']\n ).sort_index().reset_index('date_time')\n\n # make a dataframe showing potential projects (same structure as 'projects' table)\n # note: for now we don't really handle multiple load zones and we don't worry about orientation\n # (may eventually have projects available with different azimuth and slope)\n # This concatenates a list of DataFrames, one for each technology\n project_df = pd.concat([\n pd.DataFrame(dict(\n load_zone=load_zone,\n technology=tech,\n site=site_ids,\n orientation='na',\n gen_capacity_limit_mw=cluster_total_solar_area*central_solar_techs.loc[tech, 'mw_per_m2'],\n latitude=cluster_coords['latitude'],\n longitude=cluster_coords['longitude'],\n ))\n for tech in technologies\n ], axis=0).set_index(['load_zone', 'technology', 'site', 'orientation'])\n\n\n # store data in postgresql tables\n shared_tables.create_table('projects')\n execute(\"DELETE FROM projects WHERE technology IN %s;\", [tuple(technologies)])\n project_df.to_sql('projects', db_engine, if_exists='append')\n\n # retrieve the project IDs (created automatically in the database)\n project_ids = pd.read_sql(\n \"SELECT project_id, load_zone, technology, site, orientation \"\n + \"FROM projects WHERE technology IN %(techs)s;\",\n db_engine, index_col=['load_zone', 'technology', 'site', 'orientation'],\n params={'techs': tuple(technologies)}\n )\n cap_factor_df['project_id'] = project_ids['project_id']\n\n # convert date_time values into strings for insertion into postgresql.\n # Inserting a timezone-aware DatetimeIndex into postgresql fails; see\n # http://stackoverflow.com/questions/35435424/pandas-to-sql-gives-valueerror-with-timezone-aware-column/35552061\n # note: the string conversion is pretty slow\n cap_factor_df['date_time'] = pd.DatetimeIndex(cap_factor_df['date_time']).strftime(\"%Y-%m-%d %H:%M:%S%z\")\n\n # Do we need error checking here? If any projects aren't in cap_factor_df, they'll\n # create single rows with NaNs (and any prior existing cap_factors for them will\n # get dropped below).\n # If any rows in cap_factor_df aren't matched to a project, they'll go in with\n # a null project_id.\n\n shared_tables.create_table('variable_capacity_factors') # only created if it doesn't exist\n shared_tables.drop_indexes('variable_capacity_factors') # drop and recreate is faster than incremental sorting\n # drop any rows that no longer have records in projects table\n execute(\"DELETE FROM variable_capacity_factors c WHERE NOT EXISTS (SELECT * FROM projects p WHERE p.project_id=c.project_id);\")\n # cap_factor_df.to_sql('variable_capacity_factors', db_engine, if_exists='append', chunksize=10000)\n copy_dataframe_to_table(cap_factor_df, 'variable_capacity_factors')\n shared_tables.create_indexes('variable_capacity_factors')\n\n\ndef distributed_pv():\n \"\"\"\n add records to database for each distributed PV technology, grouping into\n an appropriate number of tranches\n \"\"\"\n\n # make sure tables exist, and clear out existing DistPV data;\n # the functions below will add records back to these tables\n shared_tables.create_table('projects')\n shared_tables.create_table('variable_capacity_factors')\n # drop and recreate is faster than incremental sorting\n shared_tables.drop_indexes('variable_capacity_factors')\n execute(\"\"\"\n DELETE FROM variable_capacity_factors c\n USING projects p\n WHERE c.project_id=p.project_id AND p.technology in %(pv_techs)s;\n DELETE FROM projects\n WHERE technology in %(pv_techs)s;\n DROP TABLE IF EXISTS dist_pv_details;\n \"\"\", {'pv_techs': ('DistPV', 'SlopedDistPV', 'FlatDistPV')})\n\n add_distributed_pv('FlatDistPV', 4)\n add_distributed_pv('SlopedDistPV', 16)\n\n # restore indexes, final cleanup\n shared_tables.create_indexes('variable_capacity_factors')\n\ndef add_distributed_pv(technology, n_tranches):\n # TODO: break up the major sub-sections of the main loop into separate functions\n # TODO: merge the code that gets capacity factors for each configuration here\n # with the code that gets capacity factors for each cell for utility-scale PV.\n # TODO: write a general function that adds a block of projects and capacity\n # factors to the postgresql database (including reading back the project IDs),\n # and use that for distributed PV, utility-scale PV and wind projects\n\n\n # read roof areas from load_zone_grid_cell.csv\n # treat any NaNs (missing data) as 0.0 coverage\n # See \"Resource Assessment/GIS/Rooftop PV/steps to produce rooftop solar files.txt\"\n # for steps to create this file.\n \"\"\"\n testing:\n\n technology, n_tranches = 'FlatDistPV', 4\n \"\"\"\n all_cells = pd.read_csv(\n db_path('GIS/General/load_zone_nsrdb_cell.csv'),\n index_col=['load_zone', 'nsrdb_id']\n ).fillna(0.0)\n\n # calculate hourly capacity factor for all dist pv configurations\n # for each cell in each load zone\n print(\"Calculating hourly capacity factor for all {} configurations (abt. 1-3 mins).\".format(technology))\n next_alert = time.time() + 60\n for lz in load_zones:\n # lz = 'Oahu'\n lz_cells = all_cells.loc[lz, :]\n lz_cells = lz_cells[lz_cells.roof_area > 0.0]\n # create an array to hold hourly capacity factors for all cells in this load zone\n # it will end up with one row for each cell and one column for each hour\n cap_factors = None\n for cell_n, cell in enumerate(lz_cells.itertuples()):\n cell_capacities, cell_cap_factors = get_dist_pv_cap_factors(\n technology, cell.nsrdb_lat, cell.nsrdb_lon, cell.roof_area\n )\n # note: this is the first time when we know how many configurations\n # and timesteps there are, so this is when we create the cap_factors array\n if cap_factors is None:\n capacities = np.empty((len(lz_cells),) + cell_capacities.shape)\n cap_factors = np.empty((len(lz_cells),) + cell_cap_factors.shape)\n # fill them with nans, so we'll see if any aren't filled later\n capacities.fill(np.nan)\n cap_factors.fill(np.nan)\n capacities[cell_n, :] = cell_capacities\n cap_factors[cell_n, :, :] = cell_cap_factors\n if time.time() > next_alert or cell_n+1 == len(lz_cells):\n next_alert = time.time() + 30\n print(\n \"Calculated distributed PV capacity factors for {} of {} cells in {} load zone.\"\n .format(cell_n+1, len(lz_cells), lz)\n )\n\n # reshape into a long list of resources instead of a cell x config matrix\n capacities = capacities.reshape((-1,))\n cap_factors = cap_factors.reshape((-1, cap_factors.shape[2]))\n # if there are 90 cells in load zone * 3 configurations, then\n # capacities is now a 270-item vector and cap_factors is 270 x number of timesteps\n\n # Get timesteps labels (based on lat and lon of last cell in the list).\n # These may have gaps in years.\n timesteps = [\n get_timesteps(nsrdb_file_dict[(cell.nsrdb_lat, cell.nsrdb_lon, year)])\n for year in years\n ]\n # make an index of all timesteps\n timestep_index = pd.concat(\n (pd.DataFrame(index=x) for x in timesteps)\n ).index.sort_values()\n\n # send cell capacities and cap factors to use for clustering, receive\n # weights of each cell to apply to each cluster;\n # Weights have one row per cluster, one column per cell, with a 1 showing\n # which cluster each cell belongs in.\n cell_cluster_weights = get_cluster_weights(\n cell_capacities=capacities,\n cell_cap_factors=cap_factors[:, (timestep_index.year >= 2007) & (timestep_index.year <= 2008)],\n n_clusters=n_tranches\n )\n\n # use weights to calculate capacity and capacity factors for each cluster\n cluster_capacities = np.dot(cell_cluster_weights, capacities)\n cell_output = np.multiply(capacities[:, np.newaxis], cap_factors) # cells x hours\n cluster_output = np.dot(cell_cluster_weights, cell_output) # clusters x hours\n cluster_cap_factors = np.divide(\n cluster_output,\n cluster_capacities[:, np.newaxis]\n ) # clusters x hours\n\n # PROJECT TABLE\n\n # store project definitions and capacity factors\n print(\"Saving {} project definitions to database.\".format(technology))\n project_df = pd.DataFrame(\n OrderedDict([\n ('load_zone', load_zone),\n ('technology', technology),\n ('site', [\n 'Oahu_{}_{}'.format(technology, i)\n for i in range(len(cluster_capacities))\n ]),\n ('orientation', 'na'),\n ('gen_capacity_limit_mw', cluster_capacities)\n ]),\n ).set_index(['load_zone', 'technology', 'site', 'orientation'])\n project_df.to_sql('projects', db_engine, if_exists='append')\n\n # VARIABLE_CAPACITY_FACTORS TABLE\n\n print(\"Linking capacity factor table with database records.\")\n\n # make an index of all site_ids\n # TODO: change this code and project_df code to zero-fill site numbers up to 2 digits\n # (enough to cover the number of tranches in each zone)\n site_ids = [\n '_'.join([load_zone, technology, str(i)])\n for i in range(cluster_cap_factors.shape[0])\n ]\n\n # multiindex of load_zone, technology, site, orientation\n proj_index = pd.MultiIndex.from_product([\n [load_zone], [technology], site_ids, ['na']\n ])\n # proj_index.to_list()\n\n # make a single dataframe to hold all the data (hours x clusters)\n cap_factor_df = pd.DataFrame(\n cluster_cap_factors.T,\n index=timestep_index,\n columns=proj_index,\n )\n # name the index levels\n cap_factor_df.columns.names = ['load_zone', 'technology', 'site', 'orientation']\n cap_factor_df.index.names=['date_time']\n\n # SAM doesn't currently provide data for leap days, so we fill in with\n # averages from 3 days on either side\n leap_years = set(y for y in cap_factor_df.index.year if y % 4 == 0)\n fill_hours = pd.DatetimeIndex(\n [\n datetime.datetime(y, m, d, h, 0, 0)\n for y in leap_years\n for (m, d) in [(2, 26), (2, 27), (2, 28), (3, 1), (3, 2), (3, 3)]\n for h in range(24)\n ],\n tz=cap_factor_df.index.tz\n )\n # remove any that are already in the index\n fill_hours = fill_hours.difference(cap_factor_df.index)\n\n fill_data = cap_factor_df.loc[fill_hours, :]\n fill_mean = fill_data.groupby([fill_data.index.year, fill_data.index.hour]).mean()\n fill_mean.index = pd.DatetimeIndex(\n [datetime.datetime(y, 2, 29, h) for y, h in fill_mean.index.to_list()],\n tz=cap_factor_df.index.tz\n )\n # drop any fill dates that are already in the data frame\n fill_mean = fill_mean.reindex(index=fill_mean.index.difference(cap_factor_df.index))\n cap_factor_df = cap_factor_df.append(fill_mean).sort_index()\n cap_factor_df.loc['2012-02-29', :]\n cap_factor_df.index.names=['date_time'] # name got dropped during append\n\n # convert to database orientation, with natural order for indexes,\n # but also keep as a DataFrame\n cap_factor_df = pd.DataFrame(\n {'cap_factor': cap_factor_df.stack(cap_factor_df.columns.names)}\n )\n # sort table, then switch to using z, t, s, o as index (to match with project table)\n # (takes a few minutes)\n cap_factor_df = cap_factor_df.reorder_levels(\n ['load_zone', 'technology', 'site', 'orientation', 'date_time']\n ).sort_index().reset_index('date_time')\n\n # retrieve the project IDs (created automatically in the database earlier)\n # note: this read-back could potentially be done earlier, and then the\n # project ids could be included in cap_factor_df when it is first created.\n # but this provides cross-referencing by z, t, s, o automatically, which is helpful.\n project_ids = pd.read_sql(\n \"SELECT project_id, load_zone, technology, site, orientation \"\n \"FROM projects WHERE technology = '{}';\".format(technology),\n db_engine,\n index_col=['load_zone', 'technology', 'site', 'orientation']\n )\n cap_factor_df['project_id'] = project_ids['project_id']\n\n # convert date_time values into strings for insertion into postgresql.\n # Inserting a timezone-aware DatetimeIndex into postgresql fails; see\n # http://stackoverflow.com/questions/35435424/pandas-to-sql-gives-valueerror-with-timezone-aware-column/35552061\n # note: the string conversion is pretty slow\n cap_factor_df['date_time'] = \\\n pd.DatetimeIndex(cap_factor_df['date_time']).strftime(\"%Y-%m-%d %H:%M:%S%z\")\n\n cap_factor_df.set_index(['project_id', 'date_time'], inplace=True)\n # Do we need error checking here? If any projects aren't in cap_factor_df, they'll\n # create single rows with NaNs (and any prior existing cap_factors for them will\n # get dropped below).\n # If any rows in cap_factor_df aren't matched to a project, they'll go in with\n # a null project_id.\n\n print(\"Saving {} capacity factors to database.\".format(technology))\n # The next line is very slow. But it only seems possible to speed it up by\n # copying the data to a csv and doing a bulk insert, which is more cumbersome.\n # progress can be monitored via this command in psql:\n # select query from pg_stat_activity where query like 'INSERT%';\n # cap_factor_df.to_sql('variable_capacity_factors', db_engine, if_exists='append', chunksize=10000)\n copy_dataframe_to_table(cap_factor_df.reset_index(), 'variable_capacity_factors')\n\n # DIST_PV_DETAILS TABLE (optional)\n\n # print(\"Saving {} cluster data to database.\".format(technology))\n # # store cluster details for later reference\n # # would be interesting to see mean and stdev of lat, lon,\n # # cap factor, azimuth, tilt for each cluster, so we can describe them.\n #\n # # use descriptive data for each cell and each configuration as\n # # row and column indexes (will later be saved along with data)\n # rows = pd.MultiIndex.from_arrays(\n # lz_cells[col] for col in ['nsrdb_lat', 'nsrdb_lon']\n # )\n # cols = pd.MultiIndex.from_arrays(\n # dist_pv_configs.loc[technology, col].astype(str)\n # for col in dist_pv_configs.columns\n # )\n # data = {\n # 'capacity_mw': capacities.reshape((len(lz_cells), -1)),\n # 'tranche': (\n # 'Oahu_'\n # + technology + '_'\n # + km.cluster_id.astype(str).astype(np.object)\n # ).reshape((len(lz_cells), -1))\n # }\n # key, vals = list(data.items())[0]\n # dist_pv_details = pd.concat(\n # [\n # pd.DataFrame(vals, index=rows, columns=cols).stack(cols.names).to_frame(name=key)\n # for key, vals in data.items()\n # ],\n # axis=1\n # ).reset_index()\n # dist_pv_details.insert(0, 'technology', technology)\n # dist_pv_details.insert(0, 'load_zone', load_zone)\n #\n # # store in postgresql database\n # dist_pv_details.to_sql('dist_pv_details', db_engine, if_exists='append')\n\n\nimport hashlib\ndef get_cluster_weights(cell_capacities, cell_cap_factors, n_clusters):\n \"\"\"\n receive:\n cell_capacities (vector, weights to use for each cell)\n cap_factors (one row per cell, one column per time step used for clustering)\n n_tranches (number of tranches to create)\n\n return:\n cell_cluster_weights (one row per cluster, one column per cell, showing\n fraction of each cell to include in each cluster)\n\n cluster available resources into specified number of tranches with\n similar timing and quality\n (we assume the better-suited ones will be developed before the worse ones).\n Return capacity in each cluster and hourly capacity factor for each cluster.\n This could be sped up by using a subsample of the timesteps if needed.\n , but then\n the cluster means would have to be calculated afterwards.)\n an alternative approach would be to cluster resources based on annual average\n capacity factor, but that neglects differences in timing between different\n orientations.\n\n use cached value if previously called for these particular capacities and cap_factors\n\n testing:\n np.save('cell_capacities.npy', cell_capacities)\n np.save('cell_cap_factors.npy', cell_cap_factors)\n cell_capacities = np.load('cell_capacities.npy')\n cell_cap_factors = np.load('cell_cap_factors.npy')\n n_clusters = 4\n \"\"\"\n # return cached values if available\n cluster_definition = [\n 'weighted_k_means'.encode(),\n cell_capacities.copy(),\n cell_cap_factors.copy(), # have to copy to avoid non-contiguous errors\n str(n_clusters).encode()\n ]\n h = hashlib.sha1()\n for o in cluster_definition:\n h.update(o)\n cache_file = db_path(nsrdb_dir + '/cluster_cache_{}.npy'.format(h.hexdigest()))\n\n if os.path.exists(cache_file):\n print('Using cached cluster weights {}.'.format(cache_file))\n cell_cluster_weights = np.load(cache_file, allow_pickle=False)\n else:\n print('Calculating new cluster weights via k-means; will cache in {}.'.format(cache_file))\n\n # perform k-means clustering\n km = KMeans(n_clusters, X=cell_cap_factors, size=cell_capacities)\n km.init_centers()\n km.find_centers()\n\n # km.cluster_id shows which cluster each resource belongs to\n # km.mu is a matrix of capacity factors, with one row per cluster and one\n # column per timestep.\n # In theory we could just use the means for the cells from km (km.mu.T),\n # but that wouldn't allow us to reuse the clustering when rebuilding the\n # tables (e.g., to process different date ranges or to rebuild the database)\n # and it would require us to use the full timeseries for k-means instead\n # of just a relevant subset.\n cell_cluster_weights = np.zeros((n_clusters, len(cell_capacities)))\n cell_cluster_weights[km.cluster_id, np.arange(len(km.cluster_id))] = 1\n\n \"\"\"\n # verify these produce the right capacities and production\n cluster_capacities = np.dot(cell_cluster_weights, cell_capacities)\n cell_output = np.multiply(cell_capacities[:, np.newaxis], cell_cap_factors)\n cluster_output = np.dot(cell_cluster_weights, cell_output)\n cluster_cap_factors = np.divide(\n cluster_output,\n cluster_capacities[:, np.newaxis]\n )\n (\n np.abs(np.bincount(km.cluster_id, weights=cell_capacities) - cluster_capacities).max(),\n np.abs(km.mu - cluster_cap_factors).max()\n )\n \"\"\"\n\n # cache weights (this may be a re-save, which allows users to see the latest\n # time a cache file was used, so they can delete obsolete ones)\n np.save(cache_file, cell_cluster_weights, allow_pickle=False)\n return cell_cluster_weights\n\ndef get_cap_factors(file, settings):\n # file, settings = nsrdb_file_dict[21.25, -158.26, 2008], dist_pv_configs.loc['SlopedDistPV', :].iloc[1, :]['settings']\n # file, settings = nsrdb_file_dict[lat, lon, year], settings\n dat = ssc.data_create()\n\n # make sure all needed settings have been specified (there may be other optional ones too)\n assert(all(k in settings for k in [\n 'azimuth', 'tilt', 'array_type', 'gcr', 'dc_ac_ratio', 'inv_eff',\n 'losses', 'module_type'\n ]))\n assert(not np.isnan(settings['tilt'])) # make sure none got through\n\n # assign standard settings (also convert keys from str to bytes)\n for key, val in settings.items():\n ssc.data_set_number(dat, key.encode(), val)\n\n # dc rating in kW for a 1 kW AC system\n ssc.data_set_number(dat, b'system_capacity', settings['dc_ac_ratio'])\n ssc.data_set_number(dat, b'adjust:constant', 0) # required\n\n # specify the file holding the solar data\n ssc.data_set_string(dat, b'solar_resource_file', file.encode())\n\n # run PVWatts\n if ssc.module_exec(pvwatts, dat) == 0:\n err = 'PVWatts simulation error:\\n'\n idx = 1\n msg = ssc.module_log(pvwatts, 0)\n while (msg is not None):\n err += ' : {}\\n'.format(msg)\n msg = ssc.module_log(pvwatts, idx)\n idx += 1\n raise RuntimeError(err.strip())\n else:\n # get power production in kW; for a 1 kW AC system this is also the capacity factor\n cap_factors = np.asarray(ssc.data_get_array(dat, b'gen'), dtype=float)\n\n ssc.data_free(dat)\n\n return cap_factors\n\ndef get_timesteps(file):\n \"\"\"\n Retrieve timesteps from nsrdb file as pandas datetime series.\n Based on code in sscapi.run_test2().\n \"\"\"\n dat = ssc.data_create()\n\n ssc.data_set_string(dat, b'file_name', file.encode())\n ssc.module_exec_simple_no_thread(b'wfreader', dat)\n\n # create a tzinfo structure for this file\n # note: nsrdb uses a fixed offset from UTC, i.e., no daylight saving time\n tz_offset = ssc.data_get_number(dat, b'tz')\n tzinfo = dateutil.tz.tzoffset(None, 3600 * tz_offset)\n\n df = pd.DataFrame(dict(\n year=ssc.data_get_array(dat, b'year'),\n month=ssc.data_get_array(dat, b'month'),\n day=ssc.data_get_array(dat, b'day'),\n hour=ssc.data_get_array(dat, b'hour'),\n minute=ssc.data_get_array(dat, b'minute'),\n )).astype(int)\n\n ssc.data_free(dat)\n\n # create pandas DatetimeIndex for the timesteps in the file\n # note: we ignore minutes because time indexes always refer to the start of the hour\n # in our database\n # note: if you use tz-aware datetime objects with pd.DatetimeIndex(), it converts them\n # to UTC and makes them tz-naive. If you use pd.to_datetime() to make a column of datetime\n # values, you have to specify UTC=True and then it does the same thing.\n # So we start with naive datetimes and then specify the tzinfo when creating the\n # DatetimeIndex. (We could also use idx.localize(tzinfo) after creating a naive DatetimeIndex.)\n\n timesteps = pd.DatetimeIndex(\n [datetime.datetime(year=t.year, month=t.month, day=t.day, hour=t.hour) for t in df.itertuples()],\n tz=tzinfo\n )\n return timesteps\n\ndef get_dist_pv_cap_factors(technology, lat, lon, area):\n \"\"\"\n Calculate size and capacity factors for all distributed PV configurations\n that have been defined with the specified technology label, if sited at the\n specified latitude and longitude, with the specified amount of total roof\n area.\n\n Returns capacity, cap_factors, where capacity is a vector of capacities (in\n MW) available in each configuration, and cap_factors is a matrix showing\n hourly capacity factors for each configuration. cap_factors has one row per\n configuration and one column per timestep. area should be total roof area in\n the cell, in square meters.\n\n Note: area * dist_pv_configs['roof_fraction'] should be total roof area\n covered by panels in m^2, allowing for non-covered areas and space between\n panels. dist_pv_configs['settings']['gcr'] is the percent coverage within\n the panel-covered regions, allowing for space between panels; it only affects\n shading calculations, not capacity.\n \"\"\"\n # technology, lat, lon, area = technology, cell.nsrdb_lat, cell.nsrdb_lon, cell.roof_area\n capacities = []\n cap_factors = []\n for config in dist_pv_configs.loc[technology, :].itertuples():\n # capacity in MW, assuming 1000 W/m2 of irradiance (0.001 MW/m2)\n settings = config.settings.copy()\n if np.isnan(settings['tilt']):\n # flat roof, use latitude\n settings['tilt'] = lat\n capacities.append(\n 0.001 * area * config.roof_fraction # MW of irradiance under rated conditions\n * config.panel_efficiency # DC output at rated conditions, i.e., DC rating\n * (1 / settings['dc_ac_ratio']) # convert to AC rating\n )\n yearly_cfs = [\n get_cap_factors(nsrdb_file_dict[lat, lon, year], settings)\n for year in years\n ]\n # convert list of yearly capacity factors into a single vector\n # and add it to the list of configurations\n cap_factors.append(np.concatenate(yearly_cfs))\n return np.array(capacities), np.array(cap_factors)\n\n# cf = get_cap_factors(nsrdb_file_dict[21.25, -158.26, 2008], dist_pv_configs.loc['SlopedDistPV', :].iloc[1, :]['settings'])\n\ndef db_path(path):\n \"\"\"Convert the path specified relative to the database directory into a real path.\n For convenience, this also converts '/' file separators to whatever is appropriate for\n the current operating system.\"\"\"\n return os.path.join(database_dir, *path.split('/'))\n\ndef round_coord(coord):\n \"\"\"convert lat or lon from whatever form it's currently in to a standard form (2-digit rounded float)\n this ensures stable matching in dictionaries, indexes, etc.\"\"\"\n return round(float(coord), 2)\n\ndef get_nsrdb_file_dict():\n \"\"\"get a list of all the files that have data for each lat/lon pair (parsed from the file names)\"\"\"\n file_dict = dict()\n years = set()\n for dir_name, dirs, files in os.walk(db_path(nsrdb_dir)):\n for f in files:\n file_path = os.path.join(dir_name, f)\n m = nsrdb_file_regex.match(f)\n if m is None:\n # print(\"Skipping unrecognized file {}\".format(file_path))\n pass\n else:\n lat = round_coord(m.group('lat'))\n lon = round_coord(m.group('lon'))\n year = int(m.group('year'))\n file_dict[lat, lon, year] = file_path\n years.add(year)\n if not file_dict:\n print(\"WARNING: unable to find any NSRDB files in {}\".format(db_path(nsrdb_dir)))\n return file_dict, years\n\n# call standard module setup code (whether this is loaded as main or not)\nmodule_setup()\n\n# if __name__ == '__main__':\n# main()\n","sub_path":"build_database/solar_resources.py","file_name":"solar_resources.py","file_ext":"py","file_size_in_byte":45151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48701981","text":"\nclass ICMPPairsGenerator():\n\n def getICMPPair(self, ip_pair_datas, icmp_pairs_dict):\n\n for data in ip_pair_datas:\n\n ip_packet = data.payload\n \n icmp_packet = ip_packet.payload\n\n icmp_fileds = icmp_packet.fields\n\n try:\n\n icmp_type = icmp_fileds['type']\n\n if icmp_type == 8 or icmp_type == 0:\n\n id = icmp_packet.fields['id']\n seq = icmp_packet.fields['seq']\n key = (id, seq)\n \n if key not in icmp_pairs_dict.keys():\n\n icmp_pairs_dict[key] = []\n\n icmp_pairs_dict[key].append(icmp_packet)\n except KeyError as e:\n print(ip_packet.fields['src'])\n # print(len(data.payload.payload.original))\n print(e)\n\n","sub_path":"ICMPPairsGenerator.py","file_name":"ICMPPairsGenerator.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16360956","text":"class Cursor(object):\n\n def __init__(self,\n context,\n container_name,\n access_key,\n table_path,\n raise_for_status=None,\n attribute_names='*',\n filter_expression=None,\n marker=None,\n sharding_key=None,\n limit=None,\n segment=None,\n total_segments=None,\n sort_key_range_start=None,\n sort_key_range_end=None):\n self._context = context\n self._container_name = container_name\n self._access_key = access_key\n self._current_response = None\n self._current_items = None\n self._current_item = None\n self._current_item_index = 0\n self._total_items_read = 0\n\n # get items params\n self.raise_for_status = raise_for_status\n self.table_path = table_path\n self.attribute_names = attribute_names\n self.filter_expression = filter_expression\n self.marker = marker\n self.sharding_key = sharding_key\n self.limit = limit\n self.segment = segment\n self.total_segments = total_segments\n self.sort_key_range_start = sort_key_range_start\n self.sort_key_range_end = sort_key_range_end\n\n def next_item(self):\n calculated_limit = self.limit\n\n # check if we already reached the limit we were asked for\n if self.limit is not None:\n\n # if we already passed the limit, stop here\n if self._total_items_read >= self.limit:\n return None\n\n # don't ask for more items than we'll read\n calculated_limit -= self._total_items_read\n\n # if we already have the item in memory (from the previous scan), return it\n if self._current_item_index < len(self._current_items or []):\n self._current_item = self._current_items[self._current_item_index]\n self._current_item_index += 1\n self._total_items_read += 1\n\n return self._current_item\n\n # if we had a response which was signaled as last, or we didn't get a responsereturn none\n if self._current_response and (self._current_response.output.last or len(self._current_items) == 0):\n return None\n\n self.marker = self._current_response.output.next_marker if self._current_response else None\n\n # get the next batch\n self._current_response = self._context.kv.scan(self._container_name,\n self.table_path,\n self._access_key,\n self.raise_for_status,\n None,\n self.attribute_names,\n self.filter_expression,\n self.marker,\n self.sharding_key,\n calculated_limit,\n self.segment,\n self.total_segments,\n self.sort_key_range_start,\n self.sort_key_range_end)\n\n # raise if there was an issue\n self._current_response.raise_for_status()\n\n # set items\n self._current_items = self._current_response.output.items\n self._current_item_index = 0\n\n # and recurse into next now that we repopulated response\n return self.next_item()\n\n def all(self):\n items = []\n\n while True:\n item = self.next_item()\n\n if item is None:\n break\n\n items.append(item)\n\n return items\n","sub_path":"v3io/dataplane/kv_cursor.py","file_name":"kv_cursor.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"427352830","text":"#!/usr/bin/env python3\nimport argparse\nimport codecs\nimport kdtree\nimport logging\nimport math\nimport requests\nimport os\nimport sys\nfrom io import BytesIO\nimport json # for profiles\nimport re # for profiles\nimport zipfile # for profiles\nfrom collections import defaultdict # for profiles\ntry:\n from .version import __version__\nexcept ImportError:\n from version import __version__\ntry:\n from lxml import etree\nexcept ImportError:\n import xml.etree.ElementTree as etree\n\nTITLE = 'OSM Conflator ' + __version__\nOVERPASS_SERVER = 'http://overpass-api.de/api/'\nOSM_API_SERVER = 'https://api.openstreetmap.org/api/0.6/'\nBBOX_PADDING = 0.003 # in degrees, ~330 m default\nMAX_DISTANCE = 100 # how far can object be to be considered a match, in meters\n\n\nclass SourcePoint:\n \"\"\"A common class for points. Has an id, latitude and longitude,\n and a dict of tags.\"\"\"\n def __init__(self, pid, lat, lon, tags=None, category=None):\n self.id = str(pid)\n self.lat = lat\n self.lon = lon\n self.tags = {} if tags is None else {\n k.lower(): str(v) for k, v in tags.items() if v is not None}\n self.category = category\n self.dist_offset = 0\n\n def distance(self, other):\n \"\"\"Calculate distance in meters.\"\"\"\n dx = math.radians(self.lon - other.lon) * math.cos(0.5 * math.radians(self.lat + other.lat))\n dy = math.radians(self.lat - other.lat)\n return 6378137 * math.sqrt(dx*dx + dy*dy) - self.dist_offset\n\n def __len__(self):\n return 2\n\n def __getitem__(self, i):\n if i == 0:\n return self.lat\n elif i == 1:\n return self.lon\n else:\n raise ValueError('A SourcePoint has only lat and lon in a list')\n\n def __eq__(self, other):\n return self.id == other.id\n\n def __hash__(self):\n return hash(self.id)\n\n def __repr__(self):\n return 'SourcePoint({}, {}, {}, offset={}, tags={})'.format(\n self.id, self.lat, self.lon, self.dist_offset, self.tags)\n\n\nclass OSMPoint(SourcePoint):\n \"\"\"An OSM points is a SourcePoint with a few extra fields.\n Namely, version, members (for ways and relations), and an action.\n The id is compound and created from object type and object id.\"\"\"\n def __init__(self, ptype, pid, version, lat, lon, tags=None):\n super().__init__('{}{}'.format(ptype[0], pid), lat, lon, tags)\n self.osm_type = ptype\n self.osm_id = pid\n self.version = version\n self.members = None\n self.action = None\n\n def copy(self):\n \"\"\"Returns a copy of this object, except for members field.\"\"\"\n c = OSMPoint(self.osm_type, self.osm_id, self.version, self.lat, self.lon, self.tags.copy())\n c.action = self.action\n return c\n\n def is_area(self):\n return self.osm_type != 'node'\n\n def is_poi(self):\n if self.osm_type == 'node':\n return True\n if self.osm_type == 'way' and len(self.members) > 2:\n return self.members[0] == self.members[-1]\n if self.osm_type == 'relation' and len(self.members) > 0:\n return self.tags.get('type', None) == 'multipolygon'\n return False\n\n def to_xml(self):\n \"\"\"Produces an XML out of the point data. Disregards the \"action\" field.\"\"\"\n el = etree.Element(self.osm_type, id=str(self.osm_id), version=str(self.version))\n for tag, value in self.tags.items():\n etree.SubElement(el, 'tag', k=tag, v=value)\n\n if self.osm_type == 'node':\n el.set('lat', str(self.lat))\n el.set('lon', str(self.lon))\n elif self.osm_type == 'way':\n for node_id in self.members:\n etree.SubElement(el, 'nd', ref=str(node_id))\n elif self.osm_type == 'relation':\n for member in self.members:\n m = etree.SubElement(el, 'member')\n for i, n in enumerate(('type', 'ref', 'role')):\n m.set(n, str(member[i]))\n return el\n\n def __repr__(self):\n return 'OSMPoint({} {} v{}, {}, {}, action={}, tags={})'.format(\n self.osm_type, self.osm_id, self.version, self.lat, self.lon, self.action, self.tags)\n\n\nclass ProfileException(Exception):\n \"\"\"An exception class for the Profile instance.\"\"\"\n def __init__(self, attr, desc):\n super().__init__('Field missing in profile: {} ({})'.format(attr, desc))\n\n\nclass Profile:\n \"\"\"A wrapper for a profile.\n\n A profile is a python script that sets a few local variables.\n These variables become properties of the profile, accessible with\n a \"get\" method. If something is a function, it will be called,\n optional parameters might be passed to it.\n\n You can compile a list of all supported variables by grepping through\n this code, or by looking at a few example profiles. If something\n is required, you will be notified of that.\n \"\"\"\n def __init__(self, fileobj):\n if isinstance(fileobj, dict):\n self.profile = fileobj\n elif hasattr(fileobj, 'read'):\n s = fileobj.read().replace('\\r', '')\n if s[0] == '{':\n self.profile = json.loads(s)\n else:\n self.profile = {}\n exec(s, globals(), self.profile)\n else:\n # Got a class\n self.profile = {name: getattr(fileobj, name)\n for name in dir(fileobj) if not name.startswith('_')}\n\n def has(self, attr):\n return attr in self.profile\n\n def get(self, attr, default=None, required=None, args=None):\n if attr in self.profile:\n value = self.profile[attr]\n if callable(value):\n if args is None:\n return value()\n else:\n return value(*args)\n else:\n return value\n if required is not None:\n raise ProfileException(attr, required)\n return default\n\n def get_raw(self, attr, default=None):\n if attr in self.profile:\n return self.profile[attr]\n return default\n\n\nclass OsmConflator:\n \"\"\"The main class for the conflator.\n\n It receives a dataset, after which one must call either\n \"download_osm\" or \"parse_osm\" methods. Then it is ready to match:\n call the \"match\" method and get results with \"to_osc\".\n \"\"\"\n def __init__(self, profile, dataset, audit=None):\n self.dataset = {p.id: p for p in dataset}\n self.audit = audit or {}\n self.osmdata = {}\n self.matched = []\n self.changes = []\n self.profile = profile\n self.source = self.profile.get(\n 'source', required='value of \"source\" tag for uploaded OSM objects')\n self.add_source_tag = self.profile.get('add_source', False)\n if self.profile.get('no_dataset_id', False):\n self.ref = None\n else:\n self.ref = 'ref:' + self.profile.get(\n 'dataset_id', required='A fairly unique id of the dataset to query OSM')\n\n def construct_overpass_query(self, bboxes=None):\n \"\"\"Constructs an Overpass API query from the \"query\" list in the profile.\n (k, v) turns into [k=v], (k,) into [k], (k, None) into [!k], (k, \"~v\") into [k~v].\"\"\"\n tags = self.profile.get(\n 'query', required=\"a list of tuples. E.g. [('amenity', 'cafe'), ('name', '~Mc.*lds')]\")\n if isinstance(tags, str):\n tag_str = tags\n else:\n tag_str = ''\n for t in tags:\n if len(t) == 1:\n q = '\"{}\"'.format(t[0])\n elif t[1] is None or len(t[1]) == 0:\n q = '\"!{}\"'.format(t[0])\n elif t[1][0] == '~':\n q = '\"{}\"~\"{}\"'.format(t[0], t[1][1:])\n else:\n q = '\"{}\"=\"{}\"'.format(t[0], t[1])\n tag_str += '[' + q + ']'\n\n timeout = self.profile.get('overpass_timeout', 120)\n query = '[out:xml]{};('.format('' if timeout is None else '[timeout:{}]'.format(timeout))\n for bbox in bboxes:\n bbox_str = '' if bbox is None else '(' + ','.join([str(x) for x in bbox]) + ')'\n for t in ('node', 'way', 'relation[\"type\"=\"multipolygon\"]'):\n query += t + tag_str + bbox_str + ';'\n if self.ref is not None:\n for t in ('node', 'way', 'relation'):\n query += t + '[\"' + self.ref + '\"];'\n query += '); out meta qt center;'\n return query\n\n def get_dataset_bbox(self):\n \"\"\"Plain iterates over the dataset and returns the bounding box\n that encloses it.\"\"\"\n padding = self.profile.get('bbox_padding', BBOX_PADDING)\n bbox = [90.0, 180.0, -90.0, -180.0]\n for p in self.dataset.values():\n bbox[0] = min(bbox[0], p.lat - padding)\n bbox[1] = min(bbox[1], p.lon - padding)\n bbox[2] = max(bbox[2], p.lat + padding)\n bbox[3] = max(bbox[3], p.lon + padding)\n return bbox\n\n def split_into_bboxes(self):\n \"\"\"\n Splits the dataset into multiple bboxes to lower load on the overpass api.\n\n Returns a list of tuples (minlat, minlon, maxlat, maxlon).\n \"\"\"\n if len(self.dataset) <= 1:\n return [self.get_dataset_bbox()]\n\n # coord, alt coord, total w/h to the left/bottom, total w/h to the right/top\n lons = sorted([[d.lon, d.lat, 0, 0] for d in self.dataset.values()])\n lats = sorted([[d.lat, d.lon, 0, 0] for d in self.dataset.values()])\n\n def update_side_dimensions(ar):\n \"\"\"For each point, calculates the maximum and\n minimum bound for all points left and right.\"\"\"\n fwd_top = fwd_bottom = ar[0][1]\n back_top = back_bottom = ar[-1][1]\n for i in range(len(ar)):\n fwd_top = max(fwd_top, ar[i][1])\n fwd_bottom = min(fwd_bottom, ar[i][1])\n ar[i][2] = fwd_top - fwd_bottom\n back_top = max(back_top, ar[-i-1][1])\n back_bottom = min(back_bottom, ar[-i-1][1])\n ar[-i-1][3] = back_top - back_bottom\n\n def find_max_gap(ar, h):\n \"\"\"Select an interval between points, which would give\n the maximum area if split there.\"\"\"\n max_id = None\n max_gap = 0\n for i in range(len(ar) - 1):\n # \"Extra\" variables are for area to the left and right\n # that would be freed after splitting.\n extra_left = (ar[i][0]-ar[0][0]) * (h-ar[i][2])\n extra_right = (ar[-1][0]-ar[i+1][0]) * (h-ar[i+1][3])\n # Gap is the area of the column between points i and i+1\n # plus extra areas to the left and right.\n gap = (ar[i+1][0] - ar[i][0]) * h + extra_left + extra_right\n if gap > max_gap:\n max_id = i\n max_gap = gap\n return max_id, max_gap\n\n def get_bbox(b, pad=0):\n \"\"\"Returns a list of [min_lat, min_lon, max_lat, max_lon] for a box.\"\"\"\n return [b[2][0][0]-pad, b[3][0][0]-pad, b[2][-1][0]+pad, b[3][-1][0]+pad]\n\n def split(box, point_array, point_id):\n \"\"\"Split the box over axis point_array at point point_id...point_id+1.\n Modifies the box in-place and returns a new box.\"\"\"\n alt_array = 5 - point_array # 3->2, 2->3\n points = box[point_array][point_id+1:]\n del box[point_array][point_id+1:]\n alt = {True: [], False: []} # True means point is in new box\n for p in box[alt_array]:\n alt[(p[1], p[0]) >= (points[0][0], points[0][1])].append(p)\n\n new_box = [None] * 4\n new_box[point_array] = points\n new_box[alt_array] = alt[True]\n box[alt_array] = alt[False]\n for i in range(2):\n box[i] = box[i+2][-1][0] - box[i+2][0][0]\n new_box[i] = new_box[i+2][-1][0] - new_box[i+2][0][0]\n return new_box\n\n # height, width, lats, lons\n max_bboxes = self.profile.get('max_request_boxes', 8)\n boxes = [[lats[-1][0]-lats[0][0], lons[-1][0]-lons[0][0], lats, lons]]\n initial_area = boxes[0][0] * boxes[0][1]\n while len(boxes) < max_bboxes and len(boxes) <= len(self.dataset):\n candidate_box = None\n area = 0\n point_id = None\n point_array = None\n for box in boxes:\n for ar in (2, 3):\n # Find a box and an axis for splitting that would decrease the area the most\n update_side_dimensions(box[ar])\n max_id, max_area = find_max_gap(box[ar], box[3-ar])\n if max_area > area:\n area = max_area\n candidate_box = box\n point_id = max_id\n point_array = ar\n if area * 100 < initial_area:\n # Stop splitting when the area decrease is less than 1%\n break\n logging.debug('Splitting bbox %s at %s %s-%s; area decrease %s%%',\n get_bbox(candidate_box),\n 'longs' if point_array == 3 else 'lats',\n candidate_box[point_array][point_id][0],\n candidate_box[point_array][point_id+1][0],\n round(100*area/initial_area))\n boxes.append(split(candidate_box, point_array, point_id))\n\n padding = self.profile.get('bbox_padding', BBOX_PADDING)\n return [get_bbox(b, padding) for b in boxes]\n\n def check_against_profile_tags(self, tags):\n qualifies = self.profile.get('qualifies', args=tags)\n if qualifies is not None:\n return qualifies\n\n query = self.profile.get('query', None)\n if query is not None and not isinstance(query, str):\n for tag in query:\n if len(tag) >= 1:\n if tag[0] not in tags:\n return False\n if len(tag) >= 2 and tag[1][0] != '~':\n if tag[1] != tags[tag[0]]:\n return False\n return True\n\n def download_osm(self):\n \"\"\"Constructs an Overpass API query and requests objects\n to match from a server.\"\"\"\n profile_bbox = self.profile.get('bbox', True)\n if not profile_bbox:\n bboxes = [None]\n elif hasattr(profile_bbox, '__len__') and len(profile_bbox) == 4:\n bboxes = [profile_bbox]\n else:\n bboxes = self.split_into_bboxes()\n\n query = self.construct_overpass_query(bboxes)\n logging.debug('Overpass query: %s', query)\n r = requests.get(OVERPASS_SERVER + 'interpreter', {'data': query})\n if r.status_code != 200:\n logging.error('Failed to download data from Overpass API: %s', r.status_code)\n if 'rate_limited' in r.text:\n r = requests.get(OVERPASS_SERVER + 'status')\n logging.warning('Seems like you are rate limited. API status:\\n%s', r.text)\n else:\n logging.error('Error message: %s', r.text)\n raise IOError()\n self.parse_osm(r.content)\n\n def parse_osm(self, fileobj):\n \"\"\"Parses an OSM XML file into the \"osmdata\" field. For ways and relations,\n finds the center. Drops objects that do not match the overpass query tags\n (see \"check_against_profile_tags\" method).\"\"\"\n if isinstance(fileobj, bytes):\n xml = etree.fromstring(fileobj)\n else:\n xml = etree.parse(fileobj).getroot()\n nodes = {}\n for nd in xml.findall('node'):\n nodes[nd.get('id')] = (float(nd.get('lat')), float(nd.get('lon')))\n ways = {}\n for way in xml.findall('way'):\n center = way.find('center')\n if center is not None:\n ways[way.get('id')] = [float(center.get('lat')), float(center.get('lon'))]\n else:\n logging.warning('Way %s does not have a center', way.get('id'))\n coord = [0, 0]\n count = 0\n for nd in way.findall('nd'):\n if nd.get('id') in nodes:\n count += 1\n for i in range(len(coord)):\n coord[i] += nodes[nd.get('ref')][i]\n ways[way.get('id')] = [coord[0] / count, coord[1] / count]\n\n # For calculating weight of OSM objects\n weight_fn = self.profile.get_raw('weight')\n max_distance = self.profile.get('max_distance', MAX_DISTANCE)\n\n for el in xml:\n tags = {}\n for tag in el.findall('tag'):\n tags[tag.get('k')] = tag.get('v')\n if not self.check_against_profile_tags(tags):\n continue\n\n if el.tag == 'node':\n coord = nodes[el.get('id')]\n members = None\n elif el.tag == 'way':\n coord = ways[el.get('id')]\n members = [nd.get('ref') for nd in el.findall('nd')]\n elif el.tag == 'relation':\n center = el.find('center')\n if center is not None:\n coord = [float(center.get('lat')), float(center.get('lon'))]\n else:\n coord = [0, 0]\n count = 0\n for m in el.findall('member'):\n if m.get('type') == 'node' and m.get('ref') in nodes:\n count += 1\n for i in range(len(coord)):\n coord[i] += nodes[m.get('ref')][i]\n elif m.get('type') == 'way' and m.get('ref') in ways:\n count += 1\n for i in range(len(coord)):\n coord[i] += ways[m.get('ref')][i]\n coord = [coord[0] / count, coord[1] / count]\n members = [\n (m.get('type'), m.get('ref'), m.get('role'))\n for m in el.findall('member')\n ]\n else:\n continue\n pt = OSMPoint(\n el.tag, int(el.get('id')), int(el.get('version')),\n coord[0], coord[1], tags)\n pt.members = members\n if pt.is_poi():\n if callable(weight_fn):\n weight = weight_fn(pt)\n if weight:\n pt.dist_offset = weight if abs(weight) > 3 else weight * max_distance\n self.osmdata[pt.id] = pt\n\n def register_match(self, dataset_key, osmdata_key, keep=False, retag=None):\n \"\"\"Registers a match between an OSM point and a dataset point.\n\n Merges tags from an OSM Point and a dataset point, and add the result to the\n self.matched list.\n If dataset_key is None, deletes or retags the OSM point.\n If osmdata_key is None, adds a new OSM point for the dataset point.\n \"\"\"\n def update_tags(tags, source, master_tags=None, retagging=False, audit=None):\n \"\"\"Updates tags dictionary with tags from source,\n returns True is something was changed.\"\"\"\n keep = set()\n override = set()\n changed = False\n if source:\n if audit:\n keep = set(audit.get('keep', []))\n override = set(audit.get('override', []))\n for k, v in source.items():\n if k in keep:\n continue\n if k in override:\n if not v and k in tags:\n del tags[k]\n changed = True\n elif v and tags.get(k, None) != v:\n tags[k] = v\n changed = True\n continue\n if k not in tags or retagging or (\n tags[k] != v and (master_tags and k in master_tags)):\n if v is not None and len(v) > 0:\n tags[k] = v\n changed = True\n elif k in p.tags and (v == '' or retagging):\n del tags[k]\n changed = True\n return changed\n\n def format_change(before, after, ref):\n MARKER_COLORS = {\n 'delete': '#ee2211', # deleting feature from OSM\n 'create': '#1100dd', # creating a new node\n 'update': '#0000ee', # changing tags on an existing feature\n 'retag': '#660000', # cannot delete unmatched feature, changing tags\n 'move': '#000066', # moving an existing node\n }\n marker_action = None\n geometry = {'type': 'Point', 'coordinates': [after.lon, after.lat]}\n props = {\n 'osm_type': after.osm_type,\n 'osm_id': after.osm_id,\n 'action': after.action\n }\n if after.action in ('create', 'delete'):\n # Red if deleted, green if added\n marker_action = after.action\n for k, v in after.tags.items():\n props['tags.{}'.format(k)] = v\n if ref:\n props['ref_id'] = ref.id\n else: # modified\n # Blue if updated from dataset, dark red if retagged, dark blue if moved\n marker_action = 'update' if ref else 'retag'\n if ref:\n props['ref_id'] = ref.id\n props['ref_distance'] = round(10 * ref.distance(before)) / 10.0\n props['ref_coords'] = [ref.lon, ref.lat]\n if before.lon != after.lon or before.lat != after.lat:\n # The object was moved\n props['were_coords'] = [before.lon, before.lat]\n marker_action = 'move'\n # Find tags that were superseeded by OSM tags\n unused_tags = {}\n for k, v in ref.tags.items():\n if k not in after.tags or after.tags[k] != v:\n unused_tags[k] = v\n if unused_tags:\n for k, v in unused_tags.items():\n props['ref_unused_tags.{}'.format(k)] = v\n # Now compare old and new OSM tags\n for k in set(after.tags.keys()).union(set(before.tags.keys())):\n v0 = before.tags.get(k, None)\n v1 = after.tags.get(k, None)\n if v0 == v1:\n props['tags.{}'.format(k)] = v0\n elif v0 is None:\n props['tags_new.{}'.format(k)] = v1\n elif v1 is None:\n props['tags_deleted.{}'.format(k)] = v0\n else:\n props['tags_changed.{}'.format(k)] = '{} -> {}'.format(v0, v1)\n props['marker-color'] = MARKER_COLORS[marker_action]\n return {'type': 'Feature', 'geometry': geometry, 'properties': props}\n\n max_distance = self.profile.get('max_distance', MAX_DISTANCE)\n p = self.osmdata.pop(osmdata_key, None)\n p0 = None if p is None else p.copy()\n sp = self.dataset.pop(dataset_key, None)\n audit = self.audit.get(sp.id if sp else '{}{}'.format(p.osm_type, p.osm_id), {})\n if audit.get('skip', False):\n return\n\n if sp is not None:\n if p is None:\n p = OSMPoint('node', -1-len(self.matched), 1, sp.lat, sp.lon, sp.tags)\n p.action = 'create'\n else:\n master_tags = set(self.profile.get('master_tags', []))\n if update_tags(p.tags, sp.tags, master_tags, audit=audit):\n p.action = 'modify'\n # Move a node if it is too far from the dataset point\n if not p.is_area() and sp.distance(p) > max_distance:\n p.lat = sp.lat\n p.lon = sp.lon\n p.action = 'modify'\n if self.add_source_tag:\n if 'source' in p.tags:\n if self.source not in p.tags['source']:\n p.tags['source'] = ';'.join([p.tags['source'], self.source])\n else:\n p.tags['source'] = self.source\n if self.ref is not None:\n p.tags[self.ref] = sp.id\n if 'fixme' in audit and audit['fixme']:\n p.tags['fixme'] = audit['fixme']\n if 'move' in audit and not p.is_area():\n if p0 and audit['move'] == 'osm':\n p.lat = p0.lat\n p.lon = p0.lon\n elif audit['move'] == 'dataset':\n p.lat = sp.lat\n p.lon = sp.lon\n elif len(audit['move']) == 2:\n p.lat = audit['move'][1]\n p.lon = audit['move'][0]\n if p.action is None:\n p.action = 'modify'\n elif keep or p.is_area():\n if update_tags(p.tags, retag, retagging=True, audit=audit):\n p.action = 'modify'\n else:\n p.action = 'delete'\n\n if p.action is not None:\n self.matched.append(p)\n self.changes.append(format_change(p0, p, sp))\n\n def match_dataset_points_smart(self):\n \"\"\"Smart matching for dataset <-> OSM points.\n\n We find a shortest link between a dataset and an OSM point.\n Then we match these and remove both from dicts.\n Then find another link and so on, until the length of a link\n becomes larger than \"max_distance\".\n\n Currently the worst case complexity is around O(n^2*log^2 n).\n But given the small number of objects to match, and that\n the average case complexity is ~O(n*log^2 n), this is fine.\n \"\"\"\n def search_nn_fix(kd, point):\n nearest = kd.search_knn(point, 10)\n if not nearest:\n return None, None\n match_func = self.profile.get_raw('matches')\n if match_func:\n nearest = [p for p in nearest if match_func(p[0].data.tags, point.tags)]\n if not nearest:\n return None, None\n nearest = [(n[0], n[0].data.distance(point)) for n in nearest]\n return sorted(nearest, key=lambda kv: kv[1])[0]\n\n if not self.osmdata:\n return\n max_distance = self.profile.get('max_distance', MAX_DISTANCE)\n osm_kd = kdtree.create(list(self.osmdata.values()))\n count_matched = 0\n\n # Process overridden features first\n for override, osm_find in self.profile.get('override', {}).items():\n override = str(override)\n if override not in self.dataset:\n continue\n found = None\n if len(osm_find) > 2 and osm_find[0] in 'nwr' and osm_find[1].isdigit():\n if osm_find in self.osmdata:\n found = self.osmdata[osm_find]\n # Search nearest 100 points\n nearest = osm_kd.search_knn(self.dataset[override], 100)\n if nearest:\n for p in nearest:\n if 'name' in p[0].data.tags and p[0].data.tags['name'] == osm_find:\n found = p[0].data\n if found:\n count_matched += 1\n self.register_match(override, found.id)\n osm_kd = osm_kd.remove(found)\n\n # Prepare distance list: match OSM points to each of the dataset points\n dist = []\n for sp, v in self.dataset.items():\n osm_point, distance = search_nn_fix(osm_kd, v)\n if osm_point is not None and distance <= max_distance:\n dist.append((distance, sp, osm_point.data))\n\n # The main matching loop: sort dist list if needed,\n # register the closes match, update the list\n needs_sorting = True\n while dist:\n if needs_sorting:\n dist.sort(key=lambda x: x[0])\n needs_sorting = False\n count_matched += 1\n osm_point = dist[0][2]\n self.register_match(dist[0][1], osm_point.id)\n osm_kd = osm_kd.remove(osm_point)\n del dist[0]\n for i in range(len(dist)-1, -1, -1):\n if dist[i][2] == osm_point:\n nearest, distance = search_nn_fix(osm_kd, self.dataset[dist[i][1]])\n if nearest and distance <= max_distance:\n dist[i] = (distance, dist[i][1], nearest.data)\n needs_sorting = i == 0 or distance < dist[0][0]\n else:\n del dist[i]\n needs_sorting = i == 0\n logging.info('Matched %s points', count_matched)\n\n def match(self):\n \"\"\"Matches each osm object with a SourcePoint, or marks it as obsolete.\n The resulting list of OSM Points are written to the \"matched\" field.\"\"\"\n if self.ref is not None:\n # First match all objects with ref:whatever tag set\n count_ref = 0\n for k, p in list(self.osmdata.items()):\n if self.ref in p.tags:\n if p.tags[self.ref] in self.dataset:\n count_ref += 1\n self.register_match(p.tags[self.ref], k)\n logging.info('Updated %s OSM objects with %s tag', count_ref, self.ref)\n\n # Then find matches for unmatched dataset points\n self.match_dataset_points_smart()\n\n # Add unmatched dataset points\n logging.info('Adding %s unmatched dataset points', len(self.dataset))\n for k in sorted(list(self.dataset.keys())):\n self.register_match(k, None)\n\n # And finally delete some or all of the remaining osm objects\n if len(self.osmdata) > 0:\n count_deleted = 0\n count_retagged = 0\n delete_unmatched = self.profile.get('delete_unmatched', False)\n retag = self.profile.get('tag_unmatched')\n for k, p in list(self.osmdata.items()):\n if self.ref is not None and self.ref in p.tags:\n # When ref:whatever is present, we can delete that object safely\n count_deleted += 1\n self.register_match(None, k, retag=retag)\n elif delete_unmatched or retag:\n if not delete_unmatched or p.is_area():\n count_retagged += 1\n else:\n count_deleted += 1\n self.register_match(None, k, keep=not delete_unmatched, retag=retag)\n logging.info(\n 'Deleted %s and retagged %s unmatched objects from OSM',\n count_deleted, count_retagged)\n\n def backup_osm(self):\n \"\"\"Writes OSM data as-is.\"\"\"\n osm = etree.Element('osm', version='0.6', generator=TITLE)\n for osmel in self.osmdata.values():\n el = osmel.to_xml()\n if osmel.osm_type != 'node':\n etree.SubElement(el, 'center', lat=str(osmel.lat), lon=str(osmel.lon))\n osm.append(el)\n return (\"\\n\" +\n etree.tostring(osm, encoding='utf-8').decode('utf-8'))\n\n def to_osc(self, josm=False):\n \"\"\"Returns a string with osmChange or JOSM XML.\"\"\"\n osc = etree.Element('osm' if josm else 'osmChange', version='0.6', generator=TITLE)\n if josm:\n neg_id = -1\n changeset = etree.SubElement(osc, 'changeset')\n ch_tags = {\n 'source': self.source,\n 'created_by': TITLE,\n 'type': 'import'\n }\n for k, v in ch_tags.items():\n etree.SubElement(changeset, 'tag', k=k, v=v)\n for osmel in self.matched:\n if osmel.action is not None:\n el = osmel.to_xml()\n if josm:\n if osmel.action == 'create':\n el.set('id', str(neg_id))\n neg_id -= 1\n else:\n el.set('action', osmel.action)\n osc.append(el)\n else:\n etree.SubElement(osc, osmel.action).append(el)\n return (\"\\n\" +\n etree.tostring(osc, encoding='utf-8').decode('utf-8'))\n\n\ndef check_moveability(changes):\n to_check = [x for x in changes if x['properties']['osm_type'] == 'node' and\n x['properties']['action'] == 'modify']\n logging.info('Checking moveability of %s modified nodes', len(to_check))\n for c in to_check:\n p = c['properties']\n p['can_move'] = False\n r = requests.get('{}node/{}/ways'.format(OSM_API_SERVER, p['osm_id']))\n if r.status_code == 200:\n xml = etree.fromstring(r.content)\n p['can_move'] = xml.find('way') is None\n\n\ndef read_dataset(profile, fileobj):\n \"\"\"A helper function to call a \"dataset\" function in the profile.\n If the fileobj is not specified, tries to download a dataset from\n an URL specified in \"download_url\" profile variable.\"\"\"\n if not fileobj:\n url = profile.get('download_url')\n if url is None:\n logging.error('No download_url specified in the profile, '\n 'please provide a dataset file with --source')\n return None\n r = requests.get(url)\n if r.status_code != 200:\n logging.error('Could not download source data: %s %s', r.status_code, r.text)\n return None\n if len(r.content) == 0:\n logging.error('Empty response from %s', url)\n return None\n fileobj = BytesIO(r.content)\n if not profile.has('dataset'):\n # The default option is to parse the source as a JSON\n try:\n data = []\n reader = codecs.getreader('utf-8')\n for item in json.load(reader(fileobj)):\n data.append(SourcePoint(item['id'], item['lat'], item['lon'], item['tags']))\n return data\n except Exception:\n logging.error('Failed to parse the source as a JSON')\n return profile.get(\n 'dataset', args=(fileobj,),\n required='returns a list of SourcePoints with the dataset')\n\n\ndef transform_dataset(profile, dataset):\n \"\"\"Transforms tags in the dataset using the \"transform\" method in the profile\n or the instructions in that field in string or dict form.\"\"\"\n transform = profile.get_raw('transform')\n if not transform:\n return\n if callable(transform):\n for d in dataset:\n transform(d.tags)\n return\n if isinstance(transform, str):\n # Convert string of \"key=value|rule1|rule2\" lines to a dict\n lines = [line.split('=', 1) for line in transform.splitlines()]\n transform = {l[0].strip(): l[1].strip() for l in lines}\n if not transform or not isinstance(transform, dict):\n return\n for key in transform:\n if isinstance(transform[key], str):\n transform[key] = [x.strip() for x in transform[key].split('|')]\n\n for d in dataset:\n for key, rules in transform.items():\n if not rules:\n continue\n value = None\n if callable(rules):\n # The value can be generated\n value = rules(None if key not in d.tags else d.tags[key])\n if value is None and key in d.tags:\n del d.tags[key]\n elif not rules[0]:\n # Use the value of the tag\n if key in d.tags:\n value = d.tags[key]\n elif not isinstance(rules[0], str):\n # If the value is not a string, use it\n value = str(rules[0])\n elif rules[0][0] == '.':\n # Use the value from another tag\n alt_key = rules[0][1:]\n if alt_key in d.tags:\n value = d.tags[alt_key]\n elif rules[0][0] == '>':\n # Replace the key\n if key in d.tags:\n d.tags[rules[0][1:]] = d.tags[key]\n del d.tags[key]\n elif rules[0][0] == '<':\n # Replace the key, the same but backwards\n alt_key = rules[0][1:]\n if alt_key in d.tags:\n d.tags[key] = d.tags[alt_key]\n del d.tags[alt_key]\n elif rules[0] == '-':\n # Delete the tag\n if key in d.tags:\n del d.tags[key]\n else:\n # Take the value as written\n value = rules[0]\n if value is None:\n continue\n if isinstance(rules, list):\n for rule in rules[1:]:\n if rule == 'lower':\n value = value.lower()\n d.tags[key] = value\n\n\ndef run(profile=None):\n parser = argparse.ArgumentParser(\n description='''{}.\n Reads a profile with source data and conflates it with OpenStreetMap data.\n Produces an JOSM XML file ready to be uploaded.'''.format(TITLE))\n if not profile:\n parser.add_argument('profile', type=argparse.FileType('r'), help='Name of a profile (python or json) to use')\n parser.add_argument('-i', '--source', type=argparse.FileType('rb'), help='Source file to pass to the profile dataset() function')\n parser.add_argument('-a', '--audit', type=argparse.FileType('rb'), help='Conflation validation result as a JSON file')\n parser.add_argument('-o', '--output', type=argparse.FileType('w'), default=sys.stdout, help='Output OSM XML file name')\n parser.add_argument('--osc', action='store_true', help='Produce an osmChange file instead of JOSM XML')\n parser.add_argument('--osm', help='Instead of querying Overpass API, use this unpacked osm file. Create one from Overpass data if not found')\n parser.add_argument('-c', '--changes', type=argparse.FileType('w'), help='Write changes as GeoJSON for visualization')\n parser.add_argument('-m', '--check-move', action='store_true', help='Check for moveability of modified modes')\n parser.add_argument('--verbose', '-v', action='store_true', help='Display debug messages')\n parser.add_argument('--quiet', '-q', action='store_true', help='Do not display informational messages')\n options = parser.parse_args()\n\n if options.verbose:\n log_level = logging.DEBUG\n elif options.quiet:\n log_level = logging.WARNING\n else:\n log_level = logging.INFO\n logging.basicConfig(level=log_level, format='%(asctime)s %(message)s', datefmt='%H:%M:%S')\n logging.getLogger(\"requests\").setLevel(logging.WARNING)\n logging.getLogger(\"urllib3\").setLevel(logging.WARNING)\n\n if not profile:\n logging.debug('Loading profile %s', options.profile)\n profile = Profile(profile or options.profile)\n\n dataset = read_dataset(profile, options.source)\n if not dataset:\n logging.error('Empty source dataset')\n sys.exit(2)\n transform_dataset(profile, dataset)\n logging.info('Read %s items from the dataset', len(dataset))\n\n audit = None\n if options.audit:\n reader = codecs.getreader('utf-8')\n audit = json.load(reader(options.audit))\n\n conflator = OsmConflator(profile, dataset, audit)\n if options.osm and os.path.exists(options.osm):\n with open(options.osm, 'r') as f:\n conflator.parse_osm(f)\n else:\n conflator.download_osm()\n if len(conflator.osmdata) > 0 and options.osm:\n with open(options.osm, 'w') as f:\n f.write(conflator.backup_osm())\n logging.info('Downloaded %s objects from OSM', len(conflator.osmdata))\n\n conflator.match()\n\n diff = conflator.to_osc(not options.osc)\n options.output.write(diff)\n if options.changes:\n if options.check_move:\n check_moveability(conflator.changes)\n fc = {'type': 'FeatureCollection', 'features': conflator.changes}\n json.dump(fc, options.changes, ensure_ascii=False, sort_keys=True, indent=1)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"conflate/conflate.py","file_name":"conflate.py","file_ext":"py","file_size_in_byte":40691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"224408026","text":"import re\nimport subprocess\n\n'''\n Retrieves the current IPv4 address of the client\n @RETURN:\n client_ip : IPv4 address of the client\n'''\ndef get_client_ip():\n client_ip = \"\"\n print(\"getting Client ip\")\n p = subprocess.Popen([\"hostname\", \"-I\"], stdout = subprocess.PIPE)\n for line in p.stdout:\n client_ip = re.split(\" \", line.decode(\"utf-8\"))[0]\n break\n print(\"Client IP is : {}\".format(client_ip))\n return client_ip\n\n\n'''\n Sets up a file with name : filename\n @PARAMS:\n filename : filename\n'''\ndef file_setter(filename):\n subprocess.call(['sudo', 'rm', filename])\n subprocess.call(['touch', filename])\n subprocess.call(['chmod', '666', filename])\n\n'''\n Parses the MTU out of an mtu process output file\n @PARAMS:\n stdout_data : filename of the output file\n\n @RETURN:\n mtu : maximum transmission unit\n'''\ndef parse_mtu(stdout_data):\n mtu = None\n with open(stdout_data,\"r\") as f:\n for line in f:\n temp = line\n if \"PLPMTUD\" in temp:\n mtu = re.split(\" \", temp)[3]\n return mtu\n\n'''\n Parses the RTT out of an rtt process output file\n @PARAMS:\n stdout_data : filename of the output file\n\n @RETURN:\n rtt : baseline round trip time\n'''\ndef parse_ping(stdout_data):\n ave_rtt = None\n with open(stdout_data,\"r\") as f:\n for line in f:\n temp = line\n if \"avg\" in temp:\n ave_rtt = re.split(\" \", temp)[2]\n #ave_rtt = re.split(\"/\", rtt)[2]\n return ave_rtt\n\n#'''\n# Parses the throughput metrics out of throughput process output file\n# @PARAMS:\n# stdout_data : filename of the output file\n# rtt : Round Trip Time\n#\n# @RETURN:\n# bb : baseline bandwidth\n# bdp : bandwidth delay product\n# rwnd : receive window size\n#'''\n#def parse_iperf3(stdout_data, rtt):\n# return_results = []\n# break_flag = False\n# bb = None\n# bdp = None\n# rwnd = None\n# with open(stdout_data,\"r\") as f:\n# for line in f:\n# temp = line\n# if \"Jitter\" in temp:\n# break_flag = True\n# continue\n# if break_flag:\n# entries = re.findall(r'\\S+',temp)\n# timecheck = float(re.split(\"-\",entries[2])[1])\n# if timecheck < 10:\n# print(\"iPerf UDP incomplete\")\n# break\n# bb = entries[6]\n# bdp = (float(rtt) /1000) * (float(bb)* 1000000)\n# rwnd = bdp/8 / 1000\n# break\n# return bb, bdp, rwnd\n\n'''\n Parses the throughput metrics out of a throughput process output file\n @PARAMS:\n stdout_data : filename of the output file\n recv_window : receiver window value\n rtt : Round Trip Time value\n\n @RETURN:\n ave_tcp : average TCP throughput\n ide_tcp : ideal TCP throughput\n ave_tt : average transfer time\n ide_tt : ideal transfer time\n tcp_ttr : transfer time ratio between\n average and ideal\n speed_plot : N/A\n'''\ndef parse_shark(stdout_data, recv_window, rtt, res_filter):\n speed_plot = []\n ave_tcp = None\n ave_tt = None\n ide_tt = None\n tcp_ttr = None\n ide_tcp = (float(recv_window) * 8 / (float(rtt)/1000))/(10**6)\n offset = 0\n multiplier = 1\n\n with open(stdout_data,\"r\") as f:\n for line in f:\n temp = line\n if res_filter in temp:\n entries = re.findall(r'\\S+',temp)\n if \"SUM\" in temp:\n offset = 1\n try:\n ave_tcp = float(entries[6-offset])\n\n # average transfer time\n temp2 = re.split(\"-\",entries[2-offset])\n ave_tt = float(temp2[1])\n\n if \"KBytes\" in entries[5-offset]:\n multiplier = 1000\n\n ide_tt = ( float(entries[4-offset]) * 8 * multiplier ) / ( ide_tcp )\n tcp_ttr = ave_tt / ide_tt\n except:\n pass\n\n return ave_tcp, ide_tcp, ave_tt, ide_tt, tcp_ttr, speed_plot\n\n","sub_path":"utilities/client_utils.py","file_name":"client_utils.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291909729","text":"\"\"\"\nGiven an input text and an array of k words, arr[], \nfind all occurrences of all words in the input text. \nLet n be the length of text and m be the total number \ncharacters in all words.\n\nIf we use a linear time searching algorithm like KMP, then we need to individually search all words in text[]. \nThis gives us total time complexity O(n*k+m)\n\nAho-Corasick Algorithm finds all words in O(n + m + z) time where z is total number of occurrences of words in text. \n\"\"\"\n\nfrom collections import deque\nadj_list = []\n\n\ndef init_trie(patterns): \n \"\"\"We first init a Trie (or Keyword Tree) of all words.\"\"\"\n\n adj_list.append({'value':'', 'next':[],'fail':0,'output':[]})\n for p in patterns:\n add_pattern(p)\n set_fail_states()\n\n\ndef next_state(current_state, value):\n for vtx in adj_list[current_state][\"next\"]:\n if adj_list[vtx][\"value\"] == value:\n return vtx\n return None\n\n\ndef add_pattern(pat):\n current_state = 0\n j = 0\n pat = pat.lower()\n adj = next_state(current_state, pat[j])\n while adj != None:\n current_state = adj\n j = j + 1\n if j < len(pat):\n adj = next_state(current_state, pat[j])\n else:\n break\n for i in range(j, len(pat)):\n vtx = {'value':pat[i],'next':[],'fail':0,'output':[]}\n \n adj_list.append(vtx)\n adj_list[current_state][\"next\"].append(len(adj_list) - 1)\n current_state = len(adj_list) - 1\n \n adj_list[current_state][\"output\"].append(pat)\n\n\ndef set_fail_states():\n \"\"\"This function stores all edges that are\n followed when current character doesn't\n have edge in Trie. Supports linear time matching\"\"\"\n q = deque()\n\n for vtx in adj_list[0][\"next\"]:\n q.append(vtx)\n adj_list[vtx][\"fail\"] = 0\n while q:\n r = q.popleft()\n for adj in adj_list[r][\"next\"]:\n q.append(adj)\n state = adj_list[r][\"fail\"]\n while next_state(state, adj_list[adj][\"value\"]) is None and state != 0:\n state = adj_list[state][\"fail\"]\n adj_list[adj][\"fail\"] = next_state(state, adj_list[adj][\"value\"])\n if adj_list[adj][\"fail\"] is None:\n adj_list[adj][\"fail\"] = 0\n adj_list[adj][\"output\"] = adj_list[adj][\"output\"] + adj_list[adj_list[adj][\"fail\"]][\"output\"]\n\n\ndef get_suggestions(line):\n \"\"\"Stores indexes of all words that end at current state.\"\"\"\n line = line.lower()\n current_state = 0\n matches = []\n for i in range(len(line)):\n while next_state(current_state, line[i]) is None and current_state != 0:\n current_state = adj_list[current_state][\"fail\"]\n current_state = next_state(current_state, line[i])\n if current_state is None:\n current_state = 0\n else:\n for j in adj_list[current_state][\"output\"]:\n matches.append(line)\n return matches\n\ninit_trie(['ear', 'middle', 'infection'])\n\nsuggestions = []\nfor line in open('data/short-diagnoses.txt'):\n a = get_suggestions(line.rstrip('\\n'))\n if (len(a)>0):\n suggestions.append((a[0], len(a)))\nprint(sorted(suggestions, key=lambda x: x[1], reverse=True))\n\n","sub_path":"ahoSearch.py","file_name":"ahoSearch.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"280715473","text":"import numpy as np\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nfrom colorama import init\r\nfrom termcolor import *\r\ninit()\r\n\r\nclass AutoEncoder(tf.keras.layers.Layer):\r\n\tdef __init__(self, D, M):\r\n\t\tsuper(AutoEncoder, self).__init__()\r\n\t\tcprint('Contractive AutoEncoder Initilization...........','red')\r\n\t\tself.D = D\r\n\t\tself.M = M\r\n\t\t# Input ---------> Hidden\r\n\t\tself.W = tf.Variable(tf.random.normal(shape=(D, M))*2 / np.sqrt(M))\r\n\t\tself.b = tf.Variable(tf.zeros([M], tf.float32))\r\n\t\t# Hidden ---------> Output\r\n\t\tself.V = tf.Variable(tf.random.normal(shape=(M, D))* 2 / np.sqrt(D))\r\n\t\tself.c = tf.Variable(tf.zeros([D], tf.float32))\r\n\r\n\tdef forward(self, X):\r\n\t\tZ = tf.nn.sigmoid(tf.matmul(X, self.W) + self.b)\r\n\t\tlogits = tf.matmul(Z, self.V) + self.c\r\n\t\tX_hat = tf.nn.sigmoid(logits)\r\n\t\treturn X_hat, logits, Z\r\n\r\n\t# Cost\r\n\tdef cost(self, X, Z, logits):\r\n\t\tcrossentropy_loss = tf.math.reduce_mean(\r\n\t\t\ttf.nn.sigmoid_cross_entropy_with_logits(labels=X, logits=logits))\r\n\t\t\r\n\t\treturn crossentropy_loss \r\n\r\n\tdef gradient_update(self, X, optimizer):\r\n\t\twith tf.GradientTape(persistent=True) as t:\r\n\t\t\tX = tf.convert_to_tensor(X, np.float32)\r\n\t\t\tt.watch(X)\r\n\t\t\t_, logits, Z = self.forward(X)\r\n\t\t\tcrossentropy_loss = self.cost(X, Z, logits)\r\n\t\t\t# Frobenius norm of Jacobian \r\n\t\t\tJ = t.gradient(logits, Z)\r\n\t\t\tjacobian_loss = tf.norm(tf.reshape(J, [-1,1]), ord='fro', axis=(0,1))\r\n\t\t\tLoss = crossentropy_loss + (1e-3)*jacobian_loss\r\n\t\t\tgrads = t.gradient(Loss, [model.W, model.b, model.V, model.c])\r\n\t\toptimizer.apply_gradients(zip(grads, [model.W, model.b, model.V, model.c]))\r\n\t\treturn Loss\r\n\r\n\tdef fit(self, X, epochs=10, batch_size=500, lr=0.005):\r\n\t\tN = X.shape[0]\r\n\t\tn_batches = N // batch_size\r\n\t\tcprint('Train model........','green')\r\n\t\toptimizer = tf.keras.optimizers.Adam(learning_rate=lr)\r\n\t\tcost_lst = []\r\n\t\tfor i in range(epochs):\r\n\t\t\tnp.random.shuffle(X)\r\n\t\t\tfor j in range(n_batches):\r\n\t\t\t\tLoss = self.gradient_update(X[(j*batch_size):((j+1)*batch_size)], optimizer)\r\n\t\t\t\tcost_lst.append(Loss/batch_size)\r\n\t\t\t\tif j % 10 ==0:\r\n\t\t\t\t\tcprint(f'Epoch: {i+1}, Batch: {j}, Loss: {Loss}','green')\r\n\t\treturn cost_lst\r\n\r\n\tdef predict(self, X):\r\n\t\tcprint('Making Predictions........','blue')\r\n\t\treturn self.forward(X)[0]\r\n\r\nif __name__ == \"__main__\":\r\n\t(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\r\n\tx_train, x_test = x_train / 255, x_test / 255\r\n\tN_train, H, W = np.shape(x_train)\r\n\tN_test, H, W = np.shape(x_test)\r\n\tx_train = x_train.reshape(N_train, H*W) \r\n\tx_train = x_train + 0.15*np.random.randn(N_train, H*W)\r\n\tx_train= np.clip(x_train,0,1)\r\n\tx_test = x_test.reshape(N_test, H*W) \r\n\tx_test = x_test + 0.15*np.random.randn(N_test, H*W)\r\n\tx_test= np.clip(x_test,0,1)\r\n\tD = H*W\r\n\tx_train = x_train.astype(np.float32)\r\n\tx_test = x_test.astype(np.float32)\r\n\tM = 300\r\n\tmodel = AutoEncoder(D, M)\r\n\tcost_lst = model.fit(x_train)\r\n\t#make prediction for random image\r\n\ti = np.random.choice(N_test)\r\n\tX_hat = model.predict(x_test)\r\n\tplt.figure\r\n\tplt.subplot(121)\r\n\tplt.imshow(x_test[i].reshape(28,28), cmap='gray')\r\n\tplt.title('Original')\r\n\tplt.subplot(122)\r\n\tplt.imshow(X_hat[i].numpy().reshape(28,28), cmap='gray')\r\n\tplt.title('Reconstructed')\r\n\tplt.show()\r\n\tplt.plot(cost_lst)\r\n\tplt.title('Loss Curve')\r\n\tplt.show()","sub_path":"Deep Learning/AEs/ContractiveAE.py","file_name":"ContractiveAE.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"509346309","text":"# -*- coding: utf-8 -*-\nfrom plone import api\nfrom zope.interface import implements\nfrom plone.portlets.interfaces import IPortletDataProvider\nfrom plone.app.portlets.portlets import base\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\n\n\nclass IPhotoPortlet(IPortletDataProvider):\n \"\"\"\n Photo portlet interface\n \"\"\"\n\n\nclass Assignment(base.Assignment):\n implements(IPhotoPortlet)\n\n\nclass Renderer(base.Renderer):\n render = ViewPageTemplateFile('photo.pt')\n\n @property\n def available(self):\n \"\"\"\n Portlet should be available from the 3 level of navigation\n \"\"\"\n contextPhyPath = self.context.getPhysicalPath()\n portalPhyPath = api.portal.get().getPhysicalPath()\n path = [elem for elem in list(contextPhyPath) if elem not in list(portalPhyPath)]\n depth = len(path)\n if depth < 2:\n return False\n return True\n\n\nclass AddForm(base.NullAddForm):\n\n def create(self):\n return Assignment()\n","sub_path":"cpskin/core/portlets/photo.py","file_name":"photo.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"192612382","text":"import time\nimport Email\n# Must manually end program as driver.quit() function is missing\n\nstop_loss = 0.1\n# Sell if 10% of coin is lost\n\n\ndef start():\n import WebScrap as W\n\n while True:\n print(\"TIME: \", W.get_time())\n possible_coins = W.look_for_changing_EMAS()\n\n if possible_coins:\n symbol = possible_coins[0]\n assert W.click_on_watchlist(symbol)\n # Currently only the first coin to be spotted to hold will be held, any\n # other coins that are a good buy will be discarded\n print(f\"Analyzing: {symbol}\", \"Starting MACD test...\", end=\"\\n\")\n\n Email.send_email(Email.boom, \"POSSIBLE PURCHASE GO TO COMPUTER\")\n\n if W.MACD_test_buy():\n # Start while loop with W.MACD_HOLD_SELL() to keep holding until\n # MACD decreases or stop loss\n print(f\"Purchase {symbol} and hold!!!!\")\n m = f\"\"\"\n Buy: {symbol}\n Price: {W.get_price()}\n Time: {W.get_time()}\n \"\"\"\n Email.send_email(Email.boom, \" Buy\")\n\n else:\n print(\"No possible purchases found, restarting...\")\n time.sleep(10)\n\n\nif __name__ == \"__main__\":\n start()\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"179689728","text":"import os\nimport sys\n\n#鹼基轉換標準樣本\nBase_dict = dict({\"A\":\"U\",\"C\":\"G\",\"G\":\"C\",\"T\":\"A\"})\n\n#讀取DNA序列\ndef fileRead(file_name):\n if os.path.exists(file_name):\n fileI = open(file_name ,'r')\n rna = fileI.read()\n fileI.close()\n \n print(\"complete -> \"+file_name + \" 成功載入\")\n return rna\n else:\n print(\"Error 10 -> 找不到.dna檔案,你是否忘記輸入.dna副檔名?\\n\")\n exit(10)\n \n#解析鹼基與轉錄行為\ndef resolve(base,resolve_count):\n base = base.upper()\n if base == \" \":\n return \"\"\n \n if not(base in Base_dict):\n print (\"Error 20 -> 位無法識別的鹼基 at \"+str(resolve_count)+\"\\n\")\n #print(mrna + base)\n return \"E\"\n else:\n return Base_dict[base]\n\n#輸出mRNA序列\ndef FileOut(mrna,file_name):\n try: \n fileO = open(file_name + \".mrna\",\"w\") \n textnum = fileO.write(mrna)\n print(\"complete -> 轉錄完成 \"+file_name+\".mrna\"+\" 檔案已產生,共寫入 \" + str(textnum) + \" 個鹼基\")\n except:\n print(\"Error 11 -> 檔案寫入失敗,請檢查檔案系統\")\n \n finally:\n fileO.close()\n\n#Program Entry\ndef main():\n try:\n file_name = sys.argv[1]\n except:\n print(\"Error 41 -> 參數錯誤或沒有參數\")\n exit()\n #file_name=input(\"讀取檔名.dna ->\") \n rna = fileRead(file_name)\n mrna = \"\"\n resolve_count = 0\n ok = True\n \n for base in rna:\n resolve_count += 1\n if resolve(base,resolve_count) == \"E\": \n ok = False\n break;\n else:\n if resolve(base,resolve_count) != \"\":\n mrna += resolve(base,resolve_count)\n \n #如果轉錄過程沒有異常,呼叫輸出\n if ok:\n FileOut(mrna,file_name)\n \nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"transcripter.py","file_name":"transcripter.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"86925024","text":"#!/usr/bin/python3\n\n# 1b-dic.py\n# Ask for name\n# Anthony DOMINGUE\n# 15/10/2018\n\nimport re\n\npattern = '^[A-z]*$' # Regex to check input : any amount of letter, caps or not\nuser_entry = ''\nnames_list = []\n\nwhile user_entry != 'q':\n\n user_entry = input(\"Enter a name :\")\n\n while not re.match(pattern, user_entry):\n print(\"Invalid input, must be ^[A-z]*$\")\n user_entry = input(\"Enter a name :\")\n\n if not user_entry == 'q':\n names_list.append(user_entry)\n\nsorted(names_list) # We sort the list (by default alphabetically)\nprint(names_list)\n","sub_path":"scripts/1b-dic.py","file_name":"1b-dic.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"161021666","text":"#-*- coding:utf-8 -*-\nfrom pyspark import SparkContext, SQLContext, SparkConf\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import IntegerType\nimport os\n\n\napp_name = 'sales_std'\nconf = SparkConf().setAppName(app_name).setMaster('yarn')\ntry:\n sc = SparkContext(conf=conf).getOrCreate()\n sqlContext = SQLContext(sc)\nexcept:\n pass\nspark = SparkSession.builder.master('yarn').appName(app_name).enableHiveSupport().getOrCreate()\n\n\n## hive sql\nsql_1 = '''select * from app.app_ipc_ioa_sales_rdc where dt='2016-04-01' '''\nsales_rdc = spark.sql(sql_1)\n\n## DataFrame Operate\nsales_rdc.filter(col('dc_id')=='772').show() # filter by a Column\nsales_rdc.filter((col('dc_id')=='772') & (col('item_first_cate_cd')=='1620')).show() # filter by some Columns\nsales_rdc.filter((col('dc_id')=='772') & (col('item_first_cate_cd')=='1620') & (col('total_sales')!=0)).show()\n\ndata = [[2,3,4], [1,2,3], [7,6,5]]\ndata_df = spark.createDataFrame(data, list('abc')) # create a DF, with columns name\ndata_df2 = spark.createDataFrame(data) # create a DF\n\n\ndata = [[2,3,4], [1,2,3], [7,6,5]]\n\n\nsqlContext.registerDataFrameAsTable(data_df2, \"test_table\") # register a Tmp Table\ntest_data = spark.sql('select * from test_table')\n# sqlContext.dropTempTable(\"test_table\")\n\nsqlContext.udf.register(\"stringLengthInt\", lambda x: len(str(x)), IntegerType()) # register a Function for SQL\nsqlContext.registerFunction(\"stringLengthInt\", lambda x: len(str(x)), IntegerType())\nsqlContext.sql(\"SELECT stringLengthInt('test') as len\").show()\nsqlContext.sql(\"SELECT stringLengthInt(a) as len from test_table \").show()\n\ndf_as1 = data_df.alias(\"df_as1\") # alias\ndf_as2 = data_df.alias(\"df_as2\")\njoined_df = df_as1.join(df_as2, col(\"df_as1.a\") == col(\"df_as2.a\"), 'inner') # 保留了全部列名\njoined_df.select(\"df_as1.a\", \"df_as2.a\", \"df_as2.b\", \"df_as2.c\").show()\n\nprint(data_df.columns)\n\n# ---------------------------------------------------------------------------------\ndata1 = [[2, u'Alice'], [5, u'Bob']]\ndata2 = [[u'Tom', 80], [u'Bob', 85]]\ndata3 = [[2, 2, u'Alice'], [5, 5, u'Bob'], [5, 53, u'Bob'], [7, 1, u'Alice']]\ndata4 = [[2, 2, u'Alice'], [5, None, u'Bob'], [5, 53, None], [7, 1, u'Alice']]\ndf1 = spark.createDataFrame(data1, [\"age\", \"name\"])\ndf2 = spark.createDataFrame(data2, [\"name\", \"height\"])\ndf3 = spark.createDataFrame(data3, ['weight', 'height', 'name'])\ndf4 = spark.createDataFrame(data4, ['age', 'height', 'name'])\n# ---------------------------------------------------------------------------------\n\ndf1.crossJoin(df2.select(\"height\")).select(\"age\", \"name\", \"height\").show() # crossJoin\n\ndf1.describe().show() # Descriptive statistical analysis\ndf1.distinct().show() # Distinct 无参数\ndf1.join(df2, 'name', 'inner').drop('age', 'height').show() # Drop Columns\n\ndf3.dropDuplicates(['name', 'height']).show() # dropDuplicates drop_duplicates\ndf3.select('name').drop_duplicates().show()\n\ndf3.dropna().show() # dropna 'any' 'all'\ndf3.na.drop().show()\n\nprint(df3.dtypes)\n\ndf4.fillna({'height': 50, 'name': 'unknown'}).show() # fillna dict value\ndf4.na.fill(50).show()\ndf4.groupby(['name', df4.age]).agg({'age': 'mean', 'name':'count'}).show() # groupBy groupby\n\ndf3.join(df4, df3.name == df4.name, 'outer').select(df3.name, df3.height).show() # join\n\n# 存储文件信息,在 Spark 中,存储于 HDFS 上。不建议使用 saveAsTextFile,因为无法覆盖overwrite。\nsql_3 = '''select\n item_first_cate_cd,\n item_second_cate_cd,\n count(item_second_cate_cd) as cate2_count\nfrom\n gdm.gdm_m03_item_sku_da\nwhere\n dt = '2017-11-14'\n and sku_valid_flag = 1\n and sku_status_cd = '3001'\n and data_type = 1\ngroup by\n item_first_cate_cd,\n item_second_cate_cd\n'''\ndata4 = spark.sql(sql_3)\ndata4.rdd.map(lambda x: \",\".join(map(str, x))).coalesce(1).saveAsTextFile(r'hdfs://ns15/user/cmo_ipc/longguangbin/work/count_cates/cate2' + os.sep + 'cate2')\nsql_3 = '''select\n item_first_cate_cd,\n count(item_first_cate_cd) as cate2_count\nfrom\n gdm.gdm_m03_item_sku_da\nwhere\n dt = '2017-11-14'\n and sku_valid_flag = 1\n and sku_status_cd = '3001'\n and data_type = 1\ngroup by\n item_first_cate_cd\n'''\ndata4 = spark.sql(sql_3)\ndata4.rdd.map(lambda x: \",\".join(map(str, x))).coalesce(1).saveAsTextFile(r'hdfs://ns15/user/cmo_ipc/longguangbin/work/count_cates/cate1' + os.sep + 'cate1')\ndata2 = data1.limit(1000)\ndata2.write.csv(r'hdfs://ns15/user/cmo_ipc/longguangbin/work/count_cates/data_csv', header=True, mode=\"overwrite\") # 存储为 csv\ndata3 = spark.read.csv(r'hdfs://ns15/user/cmo_ipc/longguangbin/work/count_cates/data_csv')\n\n\n# ---------------------------------------------------------\n# 172.21.9.69:50010\n# 172.21.9.226:50010\n\n# 172.21.17.99:50010\n# 172.21.17.102:50010\n\n# 172.21.18.166:50010\n# 172.21.18.168:50010\n\n# 172.21.26.165:50010\n\n# 172.21.29.3:50010\n# 172.21.29.227:50010\n# 172.21.29.235:50010\n\n# 172.21.78.194:50010\n# 172.21.78.199:50010\n# ---------------------------------------------------------\n\n\n# ---------------------------------------------------------\n# 科学算法集市\nimport numpy as np\nimport pandas as pd\n\ndf1.show()\ndf1.select(df1.columns).show()\nnp.array(df1.select(df1.columns).collect())\n\ndf1.select(df1.columns).toArray()\nmm = np.matrix(df1.toPandas())\n\n\nfrom py_offline_ipc_ioa_inv_loc_cost_cal import CostCal, getSampleData\nsku, Q, P_order, P_store, P_trans, Tau, v, weight, p_sale, beta, Const_num, Const_p, A_Matrix, T_period, r_ratio = getSampleData()\n\n\nA_Matrix = spark.createDataFrame(A_Matrix)\nQ = spark.createDataFrame(Q)\nP_store = spark.createDataFrame(map(lambda x: [x], P_store))\nP_order = spark.createDataFrame(map(lambda x: [x], P_order))\nP_trans = spark.createDataFrame(P_trans)\nTau = spark.createDataFrame(Tau)\nConst_num = spark.createDataFrame(map(lambda x: [x], Const_num))\nConst_p = spark.createDataFrame(map(lambda x: [x], Const_p))\n\n\ndef calRes(sku, Q, P_order, P_store, P_trans, Tau, v, weight, p_sale, beta, Const_num, Const_p, T_period, r_ratio):\n cost_cal = CostCal(sku, Q, P_order, P_store, P_trans, Tau, v, weight, p_sale, beta, Const_num, Const_p, T_period, r_ratio)\n total_cost, total_cost_list = cost_cal.run(A_Matrix)\n return total_cost\n\n\nA_Matrix = A_Matrix.toPandas()\nQ = Q.toPandas()\n\n\nP_store = P_store.toPandas() # store [ broadcast ]\nP_order = P_order.toPandas() # order [ broadcast ]\nP_trans = P_trans.toPandas() # trans [ broadcast ]\nTau = Tau.toPandas() # tau [ broadcast ]\nConst_num = Const_num.toPandas() # no need []\nConst_p = Const_p.toPandas() # no need []\n\n\ncalRes(sku, Q, P_order, P_store, P_trans, Tau, v, weight, p_sale, beta, Const_num, Const_p, T_period, r_ratio)\n\n\nP_store_broadcast = sc.broadcast(P_store)\nP_order_broadcast = sc.broadcast(P_order)\nP_trans_broadcast = sc.broadcast(P_trans)\nTau_broadcast = sc.broadcast(Tau)\nConst_num_broadcast = sc.broadcast(Const_num)\nConst_p_broadcast = sc.broadcast(Const_p)\n\n\n\n\n","sub_path":"longgb/Python_Module/pyspark_learn/pyspark_basic.py","file_name":"pyspark_basic.py","file_ext":"py","file_size_in_byte":7681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139404644","text":"'''\nCreated on 2018. 12. 21.\n\n@author: gdj4\nmultiprocessEx1.py\n'''\n\nimport multiprocessing\nimport time\n\n\nclass RacingCar : \n carName = \"\"\n def __init__(self,name):\n self.carName = name\n \n def runCar(self):\n for _ in range(0,3) :\n carStr = self.carName + \"~~ ?‹¬λ¦½λ‹ˆ?‹€. \\n\"\n print(carStr,end=\"\")\n time.sleep(0.1) # 0.1μ΄ˆλ™?•ˆ ??κΈ?\nif __name__ == '__main__' : # ?™ΈλΆ??—?„œ ? ‘κ·Όν•  ?•Œ 메인?ž„?„ ?•Œλ¦?\n \n car1 = RacingCar(\"@?ž?™μ°?1\")\n car2 = RacingCar(\"#?ž?™μ°?2\")\n car3 = RacingCar(\"$?ž?™μ°?3\")\n# ?Š€? ˆ?“œ 객체 ?ƒ?„±\n# target = car1.runCar : ?Š€? ˆ?“œκ°? ?‹€?–‰?•΄?•Ό ?•  λ©”μ„œ?“œ μ§?? •\n mp1 = multiprocessing.Process(target=car1.runCar())\n mp2 = multiprocessing.Process(target=car2.runCar())\n mp3 = multiprocessing.Process(target=car3.runCar())\n\n mp1.start() # ?”„λ‘œμ„Έ?Š€ ?‹€?–‰ ?‹œ?ž‘\n mp2.start()\n mp3.start()\n mp1.join() # join : mp1 ?”„λ‘œμ„Έ?Š€κ°? μ’…λ£Œ?•  ?•ŒκΉŒμ? main?΄ ??κΈ?\n mp2.join()\n mp3.join()\nprint(\"?”„λ‘œκ·Έ?ž¨ μ’…λ£Œ\") ","sub_path":"PythonEx/1221/multiprocessex1.py","file_name":"multiprocessex1.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"220650274","text":"from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.utils.data\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom models.submodule import *\nimport math\nfrom math import log\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nimport numpy as np\nfrom scipy import sparse as sp\n\n#########bts#######\n\ndef bn_init_as_tf(m):\n if isinstance(m, nn.BatchNorm2d):\n m.track_running_stats = True # These two lines enable using stats (moving mean and var) loaded from pretrained model\n m.eval() # or zero mean and variance of one if the batch norm layer has no pretrained values\n m.affine = True\n m.requires_grad = True\n\n\ndef weights_init_xavier(m):\n if isinstance(m, nn.Conv2d):\n torch.nn.init.xavier_uniform_(m.weight)\n if m.bias is not None:\n torch.nn.init.zeros_(m.bias)\n \n\nclass silog_loss(nn.Module):\n def __init__(self, variance_focus):\n super(silog_loss, self).__init__()\n self.variance_focus = variance_focus\n\n def forward(self, depth_est, depth_gt, mask):\n d = torch.log(depth_est[mask]) - torch.log(depth_gt[mask])\n return torch.sqrt((d ** 2).mean() - self.variance_focus * (d.mean() ** 2)) * 10.0\n\n\nclass atrous_conv(nn.Sequential):\n def __init__(self, in_channels, out_channels, dilation, apply_bn_first=True):\n super(atrous_conv, self).__init__()\n self.atrous_conv = torch.nn.Sequential()\n if apply_bn_first:\n self.atrous_conv.add_module('first_bn', nn.BatchNorm2d(in_channels, momentum=0.01, affine=True, track_running_stats=True, eps=1.1e-5))\n \n self.atrous_conv.add_module('aconv_sequence', nn.Sequential(nn.ReLU(),\n nn.Conv2d(in_channels=in_channels, out_channels=out_channels*2, bias=False, kernel_size=1, stride=1, padding=0),\n nn.BatchNorm2d(out_channels*2, momentum=0.01, affine=True, track_running_stats=True),\n nn.ReLU(),\n nn.Conv2d(in_channels=out_channels * 2, out_channels=out_channels, bias=False, kernel_size=3, stride=1,\n padding=(dilation, dilation), dilation=dilation)))\n\n def forward(self, x):\n return self.atrous_conv.forward(x)\n \n\nclass upconv(nn.Module):\n def __init__(self, in_channels, out_channels, ratio=2):\n super(upconv, self).__init__()\n self.elu = nn.ELU()\n self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, bias=False, kernel_size=3, stride=1, padding=1)\n self.ratio = ratio\n \n def forward(self, x):\n up_x = F.interpolate(x, scale_factor=self.ratio, mode='nearest')\n out = self.conv(up_x)\n out = self.elu(out)\n return out\n\n\nclass reduction_1x1(nn.Sequential):\n def __init__(self, num_in_filters, num_out_filters, max_depth, is_final=False):\n super(reduction_1x1, self).__init__() \n self.max_depth = max_depth\n self.is_final = is_final\n self.sigmoid = nn.Sigmoid()\n self.reduc = torch.nn.Sequential()\n \n while num_out_filters >= 4:\n if num_out_filters < 8:\n if self.is_final:\n self.reduc.add_module('final', torch.nn.Sequential(nn.Conv2d(num_in_filters, out_channels=1, bias=False,\n kernel_size=1, stride=1, padding=0),\n nn.Sigmoid()))\n else:\n self.reduc.add_module('plane_params', torch.nn.Conv2d(num_in_filters, out_channels=3, bias=False,\n kernel_size=1, stride=1, padding=0))\n break\n else:\n self.reduc.add_module('inter_{}_{}'.format(num_in_filters, num_out_filters),\n torch.nn.Sequential(nn.Conv2d(in_channels=num_in_filters, out_channels=num_out_filters,\n bias=False, kernel_size=1, stride=1, padding=0),\n nn.ELU()))\n\n num_in_filters = num_out_filters\n num_out_filters = num_out_filters // 2\n \n def forward(self, net):\n net = self.reduc.forward(net)\n if not self.is_final:\n theta = self.sigmoid(net[:, 0, :, :]) * math.pi / 3\n phi = self.sigmoid(net[:, 1, :, :]) * math.pi * 2\n dist = self.sigmoid(net[:, 2, :, :]) * self.max_depth\n n1 = torch.mul(torch.sin(theta), torch.cos(phi)).unsqueeze(1)\n n2 = torch.mul(torch.sin(theta), torch.sin(phi)).unsqueeze(1)\n n3 = torch.cos(theta).unsqueeze(1)\n n4 = dist.unsqueeze(1)\n net = torch.cat([n1, n2, n3, n4], dim=1)\n \n return net\n\nclass local_planar_guidance(nn.Module):\n def __init__(self, upratio):\n super(local_planar_guidance, self).__init__()\n self.upratio = upratio\n self.u = torch.arange(self.upratio).reshape([1, 1, self.upratio]).float()\n self.v = torch.arange(int(self.upratio)).reshape([1, self.upratio, 1]).float()\n self.upratio = float(upratio)\n\n def forward(self, plane_eq, focal):\n plane_eq_expanded = torch.repeat_interleave(plane_eq, int(self.upratio), 2)\n plane_eq_expanded = torch.repeat_interleave(plane_eq_expanded, int(self.upratio), 3)\n n1 = plane_eq_expanded[:, 0, :, :]\n n2 = plane_eq_expanded[:, 1, :, :]\n n3 = plane_eq_expanded[:, 2, :, :]\n n4 = plane_eq_expanded[:, 3, :, :]\n \n u = self.u.repeat(plane_eq.size(0), plane_eq.size(2) * int(self.upratio), plane_eq.size(3)).cuda()\n u = (u - (self.upratio - 1) * 0.5) / self.upratio\n \n v = self.v.repeat(plane_eq.size(0), plane_eq.size(2), plane_eq.size(3) * int(self.upratio)).cuda()\n v = (v - (self.upratio - 1) * 0.5) / self.upratio\n\n return n4 / (n1 * u + n2 * v + n3)\n\n#########################\n\nclass feature_extraction(nn.Module):\n def __init__(self, concat_feature=False, concat_feature_channel=12):\n super(feature_extraction, self).__init__()\n self.concat_feature = concat_feature\n\n self.inplanes = 32\n self.firstconv = nn.Sequential(convbn(3, 32, 3, 2, 1, 1),\n nn.ReLU(inplace=True),\n convbn(32, 32, 3, 1, 1, 1),\n nn.ReLU(inplace=True),\n convbn(32, 32, 3, 1, 1, 1),\n nn.ReLU(inplace=True))\n\n self.layer1 = self._make_layer(BasicBlock, 32, 3, 1, 1, 1)\n self.layer2 = self._make_layer(BasicBlock, 64, 16, 2, 1, 1)\n self.layer3 = self._make_layer(BasicBlock, 128, 3, 1, 1, 1)\n self.layer4 = self._make_layer(BasicBlock, 128, 3, 1, 1, 2)\n\n if self.concat_feature:\n self.lastconv = nn.Sequential(convbn(320, 128, 3, 1, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, concat_feature_channel, kernel_size=1, padding=0, stride=1,\n bias=False))\n\n def _make_layer(self, block, planes, blocks, stride, pad, dilation):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion), )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, pad, dilation))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, 1, None, pad, dilation))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n #x=x.repeat(1,3,1,1)\n x = self.firstconv(x)\n #x[0,13,:,:]=0\n #print(x[:,14,:,:])\n l1 = self.layer1(x)\n \n l2 = self.layer2(l1)\n l3 = self.layer3(l2)\n\n #l3[0,0,:,:]=0\n l4 = self.layer4(l3) \n \n gwc_feature = torch.cat((l2, l3, l4), dim=1)\n fea_list=[x,l1,l2,l3,l4]\n # print(x.shape)\n # print(l1.shape)\n # print(l4.shape) \n\n if not self.concat_feature:\n return {\"gwc_feature\": gwc_feature}\n else:\n # print(\"!!!!!!!!!!\")\n concat_feature = self.lastconv(gwc_feature)\n return {\"gwc_feature\": gwc_feature, \"concat_feature\": concat_feature,\"feature\":fea_list}\n\n\nclass hourglass(nn.Module):\n def __init__(self, in_channels):\n super(hourglass, self).__init__()\n\n self.conv1 = nn.Sequential(convbn_3d(in_channels, in_channels * 2, 3, 2, 1),\n nn.ReLU(inplace=True))\n\n self.conv2 = nn.Sequential(convbn_3d(in_channels * 2, in_channels * 2, 3, 1, 1),\n nn.ReLU(inplace=True))\n\n self.conv3 = nn.Sequential(convbn_3d(in_channels * 2, in_channels * 4, 3, 2, 1),\n nn.ReLU(inplace=True))\n\n self.conv4 = nn.Sequential(convbn_3d(in_channels * 4, in_channels * 4, 3, 1, 1),\n nn.ReLU(inplace=True))\n\n self.conv5 = nn.Sequential(\n nn.ConvTranspose3d(in_channels * 4, in_channels * 2, 3, padding=1, output_padding=1, stride=2, bias=False),\n nn.BatchNorm3d(in_channels * 2))\n\n self.conv6 = nn.Sequential(\n nn.ConvTranspose3d(in_channels * 2, in_channels, 3, padding=1, output_padding=1, stride=2, bias=False),\n nn.BatchNorm3d(in_channels))\n\n self.redir1 = convbn_3d(in_channels, in_channels, kernel_size=1, stride=1, pad=0)\n self.redir2 = convbn_3d(in_channels * 2, in_channels * 2, kernel_size=1, stride=1, pad=0)\n \n \n \n\n def forward(self, x):\n conv1 = self.conv1(x)\n conv2 = self.conv2(conv1)\n\n conv3 = self.conv3(conv2)\n conv4 = self.conv4(conv3)\n\n conv5 = F.relu(self.conv5(conv4) + self.redir2(conv2), inplace=True)\n conv6 = F.relu(self.conv6(conv5) + self.redir1(x), inplace=True)\n\n return conv6\n\n\nclass GwcNet(nn.Module):\n def __init__(self, args, use_concat_volume=True):\n super(GwcNet, self).__init__()\n self.maxdisp = args.maxdisp\n self.use_concat_volume = use_concat_volume\n\n self.num_groups = 40\n\n if self.use_concat_volume:\n self.concat_channels = 12\n self.feature_extraction = feature_extraction(concat_feature=True,\n concat_feature_channel=self.concat_channels)\n else:\n self.concat_channels = 0\n self.feature_extraction = feature_extraction(concat_feature=False)\n\n self.dres0 = nn.Sequential(convbn_3d(self.num_groups + self.concat_channels * 2, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True))\n\n self.dres1 = nn.Sequential(convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n convbn_3d(32, 32, 3, 1, 1))\n\n self.dres2 = hourglass(32)\n\n self.dres3 = hourglass(32)\n\n self.dres4 = hourglass(32)\n\n self.classif0 = nn.Sequential(convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv3d(32, 1, kernel_size=3, padding=1, stride=1, bias=False))\n\n self.classif1 = nn.Sequential(convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv3d(32, 1, kernel_size=3, padding=1, stride=1, bias=False))\n\n self.classif2 = nn.Sequential(convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv3d(32, 1, kernel_size=3, padding=1, stride=1, bias=False))\n\n self.classif3 = nn.Sequential(convbn_3d(32, 32, 3, 1, 1),\n nn.ReLU(inplace=True),\n nn.Conv3d(32, 1, kernel_size=3, padding=1, stride=1, bias=False))\n \n\n for m in self.modules():\n # m.weight.requires_grad=False\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n #m.weight.requires_grad=False\n elif isinstance(m, nn.Conv3d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n #m.weight.requires_grad=False\n elif isinstance(m, nn.BatchNorm2d):\n #m.weight.requires_grad=True\n #m.bias.requires_grad=True\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm3d):\n #m.weight.requires_grad=True\n #m.bias.requires_grad=True\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.bias.data.zero_()\n # m.bias.requires_grad=False\n \n #bts part\n feat_out_channels = [128, 32, 64, 128, 128]\n num_features = 192\n \n self.upconv5 = upconv(feat_out_channels[4], num_features)\n self.bn5 = nn.BatchNorm2d(num_features, momentum=0.01, affine=True, eps=1.1e-5)\n \n self.conv5 = torch.nn.Sequential(nn.Conv2d(num_features + feat_out_channels[3], num_features, 3, 1, 1, bias=False),\n nn.ELU())\n self.upconv4 = upconv(num_features, num_features // 2)\n self.bn4 = nn.BatchNorm2d(num_features // 2, momentum=0.01, affine=True, eps=1.1e-5)\n self.conv4 = torch.nn.Sequential(nn.Conv2d(num_features // 2 + feat_out_channels[2], num_features // 2, 3, 1, 1, bias=False),\n nn.ELU())\n self.bn4_2 = nn.BatchNorm2d(num_features // 2, momentum=0.01, affine=True, eps=1.1e-5)\n \n self.daspp_3 = atrous_conv(num_features // 2, num_features // 4, 3, apply_bn_first=False)\n self.daspp_6 = atrous_conv(num_features // 2 + num_features // 4 + feat_out_channels[2], num_features // 4, 6)\n self.daspp_12 = atrous_conv(num_features + feat_out_channels[2], num_features // 4, 12)\n self.daspp_18 = atrous_conv(num_features + num_features // 4 + feat_out_channels[2], num_features // 4, 18)\n self.daspp_24 = atrous_conv(num_features + num_features // 2 + feat_out_channels[2], num_features // 4, 24)\n self.daspp_conv = torch.nn.Sequential(nn.Conv2d(num_features + num_features // 2 + num_features // 4, num_features // 4, 3, 1, 1, bias=False),\n nn.ELU())\n self.reduc8x8 = reduction_1x1(num_features // 4, num_features // 4, self.maxdisp)\n self.lpg8x8 = local_planar_guidance(8)\n \n self.upconv3 = upconv(num_features // 4, num_features // 4)\n self.bn3 = nn.BatchNorm2d(num_features // 4, momentum=0.01, affine=True, eps=1.1e-5)\n self.conv3 = torch.nn.Sequential(nn.Conv2d(num_features // 4 + feat_out_channels[1] + 1, num_features // 4, 3, 1, 1, bias=False),\n nn.ELU())\n self.reduc4x4 = reduction_1x1(num_features // 4, num_features // 8, self.maxdisp)\n self.lpg4x4 = local_planar_guidance(4)\n \n self.upconv2 = upconv(num_features // 4, num_features // 8)\n self.bn2 = nn.BatchNorm2d(num_features // 8, momentum=0.01, affine=True, eps=1.1e-5)\n self.conv2 = torch.nn.Sequential(nn.Conv2d(num_features // 8 + feat_out_channels[0] + 1, num_features // 8, 3, 1, 1, bias=False),\n nn.ELU())\n \n self.reduc2x2 = reduction_1x1(num_features // 8, num_features // 16, self.maxdisp)\n self.lpg2x2 = local_planar_guidance(2)\n \n self.upconv1 = upconv(num_features // 8, num_features // 16)\n self.reduc1x1 = reduction_1x1(num_features // 16, num_features // 32, self.maxdisp, is_final=True)\n self.conv1 = torch.nn.Sequential(nn.Conv2d(num_features // 16 + 4, num_features // 16, 3, 1, 1, bias=False),\n nn.ELU())\n self.get_depth = torch.nn.Sequential(nn.Conv2d(num_features // 16, 1, 3, 1, 1, bias=False),\n nn.Sigmoid())\n\n def forward(self, left, right):\n focal=0 # \\?????\n #left_edge=y_gradient_1order(x_gradient_1order(left))\n #right_edge=y_gradient_1order(x_gradient_1order(right))\n #mask=left_edge>0.5\n #print(left,right)\n #right=right/2.0\n #pred_tra=mutual_info_pred(left,right,self.maxdisp)\n #print(\"left\")\n features_left = self.feature_extraction(left)\n #print(\"right\")\n features_right = self.feature_extraction(right)\n\n gwc_volume = build_gwc_volume(features_left[\"gwc_feature\"], features_right[\"gwc_feature\"], self.maxdisp // 4,\n self.num_groups)\n # add by yyx\n # \"gwc_feature\": gwc_feature, \"concat_feature\": concat_feature,\"feature\":fea_list\n # fea_list=[x,l1,l2,l3,l4]\n left_fea=features_left[\"feature\"]\n# fea_list=[x,l1,l2,l3,l4] torch.Size([1, 32, 256, 480]) │amp: 1604494044.58921).\n# fea_list=[x,l1,l2,l3,l4] torch.Size([1, 32, 256, 480]) │\n# fea_list=[x,l1,l2,l3,l4] torch.Size([1, 64, 128, 240]) ├──────────────────────────────────────────────────────────\n# fea_list=[x,l1,l2,l3,l4] torch.Size([1, 128, 128, 240]) │Every 1.0s: gpustat -cpu Sun Nov 15 13:05:32 2020\n# fea_list=[x,l1,l2,l3,l4] torch.Size([1, 128, 128, 240])\n right_fea=features_right[\"feature\"]\n if self.use_concat_volume:\n concat_volume = build_concat_volume(features_left[\"concat_feature\"], features_right[\"concat_feature\"],\n self.maxdisp // 4)\n volume = torch.cat((gwc_volume, concat_volume), 1)\n else:\n volume = gwc_volume\n\n cost0 = self.dres0(volume)\n cost0 = self.dres1(cost0) + cost0\n print(\"cost0\",cost0.shape)\n out1 = self.dres2(cost0)#to 1/8\n print(\"out1\",out1.shape)\n out2 = self.dres3(out1)#to 1/4\n print(\"out2\",out2.shape)\n out3 = self.dres4(out2)#to 1/2\n print(\"out3\",out3.shape)\n#add bts\n #for 8*8 to 4*4\n cost0_cla = self.classif0(cost0)\n cost0_cla = torch.squeeze(cost0_cla, 1)\n \n reduc8x8 = self.reduc8x8(cost0_cla)\n plane_normal_8x8 = reduc8x8[:, :3, :, :]\n plane_normal_8x8 = F.normalize(plane_normal_8x8, 2, 1)\n plane_dist_8x8 = reduc8x8[:, 3, :, :]\n plane_eq_8x8 = torch.cat([plane_normal_8x8, plane_dist_8x8.unsqueeze(1)], 1)\n depth_8x8 = self.lpg8x8(plane_eq_8x8, focal)\n depth_8x8_scaled = depth_8x8.unsqueeze(1) / self.maxdisp\n depth_8x8_scaled_ds = F.interpolate(depth_8x8_scaled, scale_factor=0.25, mode='nearest')\n \n upconv1 = F.upsample(cost0, [self.maxdisp//4, left.size()[2]//4, left.size()[3]//4], mode='trilinear')\n print(\"upconv1\",upconv1.shape)\n # pconv1 = self.bn3(upconv1)\n group_size1=(upconv1.shape)[1]\n print(\"target\",upconv1.shape)\n print(\"after change\",left_fea[4].unsqueeze(1).expand(-1,group_size1,-1,-1,-1).shape)\n print(\"after change2\",depth_8x8_scaled_ds.unsqueeze(1).expand(-1,group_size1,-1,-1,-1).shape)\n concat1 = torch.cat([upconv1, left_fea[4].unsqueeze(1).expand(-1,group_size1,-1,-1,-1), depth_8x8_scaled_ds.unsqueeze(1).expand(-1,group_size1,-1,-1,-1)], dim=2)\n # upconv3, torch.Size([1, 128, 64, 128])\n # skip1, torch.Size([1, 96, 64, 128])\n # skip0[1, 96, 128, 256]\n # depth_8x8_scaled_ds, torch.Size([1, 1, 64, 128])\n out1= self.conv3(concat1)\n \n #for 4*4 to 2*2\n cost1_cla = self.classif0(out1)\n cost1_cla = torch.squeeze(cost1_cla, 1)\n \n reduc4x4 = self.reduc4x4(cost1_cla)\n plane_normal_4x4 = reduc4x4[:, :3, :, :]\n plane_normal_4x4 = F.normalize(plane_normal_4x4, 2, 1)\n plane_dist_4x4 = reduc4x4[:, 3, :, :]\n plane_eq_4x4 = torch.cat([plane_normal_4x4, plane_dist_4x4.unsqueeze(1)], 1)\n depth_4x4 = self.lpg4x4(plane_eq_4x4, focal)\n depth_4x4_scaled = depth_4x4.unsqueeze(1) / self.maxdisp\n depth_4x4_scaled_ds = F.interpolate(depth_4x4_scaled, scale_factor=0.5, mode='nearest')\n \n upconv2 = F.upsample(cost1, [self.maxdisp//2, left.size()[2]//2, left.size()[3]//2], mode='trilinear') # H/2\n group_size2=(upconv2.shape)[1]\n # upconv2 = self.bn2(upconv2)\n concat2 = torch.cat([upconv2, left_fea[1].unsqueeze(1).expand(-1,group_size2,-1,-1,-1), depth_4x4_scaled_ds.unsqueeze(1).expand(-1,group_size2,-1,-1,-1)], dim=2)\n # concat2 = torch.cat([upconv2, left_fea[1], depth_4x4_scaled_ds], dim=1)\n out2 = self.conv2(concat2)\n \n \n #for 2*2 to 1*1\n cost2_cla = self.classif0(out2)\n cost2_cla = torch.squeeze(cost2_cla, 1)\n \n reduc2x2 = self.reduc2x2(cost2_cla)\n plane_normal_2x2 = reduc2x2[:, :3, :, :]\n plane_normal_2x2 = F.normalize(plane_normal_2x2, 2, 1)\n plane_dist_2x2 = reduc2x2[:, 3, :, :]\n plane_eq_2x2 = torch.cat([plane_normal_2x2, plane_dist_2x2.unsqueeze(1)], 1)\n depth_2x2 = self.lpg2x2(plane_eq_2x2, focal)\n depth_2x2_scaled = depth_2x2.unsqueeze(1) / self.maxdisp\n \n upconv3 = F.upsample(cost3, [self.maxdisp, left.size()[2], left.size()[3]], mode='trilinear')\n group_size3=(upconv3.shape)[1]\n reduc1x1 = self.reduc1x1(upconv3)\n concat3 = torch.cat([upconv3, reduc1x1, depth_2x2_scaled.unsqueeze(1).expand(-1,group_size3,-1,-1,-1), depth_4x4_scaled.unsqueeze(1).expand(-1,group_size3,-1,-1,-1), depth_8x8_scaled.unsqueeze(1).expand(-1,group_size3,-1,-1,-1)], dim=2)\n out3 = self.conv1(concat3)\n\n if self.training:\n #if True:\n cost0 = self.classif0(cost0)\n # print(\"after classif\",cost0.shape)\n cost1 = self.classif1(out1)\n cost2 = self.classif2(out2)\n cost3 = self.classif3(out3)\n\n cost0 = F.upsample(cost0, [self.maxdisp, left.size()[2], left.size()[3]], mode='trilinear')\n # print(\"after upsample\",cost0.shape)\n cost0 = torch.squeeze(cost0, 1)\n # print(\"after squeeze\",cost0.shape)\n pred0 = F.softmax(cost0, dim=1)\n pred0 = disparity_regression(pred0, self.maxdisp)\n\n cost1 = F.upsample(cost1, [self.maxdisp, left.size()[2], left.size()[3]], mode='trilinear')\n cost1 = torch.squeeze(cost1, 1)\n pred1 = F.softmax(cost1, dim=1)\n pred1 = disparity_regression(pred1, self.maxdisp)\n\n cost2 = F.upsample(cost2, [self.maxdisp, left.size()[2], left.size()[3]], mode='trilinear')\n cost2 = torch.squeeze(cost2, 1)\n pred2 = F.softmax(cost2, dim=1)\n pred2 = disparity_regression(pred2, self.maxdisp)\n\n cost3 = F.upsample(cost3, [self.maxdisp, left.size()[2], left.size()[3]], mode='trilinear')\n cost3 = torch.squeeze(cost3, 1)\n pred3 = F.softmax(cost3, dim=1)\n pred3 = disparity_regression(pred3, self.maxdisp)\n return [pred0, pred1, pred2, pred3]\n\n else:\n cost3 = self.classif3(out3)\n cost3 = F.upsample(cost3, [self.maxdisp, left.size()[2], left.size()[3]], mode='trilinear')\n cost3 = torch.squeeze(cost3, 1)\n pred3 = F.softmax(cost3, dim=1)\n # _,d,H,W=pred3.size()\n # for h in range(0,H,10):\n # for w in range(0,W,20):\n # point_disp=pred3[0,:,h,w]\n # distribution=point_disp.view(-1)\n # plt.xlabel('Disparity')\n # plt.ylabel('Probability')\n # x=np.arange(len(distribution))\n # print(h+1,\"_\",w+1,distribution)\n # plt.xlim(xmax=192, xmin=0)\n # plt.ylim(ymax=1,ymin=0)\n \n # #plt.hist(x=distribution, bins=d, color='#0504aa',alpha=0.7, rwidth=0.9)\n # plt.bar(x, distribution,fc='r')\n # filename='fea_map/kitti/disparity_distribution_4/'+str(h+1)+'_'+str(w+1)+'.png'\n # plt.savefig(filename)\n # plt.close()\n confidence,index=torch.max(pred3,dim=1)\n pred3 = disparity_regression(pred3, self.maxdisp)\n return [pred3],confidence,index\n #return pred_tra\n\n\ndef GwcNet_G(d):\n return GwcNet(d, use_concat_volume=False)\n\n\ndef GwcNet_GC(d):\n return GwcNet(d, use_concat_volume=True)\n\n\n\n# def entropy(labels):\n#\n# if len(labels) == 0:\n# return 1.0\n# label_idx = np.unique(labels, return_inverse=True)[1]\n# pi = np.bincount(label_idx).astype(np.float64)\n# #print(\"!!!\",pi)\n# #pi = pi[pi > 0]\n# pi_sum = np.sum(pi)\n# # log(a / b) should be calculated as log(a) - log(b) for\n# # possible loss of precision\n# entro=-((pi / pi_sum) * (np.log(pi) - log(pi_sum)))\n# entro = np.where(np.isnan(entro), 0, entro)\n# return entro\ndef entropy(pi):\n #pi = pi[pi >= 0]\n #print(pi)\n pi_sum = np.sum(pi)\n # log(a / b) should be calculated as log(a) - log(b) for\n # possible loss of precision\n join_entropy=-((pi / pi_sum) * (np.log(pi) - log(pi_sum)))\n #print(join_entropy)\n #zero=np.zeros([1,6,6])\n join_entropy=np.where(np.isnan(join_entropy),0,join_entropy)\n #join_entropy[0, 0] = 0\n return join_entropy\ndef mutual_entropy(a,b,bin_num):\n a=np.array(a)\n b=np.array(b)\n #print(a.shape)\n a_hist=np.histogram(a,bins=bin_num+1,range=(0,bin_num))[0]\n b_hist = np.histogram(b, bins=bin_num+1, range=(0, bin_num))[0]\n #print(\"!!!!!\",a.shape,a_hist.shape)\n #a = a.reshape(1,-1)\n #b = b.reshape(1,-1)\n # print(a.ravel().shape,b.ravel().shape)\n ab_hist=np.histogram2d(a.ravel(),b.ravel(),bins=(bin_num+1,bin_num+1),range=[(0,bin_num),(0,bin_num)])[0]\n # print(ab_hist.shape)\n # print(\"a entropy\",entropy(a_hist))\n # print(\"b entropy\",entropy(b_hist))\n # print(\"ab entropy\",entropy(ab_hist)[7])\n # a_entropy=np.repeat(entropy(a_hist),[bin_num],axis=0)\n # b_entropy = np.repeat(entropy(b_hist),bin_num,axis=0)\n # print(a_entropy.shape)\n # mutual_entro=np.zeros([bin_num,bin_num])\n # for b in range(bin_num):\n # mutual_entro[b]=entropy(a_hist)+entropy(b_hist)-(entropy(ab_hist))[b]\n mutual_entro=[entropy(a_hist),entropy(b_hist),entropy(ab_hist)]\n #print(\"!!\",mutual_entro[0].shape)\n return mutual_entro\n\ndef mutual_info_pred(left, right,maxdisp):\n # left=(left+0.5).floor()\n # right=(right+0.5).floor()\n #print(left,right)\n mutual_info=mutual_entropy(left,right,255)\n B, C, H, W = left.shape\n volume = left.new_zeros([B, maxdisp, H, W])\n for x in range(H):\n for y in range(W):\n for i in range(maxdisp):\n if x<=i:\n volume[:,i,x,y]=0\n else:\n left_i=int(left[0,0,x,y])\n right_i=int(right[0,0,x-i,y])\n # print(left_i,right_i)\n #print(mutual_info[0].shape)\n volume[0,i,x,y]=mutual_info[0][left_i]+mutual_info[1][right_i]-mutual_info[2][left_i,right_i]\n #print(volume[0,i,x,y])\n volume=torch.softmax(volume,dim=1)\n confidence,pred=torch.max(volume,dim=1)\n pred=pred.float()\n pred_sub=disparity_regression(volume,maxdisp)\n return pred\n\ndef x_gradient_1order(img):\n img = img.permute(0,2,3,1)\n img_l = img[:,:,1:,:] - img[:,:,:-1,:]\n img_r = img[:,:,-1,:] - img[:,:,-2,:]\n img_r = img_r.unsqueeze(2)\n img = torch.cat([img_l, img_r], 2).permute(0, 3, 1, 2)\n return img\n\ndef y_gradient_1order(img):\n # pdb.set_trace()\n img = img.permute(0,2,3,1)\n img_u = img[:,1:,:,:] - img[:,:-1,:,:]\n img_d = img[:,-1,:,:] - img[:,-2,:,:]\n img_d = img_d.unsqueeze(1)\n img = torch.cat([img_u, img_d], 1).permute(0, 3, 1, 2)\n return img\n\ndef gradient_1order(x,h_x=None,w_x=None):\n if h_x is None and w_x is None:\n h_x = x.size()[2]\n w_x = x.size()[3]\n r = F.pad(x, (0, 1, 0, 0))[:, :, :, 1:]\n l = F.pad(x, (1, 0, 0, 0))[:, :, :, :w_x]\n t = F.pad(x, (0, 0, 1, 0))[:, :, :h_x, :]\n b = F.pad(x, (0, 0, 0, 1))[:, :, 1:, :]\n xgrad = torch.pow(torch.pow((r - l) * 0.5, 2) + torch.pow((t - b) * 0.5, 2), 0.5)\n return xgrad\n","sub_path":"models/gwcnet_old.py","file_name":"gwcnet_old.py","file_ext":"py","file_size_in_byte":29999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"596392404","text":"from pyspark import SparkContext\nfrom pyspark import SparkConf\nfrom pyspark.streaming import StreamingContext\n\nsc = SparkContext(\"local\", \"Spark_streaming_F\")\nssc = StreamingContext(sc,20)\nlines = ssc.textFileStream('/home/abhilash/Documents/files/streaming_data')\nwords = lines.flatMap(lambda s : s.split(\" \"))\nwordcounts = words.map(lambda w : (w,1)).reduceByKey(lambda x,y:x+y)\nwordcounts.pprint()\nssc.start()\nssc.awaitTermination()\n\n\n","sub_path":"Spark_streaming_F.py","file_name":"Spark_streaming_F.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"296714072","text":"import numpy as np\nfrom numba import njit\n\n@njit(\"void()\")\ndef main():\n trial = 10\n rec = np.empty((trial, 3))\n #rec = np.empty(3)\n rec[:,:] = 2.2, 3.3, 4.4\n # for i in range(trial):\n # rec[i] = 1\n print(rec)\n\n\n\nif __name__ == '__main__':\n \n main()","sub_path":"numba_test.py","file_name":"numba_test.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"481512411","text":"#!/usr/bin/env python\nimport sys, os, json, cStringIO, tempfile, logging, traceback, codecs, math\nfrom datetime import datetime, timedelta\nimport wordcloud_multiple\n\nclass WordCloudChronological(wordcloud_multiple.MultipleWordClouds):\n\t\"\"\"\n\tGenerate word clouds based on time interval\n\t\"\"\"\n\tdef _basic_params(self):\n\t\tself.name = \"wordcloud_chronological\"\n\t\tself.template_filename = os.path.join(self.cwd, \"templates\", \"wordcloud_multiple.html\")\n\t\tself.width = \"483\"\n\t\tself.height = \"300\"\n\t\tself.fontsize = \"[10,32]\"\n\t\tself.n = 100\n\t\tself.tfidf_scoring = False\n\t\tself.MWW = False\n\t\tself.dunning = False\n\t\tif len(self.extra_args) == 1:\n\t\t\tself.interval = self.extra_args[0]\n\t\telif len(self.extra_args) > 1:\n\t\t\tif self.extra_args[0] == \"tfidf\":\n\t\t\t\tself.tfidf_scoring = True\n\t\t\telif self.extra_args[0] == \"mww\":\n\t\t\t\tself.tfidf_scoring = True\n\t\t\t\tself.MWW = True\n\t\t\telif self.extra_args[0] == \"dunning\":\n\t\t\t\tself.tfidf_scoring = True\n\t\t\t\tself.dunning = True\n\t\t\tself.interval = self.extra_args[1]\n\t\telse:\n\t\t\tself.interval = \"90\"\n\n\tdef _split_into_labels(self):\n\t\tdatestr_to_datetime = {}\n\t\tfor filename in self.metadata.keys():\n\t\t\tdate_str = self.metadata[filename][\"date\"]\n\t\t\tcleaned_date = date_str[0:10]\n\t\t\tif \"-00\" in cleaned_date:\n\t\t\t\tcleaned_date = cleaned_date[0:4] + \"-01-01\"\n\t\t\tdatestr_to_datetime[date_str] = datetime.strptime(cleaned_date, \"%Y-%m-%d\")\n\t\tdatetimes = sorted(datestr_to_datetime.values())\n\t\tstart_date = datetimes[0]\n\t\tend_date = datetimes[-1]\n\n\t\tif self.interval.isdigit():\n\t\t\tinterval = timedelta(int(self.interval))\n\t\telse:\n\t\t\tinterval = timedelta(90)\n\n\t\tintervals = []\n\t\tinterval_names = []\n\t\tstart = end = start_date\n\t\twhile end <= end_date:\n\t\t\tend += interval\n\t\t\tintervals.append((start,end))\n\t\t\tinterval_names.append(start.isoformat()[0:10].replace('-','/') + '-' + end.isoformat()[0:10].replace('-','/'))\n\t\t\tstart = end\n\n\t\tfor filename, metadata in self.metadata.iteritems():\n\t\t\tlabel = \"\"\n\t\t\tfor i in range(len(intervals)):\n\t\t\t\tinterval = intervals[i]\n\t\t\t\tif interval[0] <= datestr_to_datetime[metadata[\"date\"]] < interval[1]:\n\t\t\t\t\tlabel = interval_names[i]\n\t\t\t\t\tbreak\n\t\t\tif label not in self.labels:\n\t\t\t\tself.labels[label] = set()\n\t\t\tself.labels[label].add(filename)\n\nif __name__ == \"__main__\":\n\ttry:\n\t\tprocessor = WordCloudChronological(track_progress = True)\n\t\tprocessor.process()\n\texcept:\n\t\tlogging.error(traceback.format_exc())","sub_path":"chrome/content/papermachines/processors/wordcloud_chronological.py","file_name":"wordcloud_chronological.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"4517391","text":"from Instructions.instruction import *\n\nclass ADD(Instruction):\n\n\tdef __init__(self, currentInstruction):\n\t\tself.listeners = []\n\t\tself.opcode = currentInstruction.opcode\n\t\tself.rawInstruction = currentInstruction.rawInstruction\n\t\tself.operands = currentInstruction.operands\n\t\tself.decodedOperands = []\n\t\tself.destinationRegister = None\n\t\tself.result = None\n\t\tself.latency = 1\n\t\tself.instructionType = InstructionType.ALU\n\n\tdef execute(self, processor):\n\t\tself.result = self.decodedOperands[1] + self.decodedOperands[2]\n\n\tdef writeback(self, processor):\n\t\tif self.result == None:\n\t\t\traise Exception(\"Result hasn't yet been calculated. Has execute been called?\")\n\n\t\tprocessor.registers[self.destinationRegister] = self.result\n\n\t\tsuper(ADD, self).writeback(processor)\n\n","sub_path":"Instructions/ADD.py","file_name":"ADD.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"420040331","text":"#coding=utf-8\n\nimport unittest\n\n\"\"\"\n\nGraph Valid Tree\n\nGiven n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function \nto check whether these edges make up a valid tree.\n\n Notice\n\nYou can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [\n1, 0] and thus will not appear together in edges.\n\nHave you met this question in a real interview? Yes\nExample\nGiven n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.\n\nGiven n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.\n\nTags \nDepth First Search Facebook Zenefits Union Find Breadth First Search Google\nRelated Problems \nMedium Connecting Graph 40 %\nMedium Connected Component in Undirected Graph\n\n\"\"\"\n\n\n\nclass Solution:\n # @param {int} n an integer\n # @param {int[][]} edges a list of undirected edges\n # @return {boolean} true if it's a valid tree, or false\n \"\"\"\n There are two key points:\n 1. can use union find\n 2. the standard of a valid tree (using union find): \n a. single root(all share one root), \n b. no cycle in the graph \n How to check 2? 2a: after adding all edges, all roots should be the same. 2b: while adding edges, no shared parents \n ( if new edge is between two nodes that already in same tree, it is creating a cycle) \n ----- according to ref, a good property of undirected graph that is a tree is that : len(edges) = n-1, check the ref \n \"\"\"\n def validTree(self, n, edges):\n # Write your code here\n if not edges:\n return True if n == 1 else False\n if n < 1:\n return False #True, should be careful and distinguish cases, check case 3 and case 4\n self.roots = [x for x in range(n)]\n for edge in edges:\n a, b = edge[0], edge[1]\n ar = self.find(a)\n br = self.find(b)\n if ar == br:\n return False\n else:\n self.roots[br] = ar\n parent = self.find(0) #self.roots[0], check case6, case5\n for i in range(1,n):\n if self.find(i) != parent:\n return False\n return True\n\n def find(self, x):\n if self.roots[x] == x:\n return x\n else:\n self.roots[x] = self.find(self.roots[x])\n return self.roots[x]\n\n\n\n\nclass SolutionTester(unittest.TestCase):\n def setUp(self):\n self.sol = Solution()\n\n def test_case1(self):\n n = 5\n edges = [[0, 1], [0, 2], [0, 3], [1, 4]]\n answer = True\n result = self.sol.validTree(n, edges)\n self.assertEqual(answer, result)\n\n def test_case2(self):\n n = 5\n edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]\n answer = False\n result = self.sol.validTree(n, edges)\n self.assertEqual(answer, result)\n\n\n def test_case3(self): #====>\n n = 2\n edges = []\n answer = False\n result = self.sol.validTree(n, edges)\n self.assertEqual(answer, result)\n\n def test_case4(self): #====>\n n = 1\n edges = []\n answer = True\n result = self.sol.validTree(n, edges)\n self.assertEqual(answer, result)\n\n def test_case5(self): #====>\n n = 3\n edges = [[0,1]]\n answer = False\n result = self.sol.validTree(n, edges)\n self.assertEqual(answer, result)\n\n def test_case6(self): #====>\n n = 8\n edges = [[0,1],[1,2],[3,2],[4,3],[4,5],[5,6],[6,7]]\n answer = True\n result = self.sol.validTree(n, edges)\n self.assertEqual(answer, result)\n\ndef main():\n suite = unittest.TestLoader().loadTestsFromTestCase(SolutionTester)\n unittest.TextTestRunner(verbosity=2).run(suite)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n#-*- coding:utf-8 -*-\n\n\"\"\"\n\nclass Solution:\n # @param {int} n an integer\n # @param {int[][]} edges a list of undirected edges\n # @return {boolean} true if it's a valid tree, or false\n def validTree(self, n, edges):\n # Write your code here\n root = [i for i in range(n)]\n for i in edges:\n root1 = self.find(root, i[0])\n root2 = self.find(root, i[1])\n if root1 == root2:\n return False\n else:\n root[root1] = root2\n return len(edges) == n - 1\n \n def find(self, root, e):\n if root[e] == e:\n return e\n else:\n root[e] = self.find(root, root[e])\n return root[e]\n\n\n\n\"\"\"","sub_path":"mjbeto/graph_valid_tree.py","file_name":"graph_valid_tree.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"224626539","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = \"users\"\nurlpatterns = [\n url(\n regex=r\"^logged/$\",\n view=views.UserLoggedin.as_view(),\n name=\"logged\",\n ),\n url(\n regex=r\"^logged2/$\",\n view=views.checkLogin,\n name=\"logged\",\n ),\n]\n","sub_path":"srim/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"528904214","text":"'''\n 子集合和问题表示一组非负整数,和一个给定值,\n 确定给定集合的所有可能子集,它们的和等于给定值。\n 所选数字的和必须等于给定的数字M,并且一个数字只能使用一次。\n'''\n\n\ndef 生成定值子集(集合: list, 给定值: int):\n 结果, 子集 = list(), list()\n 当前元素 = 0\n __生成定值子集(集合, 给定值, 当前元素, 子集, 结果)\n return 结果\n\ndef __生成定值子集(集合, 给定值, 当前元素, 子集, 结果 = list()):\n '''\n 创建一个状态空间树,使用DFS遍历每个分支。\n 当下面给出的两个条件之一满足时,它终止节点的分支。\n 该算法遵循深度优先搜索,在节点不可分支时回溯。\n '''\n if sum(子集) > 给定值 or (sum(集合[当前元素:]) + sum(子集)) < 给定值:\n return\n elif sum(子集) == 给定值:\n 结果.append(子集)\n return\n else:\n for 当前元素 in range(当前元素,len(集合)):\n __生成定值子集(集合, 给定值, 当前元素 + 1, 子集 + [集合[当前元素]], 结果)\n\n'''\nremove the comment to take an input from the user \n\nprint(\"Enter the elements\")\n集合 = list(map(int, input().split()))\nprint(\"Enter 给定值 sum\")\n给定值 = int(input())\n\n'''\nif __name__ == '__main__':\n 集合 = [3, 34, 4, 12, 5, 2]\n 给定值 = 9\n 结果 = 生成定值子集(集合,给定值)\n print(*结果)","sub_path":"回溯法/生成定值子集.py","file_name":"生成定值子集.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"428803721","text":"from common.myunit import StartEnd\nimport unittest\nimport logging\nfrom businessView.loginView import Login\n\n\n\nclass Testlogin(StartEnd):\n csv_file='../data/login.csv'\n\n #@unittest.skip(\"test_login_jimi001\")\n def test_jimi_login001(self):\n '''登录测试'''\n logging.info(\"====开始执行test_login_jimi001用例\")\n login = Login(self.driver)\n data=login.get_csv_data(self.csv_file,4)\n login.action(data[0],data[1])\n self.assertTrue(login.Testin_login())\n\n @unittest.skip(\"test_login_jimi001\")\n def test_login_jimi002(self):\n '''登录测试'''\n logging.info(\"====开始执行test_login_jimi002用例\")\n login = Login(self.driver)\n data = login.get_csv_data(self.csv_file, 3)\n login.action(data[0], data[1])\n self.assertTrue(login.Testin_login(),msg=False)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test_case/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"481888329","text":"from django.http import HttpResponse\nfrom django.core.serializers import serialize\nfrom urllib import parse\nfrom uuid import UUID\nimport json\nfrom src.settings import DEBUG\n\nALLOWED_ORIGIN = [\"https://the-form.io\"]\n\n# 요청한 origin이 the-form.io나 dev.the-form.io 프론트엔드인지 식별 - 임시\ndef is_origin_valid(request):\n if DEBUG:\n return True\n\n print(request.META)\n if \"HTTP_ORIGIN\" not in request.META:\n return False\n if request.META[\"HTTP_ORIGIN\"] not in ALLOWED_ORIGIN:\n return False\n return True\n\n\n# 이메일 유효성 검사 헬퍼 함수\ndef is_valid_email(email):\n from django.core.validators import validate_email\n from django.core.exceptions import ValidationError\n\n try:\n validate_email(email)\n return True\n except ValidationError as e:\n print(\"bad email, details:\", e)\n return False\n\n\n# 딕셔너리를 JSON으로 전송하는 헬퍼 함수\ndef send_json(data):\n res = json.dumps(data, default=str)\n return HttpResponse(res, content_type=\"application/json\", status=data[\"status\"])\n\n\n# 가변 인자로 추출된 딕셔너리를 받아오는 헬퍼 함수\ndef pop_args(dic, *args):\n return {arg: dic[arg] if arg in dic else None for arg in args}\n\n\n# QuerySet 객체를 dict 객체로 변환하는 헬퍼 함수\ndef to_dict(queryset):\n return json.loads(serialize(\"json\", queryset))\n\n\ndef pk_to_dict(objects, pk):\n return to_dict(objects.filter(pk=pk))\n\n\n# request.body로 받아왔을��� json을 dict로 변환하는 함수\ndef json_to_dict(data):\n return json.loads(data.decode(\"utf-8\"))\n\n\ndef is_valid_uuid(uuid_to_test, version=4):\n \"\"\"\n Check if uuid_to_test is a valid UUID.\n\n Parameters\n ----------\n uuid_to_test : str\n version : {1, 2, 3, 4}\n\n Returns\n -------\n `True` if uuid_to_test is a valid UUID, otherwise `False`.\n\n Examples\n --------\n >>> is_valid_uuid('c9bf9e57-1685-4c89-bafb-ff5af830be8a')\n True\n >>> is_valid_uuid('c9bf9e58')\n False\n \"\"\"\n\n try:\n uuid_obj = UUID(uuid_to_test, version=version)\n except ValueError:\n return False\n return str(uuid_obj) == uuid_to_test\n","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"305573992","text":"\"\"\"OrderedList File Program\n\nThis program is used to take input from file and user can see the content of file\nthen user can search for data that he is looking for .if the user data is found then\nthat data will be removed from OrderedList and saves into file and vice versa\nand at last user can see the updated content of file\n\nAuthor:\n Saurabh\n\nSince:\n 25 Nov,2018\n\"\"\"\n\nfrom com.bridgelabz.util.datastructure_util import *\nfrom com.bridgelabz.util.utility import *\n\n\ndef orderedlist_task():\n \"\"\"\n This method is used to read content of file.\n\n this method also append data into orderedList to perform operation on it\n this method also acts as runner for various method\n\n :return:nothing\n \"\"\"\n utility_obj = Utility()\n orderedlist_obj = OrderedList()\n\n file = open(\"../util/LinkedList_File\", \"r+\")\n\n list = file.readlines()\n file_string = list[0]\n\n list = file_string.split()\n\n for i in range(0, len(list)):\n orderedlist_obj.add(list[i].strip())\n file.close()\n\n print(\"These are the data that we have in our File\")\n\n file = open(\"../util/LinkedList_File\", \"r+\")\n\n list = file.readlines()\n list = list[0]\n print(list)\n file.close()\n print(\"Enter data you are looking for\")\n try:\n data = utility_obj.get_string()\n except Exception as e:\n print(e)\n print('Enter data in string only')\n print(orderedlist_obj.search_item(data))\n\n print(\"The updated file content are as follows\")\n orderedlist_obj.file_update(data)\n\n\nif __name__ == '__main__':\n orderedlist_task()\n","sub_path":"orderedlist_task.py","file_name":"orderedlist_task.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"255935571","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n if not l1:\n return l2\n if not l2:\n return l1\n val = l1.val + l2.val\n ansnode = ListNode(val % 10)\n ansnode.next = self.addTwoNumbers(l1.next, l2.next)\n\n if val >= 10:\n ansnode.next = self.addTwoNumbers(ListNode(1), ansnode.next)\n return ansnode\nx=ListNode(1)\ny=ListNode(2)\nss=Solution()\nss.addTwoNumbers(x,y)","sub_path":"tensorflow-pre/leetcode/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"169734609","text":"import sys\r\nimport os\r\nimport argparse\r\nimport subprocess\r\nimport psycopg2\r\nimport datetime\r\nimport config\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"--sms\", help=\"directory with sms data\")\r\nap.add_argument('--voice', help=\"directory with voice data\")\r\nap.add_argument('--network', help=\"directory with network data\")\r\nap.add_argument('--delimiter', help=\"dilimeter character\")\r\nargs = vars(ap.parse_args())\r\nif args['sms'] == None:\r\n args['sms'] = config.default_sms_folder\r\nif args['voice'] == None:\r\n args['voice'] = config.default_voice_folder\r\nif args['network'] == None:\r\n args['network'] = config.default_network_folder\r\nif args['delimiter'] == None:\r\n args['delimiter'] = \"|\"\r\ntoday = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n\r\ntry:\r\n conn = psycopg2.connect(config.cdr_parser_beeline_connect_string)\r\n cursor = conn.cursor()\r\n # update info\r\n sql = \"UPDATE app_info SET started_at = '{0}', sms_smart_sync_first_file = 'None', voice_smart_sync_first_file = 'None', network_smart_sync_first_file = 'None' where id = 1\".format(\r\n today)\r\n # print(sql)\r\n cursor.execute(sql)\r\n conn.commit()\r\n cursor.close()\r\n conn.close()\r\nexcept:\r\n sys.exit('Can\\'t connect to database')\r\n\r\n\r\nfor arg in args:\r\n if arg != 'delimiter':\r\n print('start py -3 model.py --folder {0} --delimiter \"{1}\" --model {2}'.format(\r\n args[arg], args['delimiter'], arg))\r\n\r\n subprocess.call('py -3 model.py --folder {0} --delimiter \"{1}\" --model {2}'.format(\r\n args[arg], args['delimiter'], arg), shell=True)\r\n\r\n # Run SmartCore.py in par\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"79836402","text":"from typing import Tuple, Union\n\nfrom pydantic import BaseSettings, Field\n\n\nclass Settings(BaseSettings):\n IS_DEV_MODE: bool = False\n ALLOW_ORIGINS: Union[str, Tuple[str, ...]] = Field(default_factory=tuple)\n\n LOGGING_LEVEL: str = 'INFO'\n\n @property\n def logging_config(self):\n return {\n 'loggers': {\n 'gunicorn': {\n 'handlers': ['default'],\n 'level': self.LOGGING_LEVEL,\n 'propagate': False\n }\n }\n }\n","sub_path":"components/questionnaire_api/questionnaire/adapters/http_api/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"58002535","text":"import requests\nimport json\n\n\ndef print_request_error(url, reason):\n \"\"\"\n Prints request errors.\n\n Args:\n url (str): URL on which the request was made.\n reason (Any): Debugging reason / message generated by the error.\n\n Returns:\n\n \"\"\"\n print(\"[-] Error getting {}\".format(url))\n print(\"[D] {}\".format(reason))\n\n\ndef get_api_data(url, headers):\n \"\"\"\n Gracefully gets JSON data from API.\n\n Args:\n url (str): An URL to get the data from.\n headers (dict): Request headers needed to issue a proper request.\n\n Returns:\n data (dict):\n \"\"\"\n data = None\n\n try:\n r = requests.get(url, headers=headers)\n if r.status_code == 200:\n data = r.json()\n else:\n print_request_error(url, r.text)\n except Exception as e:\n print_request_error(url, e)\n\n return data\n\n\ndef config_read(config_file_path='config.json'):\n \"\"\"\n Reads proxy's config from config.json file in project root or from a config file on a given path.\n\n Args:\n config_file_path (str): Optional config file path. Defaults to 'config.json' in project root.\n\n Returns:\n config (dict): Proxy configuration.\n \"\"\"\n config = None\n try:\n with open(config_file_path, 'r') as f:\n config = json.load(f)\n except Exception as e:\n print(\"[D] Config Read FAIL!\")\n print(e)\n return config\n\n\ndef config_write(config, config_file_name='config.json'):\n \"\"\"\n Writes proxy's config to config.json file in project root or to a config file on a given path.\n\n Args:\n config (dict): Proxy runtime configuration.\n config_file_path (str): Optional config file path. Defaults to 'config.json' in project root.\n\n Returns:\n None\n \"\"\"\n try:\n with open(config_file_name, 'w') as f:\n json.dump(config, f)\n except Exception as e:\n print(\"[D] Config Write FAIL!\")\n print(e)\n","sub_path":"cal42proxy/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"338871675","text":"# Обращаемся к файлу user1.py для использования данных из этого файла для работы\nfrom user1 import user1\n# Функция получения списка пользователей для работы users, используя модуль user1\ndef update1_user():\n user2 = {}\n user_update = []\n user_update.append(user1)\n print(user1)\n yes_user = int(input(\"Если хотите добавить пользователя нажмите - 1\"))\n if yes_user == 1:\n for key in user1:\n if key == \"number\":\n number = int(input(\"Номер по списку: \"))\n user2[\"number\"] = number\n if key == \"first_name\":\n first_name = str(input(\"Фамилию: \"))\n user2[\"first_name\"] = first_name\n if key == \"middle_name\":\n middle_name = str(input(\"Имя: \"))\n user2[\"middle_name\"] = middle_name\n if key == \"last_name\":\n last_name = str(input(\"Отчество: \"))\n user2[\"last_name\"] = last_name\n if key == \"age\":\n age = int(input(\"Возраст: \"))\n user2[\"age\"] = age\n print(user2)\n user_update.append(user2)\n return user_update\nusers = update1_user()\nprint(users)\n# Функция записи данных в файл\nimport json\ndef user_json_save(users):\n fil = input(\"Введите с клавиатуры имя файла, в который нужно записать данные: \")\n json_dumps_user = json.dumps(users)\n with open(fil, 'w') as f:\n f.write(json_dumps_user)\n print(json_dumps_user)\nuser_json_save(users)\n# Функция загрузки данных списка пользователей из файла\ndef user_json_loads():\n fil = input(\"Введите с клавиатуры имя файла, с которого нужно загрузить данные: \")\n users = []\n with open(fil, \"r\") as f:\n json_loads_user = f.read()\n users = json.loads(json_loads_user)\n print(type(users))\n print(users)\n return users\nuser_json_loads()\n# Функция удаления пользователя по имени из списка пользователей\ndef user_del():\n print(users)\n user_app = \"true\"\n while user_app == \"true\":\n user_del = input(\"Введите имя пользователя, которого нужно удалить\")\n f = 0\n for user in users:\n print(user)\n for value in user.values():\n if value == user_del:\n f = user_del\n users.remove(user)\n if f == 0:\n print(\"Таких данных пользователя нет в этом списке\")\n k = int(input(\"Чтобы остаться в режиме удаления пользователя, нажмите 1\"))\n if k == 1:\n user_app = \"true\"\n else:\n user_app = \"false\"\n return users\nn = user_del()\nprint(n)\nuser_json_save(users)\nuser_json_loads()\n# Функция добавления пользователя к уже существующему списку пользователей users\ndef update2_user():\n print(users)\n user_app = \"true\"\n while user_app == \"true\":\n yes_user = int(input(\"Если хотите добавить пользователя нажмите - 1\"))\n if yes_user == 1:\n number = int(input('Введите номер пользователя'))\n first_name = str(input('Введите фамилию пользователя'))\n middle_name = str(input('Введите имя пользователя'))\n last_name = str(input('Введите отчество пользователя'))\n age = int(input('Введите возраст пользователя'))\n user = {\"number\": number, \"first_name\": first_name, \"middle_name\": middle_name, \"last_name\": last_name, \"age\": age}\n print(user)\n print(users.append(user))\n k = int(input(\"Чтобы остаться в режиме добавления пользователя, нажмите 1\"))\n if k == 1:\n user_app = \"true\"\n else:\n user_app = \"false\"\n return users\nupdate2_user()\nprint(users)\nuser_json_save(users)\nuser_json_loads()\n# Удаление пользователей по номеру из списка пользователей\ndef user_del():\n print(users)\n user_app = \"true\"\n while user_app == \"true\":\n user_del = int(input(\"Введите номер пользователя, которого нужно удалить\"))\n f = 0\n for user in users:\n for value in user.values():\n if value == user_del:\n f = user_del\n users.remove(user)\n if f == 0:\n print(\"Таких данных пользователя нет в этом списке\")\n k = int(input(\"Чтобы остаться в режиме удаления пользователя, нажмите 1\"))\n if k == 1:\n user_app = \"true\"\n else:\n user_app = \"false\"\n return users\nn = user_del()\nprint(n)\n# Функция обновления данных пользователя по номеру\nuser_json_save(users)\nuser_json_loads()\ndef update_number():\n print(users)\n user_app = \"true\"\n while user_app == \"true\":\n user_update = int(input(\"Если хотите обновить данные у пользователя, нажмите 1\"))\n user_number = int(input(\"Введите номер пользователя, у которого нужно обновить данные \"))\n user_means = str(input(\"Введите, что нужно обновить (first_name, middle_name, last_name)\"))\n user_age = input(\"Если нужно обновить возраст, наберите название age\")\n if user_update == 1:\n for user in users:\n if user[\"number\"] == user_number:\n for key in user:\n if key == user_means:\n user_key_means = input(\"Введите новое название для \" + user_means + \" .\")\n user[user_means] = user_key_means\n if key == user_age:\n user_key_age = int(input(\"Введите \" + user_age + \" для обновления\"))\n user[user_age] = user_key_age\n k = int(input(\"Чтобы остаться в режиме обновления данных пользователя, нажмите 1\"))\n if k == 1:\n user_app = \"true\"\n else:\n user_app = \"false\"\n return users\nupdate_number()\nprint(users)\n\n# Функция обновления данных пользователя по имени\nuser_json_save(users)\nuser_json_loads()\ndef update_number():\n print(users)\n user_update = int(input(\"Если хотите обновить данные у пользователя, нажмите 1\"))\n user_name = str(input(\"Введите имя пользователя, у которого нужно обновить данные \"))\n user_means = str(input(\"Введите, что нужно обновить (first_name, middle_name, last_name)\"))\n user_age = input(\"Если нужно обновить возраст, наберите название age\")\n if user_update == 1:\n for user in users:\n if user[\"middle_name\"] == user_name:\n for key in user:\n if key == user_means:\n user_key_means = input(\"Введите новое название для \" + user_means + \".\")\n user[user_means] = user_key_means\n if key == user_age:\n user_key_age = int(input(\"Введите \" + user_age + \" для обновления\"))\n user[user_age] = user_key_age\n else:\n print(\"Обновите в следующий раз\")\n return users\nupdate_number()\nprint(users)\nuser_json_save(users)\n\n\n\n\n","sub_path":"users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":8459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139342445","text":"import os\nimport tarfile\nimport threading\n\nimport cv2\nimport numpy as np\nimport six.moves.urllib as urllib\nimport tensorflow as tf\n\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\n\n\nclass Drone_Net(threading.Thread):\n def __init__(self, vision, process):\n self.storage = []\n self.last_box = None\n self.process = process\n self.boxes = None\n self.coordinates = None\n threading.Thread.__init__(self)\n # Define the video stream\n self.vision = vision\n # What model to download.\n # Models can bee found here:\n # https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md\n MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'\n MODEL_FILE = MODEL_NAME + '.tar.gz'\n DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\n\n # Path to frozen detection graph. This is the actual model that is used for the object detection.\n PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n # List of the strings that is used to add correct label for each box.\n PATH_TO_LABELS = os.path.join('object_detection/data', 'mscoco_label_map.pbtxt')\n\n # Number of classes to detect\n NUM_CLASSES = 90\n\n # Download Model\n opener = urllib.request.URLopener()\n\n already_downloaded = input(\"Enter 'Y' if the network is already downloaded; 'N' if it isn't: \")\n if (already_downloaded == \"N\"):\n opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\n tar_file = tarfile.open(MODEL_FILE)\n for file in tar_file.getmembers():\n file_name = os.path.basename(file.name)\n if 'frozen_inference_graph.pb' in file_name:\n tar_file.extract(file, os.getcwd())\n\n # Load a (frozen) Tensorflow model into memory.\n\n self.detection_graph = tf.Graph()\n with self.detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, '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\n # Loading label map\n # Label maps map indices to category names, so that when our convolution network predicts `5`,\n # we know that this corresponds to `airplane`. Here we use internal utility functions,\n # but anything that returns a dictionary mapping integers to appropriate string labels would be fine\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\n self.category_index = label_map_util.create_category_index(categories)\n # Helper code\n def load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n # runs the neural net detection algorithm as a thread\n def run(self):\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n with self.detection_graph.as_default():\n with tf.Session(graph=self.detection_graph, config=config) as sess:\n while True:\n # Read frame from camera\n image_np = self.vision.get_latest_valid_picture()\n if (image_np is not None):\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Extract image tensor\n image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')\n # Extract detection boxes\n boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')\n # Extract detection scores\n scores = self.detection_graph.get_tensor_by_name('detection_scores:0')\n # Extract detection classes\n classes = self.detection_graph.get_tensor_by_name('detection_classes:0')\n # Extract number of detectionsd\n num_detections = self.detection_graph.get_tensor_by_name(\n 'num_detections:0')\n # Actual detection.\n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n # returns all box coordinates as a double array ([[ymin, xmin, ymax, xmax]]_\n self.boxes = vis_util.get_box_coordinates(image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n self.category_index,\n use_normalized_coordinates=True,\n line_thickness=8,\n only_get=1)\n box = self.compute_boxes(self.boxes)\n\n if (box is not None):\n self.process.compute(box[0], box[1], box[2], box[3])\n else:\n self.process.set_pitch(0)\n self.process.set_rotation(0)\n self.process.set_tilt(0)\n\n\n def compute_boxes(self, coordinates):\n coordinates = np.array(coordinates)\n if (not coordinates.sum() == 0):\n coordinates = self.select_box(coordinates)\n self.storage.append(coordinates)\n if ((len(self.storage) > 30 or coordinates.sum() == 0) and len(self.storage) > 0):\n self.storage.pop(0)\n coordinates = np.array(self.storage, ndmin=2)\n final_coordinates = []\n if (coordinates.sum() == 0):\n return None\n else:\n for i in range(len(coordinates[0])):\n mean = 0\n values = 0\n for j in range(len(coordinates)):\n mean += coordinates[j][i] * (j ** 5 + 1) # (j+1) weighs the input so last frame is worth more\n values += (j ** 5 + 1)\n final_coordinates.append(mean / values)\n final_coordinates = np.array(final_coordinates)\n self.last_box = final_coordinates\n return final_coordinates\n\n def select_box(self, boxes):\n if (self.last_box is None):\n self.last_box = boxes[0] # select box with highest certainty\n else:\n min = 99999999\n min_index = 0\n for i in range(len(boxes)):\n if (abs(((boxes[i] - self.last_box) ** 2).sum()) < min):\n min = abs(((boxes[i] - self.last_box) ** 2).sum())\n min_index = i\n #print(\"Tracking box: \", i, \"difference:\", min)\n self.last_box = boxes[min_index]\n return self.last_box\n\n def get_boxes(self):\n if self.boxes is None:\n return None\n else:\n return np.array(self.boxes)\n\n def get_adjusted_box(self):\n if(len(self.storage)== 0):\n return None\n else:\n return self.last_box\n","sub_path":"Drone_Net.py","file_name":"Drone_Net.py","file_ext":"py","file_size_in_byte":7812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"237291439","text":"\"\"\"watergovernance 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: url('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, url\n 2. Add a URL to urlpatterns: url('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom . import views\n\napp_name='water'\n\n\nurlpatterns = [\n\n \n\n #about us and contact us\n url(r'aboutUs/$',views.aboutUs,name=\"aboutUs\"),\n url(r'^contact/',views.contact,name=\"contactUs\"),\n\n # User Registeration\n\n url(r'^signup/',views.signup,name=\"signup\"),\n url(r'^signin_admin/',views.signinadmin,name=\"signin_admin\"),\n url(r'^signin_user/',views.signin_user,name=\"signin_user\"),\n\n\n # Admin Pages\n\n url(r'^admin/',views.adminland,name=\"adminland\"),\n url(r'^cleanDataset/',views.cleanDataset,name = \"cleanDataset\"),\n url(r'^modelResult/',views.modelResult,name=\"modelResult\"),\n url(r'^alerts/',views.adminAlerts,name=\"alerts\"),\n url(r'^addAdmin/',views.addAdmin,name=\"addAdmin\"),\n url(r'^userInfo/',views.userInfo,name=\"userInfo\"),\n url(r'^getModel/',views.getModel,name=\"getModel\"),\n url(r'^uploadModel/',views.uploadModel,name=\"uploadModel\"),\n url(r'^adminlogout/',views.admin_logout,name=\"adminlogout\"),\n\n\n # User Pages\n # Today's consumption\n url(r'^user/',views.userland,name=\"user\"),\n url(r'^userlogout/',views.user_logout,name=\"userlogout\"),\n url(r'^useralerts/',views.user_alerts,name=\"useralerts\"),\n url(r'^usermonthly/',views.user_month,name=\"usermonthly\"),\n\n]\n","sub_path":"water/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"219244945","text":"#!/usr/bin/python\n\nfrom private import *\nimport models.dorms\nimport session\n\nfrom utils import *\n\nclass Dorm:\n\t# Get information on dorms\n\tdef on_get(self, request, response):\n\t\tresponse.media = {}\n\t\tsession_token = get_session(request)\n\n\t\ttry:\n\t\t\tdorm_id = int(get_val(request.params, \"dorm\"))\n\t\texcept ValueError: # Anything other than an int but not None\n\t\t\tresponse.media = \"Invalid paramaters\"\n\t\t\treturn\n\t\texcept TypeError: # if parameter wasn't provided\n\t\t\tresponse.media = \"No dorm provided\"\n\t\t\treturn\n\n\t\tif dorm_id:\n\t\t\tresults = sql_run_stored_proc_for_single_item(procs.get_single_dorm, dorm_id)\n\t\t\tif results:\n\t\t\t\tresponse.media = models.dorms.Dorm(results)\n\t\telse:\n\t\t\tresults = sql_run_stored_proc_for_multiple_items(procs.get_dorms)\n\n\t\t\tdorm_list = []\n\t\t\tif results:\n\t\t\t\tfor i in results:\n\t\t\t\t\tdorm = models.dorms.Dorm(i)\n\t\t\t\t\tdorm_list.append(dorm)\n\n\t\t\tresponse.media = dorm_list\n","sub_path":"api/endpoints/dorms.py","file_name":"dorms.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"2735371","text":"# Copyright 2018 The Fuchsia Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom recipe_engine import recipe_test_api\n\n\nclass AutoRollerTestApi(recipe_test_api.RecipeTestApi):\n\n def success(self):\n \"\"\"Returns mock data indicating a successful roll.\"\"\"\n return self.m.json.output({\n 'status': 'MERGED',\n 'labels': {'Commit-Queue': {'approved':{}}}\n })\n\n def failure(self):\n \"\"\"Returns mock data indicating a CQ failure.\"\"\"\n return self.m.json.output({\n 'status': 'NEW',\n 'labels': {'Commit-Queue': {}}\n })\n\n def dry_run(self):\n \"\"\"Returns mock data indicating a dry run is complete.\"\"\"\n # Note, this is the same output we expect on failure (CQ just\n # un-sets the CQ label).\n return self.failure()\n\n def timeout(self):\n \"\"\"Returns mock data indicating a roller timeout.\"\"\"\n return self.m.json.output({\n 'status': 'NEW',\n 'labels': {\n 'Commit-Queue': {\n 'approved': {}\n }\n }\n })\n","sub_path":"recipe_modules/auto_roller/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"512136575","text":"\n\nfrom xai.brain.wordbase.nouns._salamander import _SALAMANDER\n\n#calss header\nclass _SALAMANDERS(_SALAMANDER, ):\n\tdef __init__(self,): \n\t\t_SALAMANDER.__init__(self)\n\t\tself.name = \"SALAMANDERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"salamander\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_salamanders.py","file_name":"_salamanders.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"362809609","text":"import base64\nimport io\nimport re\nfrom io import BytesIO\nfrom unittest.mock import ANY, MagicMock, call\n\nimport PyPDF2\nimport pytest\nfrom flask import url_for\nfrom notifications_utils.pdf import pdf_page_count\nfrom pdfrw import PdfReader\nfrom reportlab.lib.colors import black, grey, white\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.lib.units import mm\nfrom reportlab.pdfgen import canvas\n\nfrom app.pdf_redactor import RedactionException\nfrom app.precompiled import (\n A4_HEIGHT,\n A4_WIDTH,\n NotifyCanvas,\n _extract_text_from_first_page_of_pdf,\n add_address_to_precompiled_letter,\n add_notify_tag_to_letter,\n escape_special_characters_for_regex,\n extract_address_block,\n get_invalid_pages_with_message,\n handle_irregular_whitespace_characters,\n is_notify_tag_present,\n redact_precompiled_letter_address_block,\n replace_first_page_of_pdf_with_new_content,\n rewrite_address_block,\n)\nfrom tests.pdf_consts import (\n a3_size,\n a5_size,\n address_block_repeated_on_second_page,\n address_margin,\n already_has_notify_tag,\n bad_postcode,\n blank_page,\n blank_with_2_line_address,\n blank_with_8_line_address,\n blank_with_address,\n example_dwp_pdf,\n invalid_address_character,\n landscape_oriented_page,\n landscape_rotated_page,\n multi_page_pdf,\n no_colour,\n non_uk_address,\n not_pdf,\n notify_tags_on_page_2_and_4,\n portrait_rotated_page,\n repeated_address_block,\n sample_pages,\n single_sample_page,\n valid_letter,\n)\n\n\n@pytest.mark.parametrize('endpoint, kwargs', [\n ('precompiled_blueprint.sanitise_precompiled_letter', {}),\n ('precompiled_blueprint.overlay_template_png_for_page', {'is_first_page': 'true'}),\n ('precompiled_blueprint.overlay_template_pdf', {}),\n])\n@pytest.mark.parametrize('headers', [{}, {'Authorization': 'Token not-the-actual-token'}])\ndef test_endpoints_rejects_if_not_authenticated(client, headers, endpoint, kwargs):\n resp = client.post(\n url_for(endpoint, **kwargs),\n data={},\n headers=headers\n )\n assert resp.status_code == 401\n\n\ndef test_add_notify_tag_to_letter(mocker):\n pdf_original = PyPDF2.PdfFileReader(BytesIO(multi_page_pdf))\n\n assert 'NOTIFY' not in pdf_original.getPage(0).extractText()\n\n pdf_page = add_notify_tag_to_letter(BytesIO(multi_page_pdf))\n\n pdf_new = PyPDF2.PdfFileReader(BytesIO(pdf_page.read()))\n\n assert pdf_new.numPages == pdf_original.numPages\n assert pdf_new.getPage(0).extractText() != pdf_original.getPage(0).extractText()\n assert 'NOTIFY' in pdf_new.getPage(0).extractText()\n assert pdf_new.getPage(1).extractText() == pdf_original.getPage(1).extractText()\n assert pdf_new.getPage(2).extractText() == pdf_original.getPage(2).extractText()\n assert pdf_new.getPage(3).extractText() == pdf_original.getPage(3).extractText()\n\n\ndef test_add_notify_tag_to_letter_correct_margins(mocker):\n pdf_original = PyPDF2.PdfFileReader(BytesIO(multi_page_pdf))\n\n can = NotifyCanvas(white)\n can.drawString = MagicMock(return_value=3)\n\n mocker.patch('app.precompiled.NotifyCanvas', return_value=can)\n\n # It fails because we are mocking but by that time the drawString method has been called so just carry on\n try:\n add_notify_tag_to_letter(BytesIO(multi_page_pdf))\n except Exception:\n pass\n\n mm_from_top_of_the_page = 4.3\n mm_from_left_of_page = 3.44\n\n x = mm_from_left_of_page * mm\n\n # page.mediaBox[3] Media box is an array with the four corners of the page\n # We want height so can use that co-ordinate which is located in [3]\n # The lets take away the margin and the ont size\n y = float(pdf_original.getPage(0).mediaBox[3]) - (float(mm_from_top_of_the_page * mm + 6 - 1.75))\n\n assert len(can.drawString.call_args_list) == 1\n positional_args = can.drawString.call_args[0]\n assert len(positional_args) == 3\n assert positional_args[0] == pytest.approx(x, 0.01)\n assert positional_args[1] == y\n assert positional_args[2] == \"NOTIFY\"\n\n\ndef test_get_invalid_pages_blank_page():\n packet = io.BytesIO()\n cv = canvas.Canvas(packet, pagesize=A4)\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n cv.save()\n packet.seek(0)\n\n assert get_invalid_pages_with_message(packet) == (\"\", [])\n\n\ndef test_get_invalid_pages_black_bottom_corner():\n packet = io.BytesIO()\n cv = canvas.Canvas(packet, pagesize=A4)\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n cv.setStrokeColor(black)\n cv.setFillColor(black)\n cv.rect(0, 0, 10, 10, stroke=1, fill=1)\n cv.save()\n packet.seek(0)\n\n assert get_invalid_pages_with_message(packet) == ('content-outside-printable-area', [1])\n\n\ndef test_get_invalid_pages_grey_bottom_corner():\n packet = io.BytesIO()\n cv = canvas.Canvas(packet, pagesize=A4)\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n cv.setStrokeColor(grey)\n cv.setFillColor(grey)\n cv.rect(0, 0, 10, 10, stroke=1, fill=1)\n cv.save()\n packet.seek(0)\n\n assert get_invalid_pages_with_message(packet) == ('content-outside-printable-area', [1])\n\n\ndef test_get_invalid_pages_blank_multi_page():\n packet = io.BytesIO()\n cv = canvas.Canvas(packet, pagesize=A4)\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n cv.showPage()\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n cv.save()\n packet.seek(0)\n\n assert get_invalid_pages_with_message(packet) == (\"\", [])\n\n\n@pytest.mark.parametrize('x, y, expected_failed', [\n # four corners\n (0, 0, True), (0, 830, True), (590, 0, True), (590, 830, True),\n # middle of page\n (200, 400, False),\n # middle of right margin is not okay\n (590, 400, True),\n # middle of left margin is not okay\n (0, 400, True)\n])\ndef test_get_invalid_pages_second_page(x, y, expected_failed):\n packet = io.BytesIO()\n cv = canvas.Canvas(packet, pagesize=A4)\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n cv.showPage()\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n cv.setStrokeColor(black)\n cv.setFillColor(black)\n\n cv.rect(x, y, 5, 5, stroke=1, fill=1)\n\n cv.save()\n packet.seek(0)\n\n if expected_failed:\n assert get_invalid_pages_with_message(packet) == ('content-outside-printable-area', [2])\n else:\n assert get_invalid_pages_with_message(packet) == ('', [])\n\n\n@pytest.mark.parametrize('x, y, page, expected_message', [\n (0, 0, 1, ('content-outside-printable-area', [1])),\n (200, 200, 1, ('', [])),\n (590, 830, 1, ('content-outside-printable-area', [1])),\n (0, 200, 1, ('content-outside-printable-area', [1])),\n (0, 830, 1, ('content-outside-printable-area', [1])),\n (200, 0, 1, ('content-outside-printable-area', [1])),\n (590, 0, 1, ('content-outside-printable-area', [1])),\n (590, 200, 1, ('content-outside-printable-area', [1])),\n # under the citizen address block:\n (24.6 * mm, (297 - 90) * mm, 1, ('content-outside-printable-area', [1])),\n (24.6 * mm, (297 - 90) * mm, 2, ('', [])), # Same place on page 2 should be ok\n (24.6 * mm, (297 - 39) * mm, 1, ('content-outside-printable-area', [1])), # under the logo\n (24.6 * mm, (297 - 39) * mm, 2, ('', [])), # Same place on page 2 should be ok\n (0, 0, 2, ('content-outside-printable-area', [2])),\n (200, 200, 2, ('', [])),\n (590, 830, 2, ('content-outside-printable-area', [2])),\n (0, 200, 2, ('content-outside-printable-area', [2])),\n (0, 830, 2, ('content-outside-printable-area', [2])),\n (200, 0, 2, ('content-outside-printable-area', [2])),\n (590, 0, 2, ('content-outside-printable-area', [2])),\n (590, 200, 2, ('content-outside-printable-area', [2])),\n])\ndef test_get_invalid_pages_black_text(x, y, page, expected_message):\n packet = io.BytesIO()\n cv = canvas.Canvas(packet, pagesize=A4)\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n\n if page > 1:\n cv.showPage()\n\n cv.setStrokeColor(black)\n cv.setFillColor(black)\n cv.setFont('Arial', 6)\n cv.drawString(x, y, 'This is a test string used to detect non white on a page')\n\n cv.save()\n packet.seek(0)\n assert get_invalid_pages_with_message(packet) == expected_message\n\n\ndef test_get_invalid_pages_address_margin():\n packet = io.BytesIO()\n cv = canvas.Canvas(packet, pagesize=A4)\n cv.setStrokeColor(white)\n cv.setFillColor(white)\n cv.rect(0, 0, 1000, 1000, stroke=1, fill=1)\n\n cv.setStrokeColor(black)\n cv.setFillColor(black)\n\n # This rectangle is the address margin, but 1 mm smaller on each side to account for aliasing\n cv.rect(121 * mm, 203 * mm, 4 * mm, 64 * mm, stroke=1, fill=1)\n\n cv.save()\n packet.seek(0)\n\n assert get_invalid_pages_with_message(packet) == ('content-outside-printable-area', [1])\n\n\n@pytest.mark.parametrize('pdf', [\n a3_size, a5_size, landscape_oriented_page, landscape_rotated_page\n], ids=['a3_size', 'a5_size', 'landscape_oriented_page', 'landscape_rotated_page']\n)\ndef test_get_invalid_pages_not_a4_oriented(pdf):\n message, invalid_pages = get_invalid_pages_with_message(BytesIO(pdf))\n assert message == 'letter-not-a4-portrait-oriented'\n assert invalid_pages == [1]\n\n\ndef test_get_invalid_pages_is_ok_with_landscape_pages_that_are_rotated():\n # the page is orientated landscape but rotated 90º - all the text is sideways but it's still portrait\n message, invalid_pages = get_invalid_pages_with_message(BytesIO(portrait_rotated_page))\n assert message == ''\n assert invalid_pages == []\n\n\ndef test_get_invalid_pages_ignores_notify_tags_on_page_1():\n message, invalid_pages = get_invalid_pages_with_message(BytesIO(already_has_notify_tag))\n assert message == ''\n assert invalid_pages == []\n\n\ndef test_get_invalid_pages_rejects_later_pages_with_notify_tags():\n message, invalid_pages = get_invalid_pages_with_message(BytesIO(notify_tags_on_page_2_and_4))\n assert message == 'notify-tag-found-in-content'\n assert invalid_pages == [2, 4]\n\n\ndef test_overlay_template_png_for_page_not_encoded(client, auth_header):\n\n response = client.post(\n url_for('precompiled_blueprint.overlay_template_png_for_page', is_first_page='true'),\n data=None,\n headers={\n 'Content-type': 'application/json',\n **auth_header\n }\n )\n\n assert response.status_code == 400\n\n\n@pytest.mark.parametrize(['params', 'expected_first_page'], [\n ({'page_number': '1'}, True),\n ({'page_number': '2'}, False),\n ({'is_first_page': 'true'}, True),\n ({'is_first_page': 'anything_else'}, False),\n ({'is_first_page': ''}, False),\n ({'page_number': 1, 'is_first_page': 'true'}, True), # is_first_page takes priority\n])\ndef test_overlay_template_png_for_page_checks_if_first_page(client, auth_header, mocker, params, expected_first_page):\n\n mock_png_from_pdf = mocker.patch('app.precompiled.png_from_pdf', return_value=BytesIO(b'\\x00'))\n mock_colour = mocker.patch('app.precompiled._colour_no_print_areas_of_single_page_pdf_in_red')\n\n response = client.post(\n url_for('precompiled_blueprint.overlay_template_png_for_page', **params),\n data=b'1234',\n headers={\n 'Content-type': 'application/json',\n **auth_header\n }\n )\n\n assert response.status_code == 200\n mock_colour.assert_called_once_with(ANY, is_first_page=expected_first_page)\n mock_png_from_pdf.assert_called_once_with(mock_colour.return_value, page_number=1)\n\n\ndef test_overlay_template_png_for_page_errors_if_not_a_pdf(client, auth_header):\n resp = client.post(\n url_for('precompiled_blueprint.overlay_template_png_for_page', is_first_page='true'),\n data=not_pdf,\n headers=auth_header\n )\n assert resp.status_code == 400\n\n\ndef test_overlay_template_png_for_page_errors_if_multi_page_pdf(client, auth_header):\n resp = client.post(\n url_for('precompiled_blueprint.overlay_template_png_for_page', is_first_page='true'),\n data=multi_page_pdf,\n headers=auth_header\n )\n assert resp.status_code == 400\n\n\ndef test_overlay_template_pdf_errors_if_no_content(client, auth_header):\n resp = client.post(\n url_for('precompiled_blueprint.overlay_template_pdf'),\n headers=auth_header\n )\n assert resp.status_code == 400\n assert resp.json['message'] == 'no data received in POST'\n\n\ndef test_overlay_template_pdf_errors_if_request_args_provided(client, auth_header):\n resp = client.post(\n url_for('precompiled_blueprint.overlay_template_pdf', is_first_page=True),\n data=b'1234',\n headers=auth_header\n )\n assert resp.status_code == 400\n assert 'Did not expect any args' in resp.json['message']\n\n\ndef test_overlay_template_pdf_colours_pages_in_red(client, auth_header, mocker):\n mock_colour = mocker.patch('app.precompiled._colour_no_print_areas_of_page_in_red')\n resp = client.post(\n url_for('precompiled_blueprint.overlay_template_pdf'),\n data=multi_page_pdf,\n headers=auth_header\n )\n assert resp.status_code == 200\n\n assert mock_colour.call_args_list == [call(ANY, is_first_page=True)] + [call(ANY, is_first_page=False)] * 9\n\n\ndef test_precompiled_sanitise_pdf_without_notify_tag(client, auth_header):\n assert not is_notify_tag_present(BytesIO(blank_with_address))\n\n response = client.post(\n url_for('precompiled_blueprint.sanitise_precompiled_letter'),\n data=blank_with_address,\n headers={\n 'Content-type': 'application/json',\n **auth_header\n }\n )\n assert response.status_code == 200\n assert response.json == {\n \"message\": None,\n \"file\": ANY,\n \"page_count\": 1,\n \"recipient_address\": \"Queen Elizabeth\\nBuckingham Palace\\nLondon\\nSW1 1AA\",\n \"invalid_pages\": None,\n 'redaction_failed_message': None\n }\n\n pdf = BytesIO(base64.b64decode(response.json[\"file\"].encode()))\n assert is_notify_tag_present(pdf)\n assert extract_address_block(pdf).normalised == (\n 'Queen Elizabeth\\n'\n 'Buckingham Palace\\n'\n 'London\\n'\n 'SW1 1AA'\n )\n\n\ndef test_precompiled_sanitise_pdf_with_colour_outside_boundaries_returns_400(client, auth_header):\n response = client.post(\n url_for('precompiled_blueprint.sanitise_precompiled_letter'),\n data=no_colour,\n headers={'Content-type': 'application/json', **auth_header}\n )\n\n assert response.status_code == 400\n assert response.json == {\n \"page_count\": 2,\n \"recipient_address\": None,\n \"message\": 'content-outside-printable-area',\n \"invalid_pages\": [1, 2],\n \"file\": None\n }\n\n\ndef test_precompiled_sanitise_pdf_with_colour_in_address_margin_returns_400(client, auth_header, mocker):\n response = client.post(\n url_for('precompiled_blueprint.sanitise_precompiled_letter'),\n data=address_margin,\n headers={'Content-type': 'application/json', **auth_header}\n )\n\n assert response.status_code == 400\n assert response.json == {\n \"page_count\": 1,\n \"recipient_address\": None,\n \"message\": 'content-outside-printable-area',\n \"invalid_pages\": [1],\n \"file\": None\n }\n\n\ndef test_precompiled_sanitise_pdf_that_is_too_long_returns_400(client, auth_header, mocker):\n mocker.patch('app.precompiled.pdf_page_count', return_value=11)\n mocker.patch('app.precompiled.is_letter_too_long', return_value=True)\n response = client.post(\n url_for('precompiled_blueprint.sanitise_precompiled_letter'),\n data=address_margin,\n headers={'Content-type': 'application/json', **auth_header}\n )\n\n assert response.status_code == 400\n assert response.json == {\n \"page_count\": 11,\n \"recipient_address\": None,\n \"message\": \"letter-too-long\",\n \"invalid_pages\": None,\n \"file\": None\n }\n\n\ndef test_precompiled_sanitise_pdf_that_with_an_unknown_error_raised_returns_400(client, auth_header, mocker):\n mocker.patch('app.precompiled.get_invalid_pages_with_message', side_effect=Exception())\n\n response = client.post(\n url_for('precompiled_blueprint.sanitise_precompiled_letter'),\n data=address_margin,\n headers={'Content-type': 'application/json', **auth_header}\n )\n\n assert response.status_code == 400\n assert response.json == {\n \"page_count\": None,\n \"recipient_address\": None,\n \"message\": 'unable-to-read-the-file',\n \"invalid_pages\": None,\n \"file\": None\n }\n\n\ndef test_sanitise_precompiled_letter_with_missing_address_returns_400(client, auth_header):\n\n response = client.post(\n url_for('precompiled_blueprint.sanitise_precompiled_letter'),\n data=blank_page,\n headers={\n 'Content-type': 'application/json',\n **auth_header\n }\n )\n\n assert response.status_code == 400\n assert response.json == {\n \"page_count\": 1,\n \"recipient_address\": None,\n \"message\": 'address-is-empty',\n \"invalid_pages\": [1],\n \"file\": None\n }\n\n\n@pytest.mark.parametrize('file, allow_international, expected_error_message', (\n (bad_postcode, '', 'not-a-real-uk-postcode'),\n (bad_postcode, 'true', 'not-a-real-uk-postcode-or-country'),\n (non_uk_address, '', 'cant-send-international-letters'),\n (blank_with_2_line_address, '', 'not-enough-address-lines'),\n (blank_with_8_line_address, '', 'too-many-address-lines'),\n (invalid_address_character, '', 'invalid-char-in-address'),\n))\ndef test_sanitise_precompiled_letter_with_bad_address_returns_400(\n client,\n auth_header,\n file,\n allow_international,\n expected_error_message,\n):\n\n response = client.post(\n url_for(\n 'precompiled_blueprint.sanitise_precompiled_letter',\n allow_international_letters=allow_international,\n ),\n data=file,\n headers={\n 'Content-type': 'application/json',\n **auth_header\n }\n )\n\n assert response.status_code == 400\n assert response.json == {\n \"page_count\": 1,\n \"recipient_address\": None,\n \"message\": expected_error_message,\n \"invalid_pages\": [1],\n \"file\": None\n }\n\n\ndef test_is_notify_tag_present_finds_notify_tag():\n assert is_notify_tag_present(BytesIO(example_dwp_pdf)) is True\n\n\ndef test_is_notify_tag_present():\n assert is_notify_tag_present(BytesIO(blank_page)) is False\n\n\ndef test_is_notify_tag_calls_extract_with_wider_numbers(mocker):\n mock_extract = mocker.patch('app.precompiled._extract_text_from_first_page_of_pdf')\n pdf = MagicMock()\n\n is_notify_tag_present(pdf)\n\n mock_extract.assert_called_once_with(\n ANY,\n x1=pytest.approx(6.8031496),\n y1=pytest.approx(3.685039),\n x2=pytest.approx(58.149606),\n y2=pytest.approx(26.692913),\n )\n\n\n@pytest.mark.parametrize(['pdf_data', 'address_snippet'], [\n (example_dwp_pdf, 'testington'),\n (valid_letter, 'buckingham palace')\n], ids=['example_dwp_pdf', 'valid_letter'])\ndef test_rewrite_address_block_end_to_end(pdf_data, address_snippet):\n new_pdf, address, message = rewrite_address_block(\n BytesIO(pdf_data),\n page_count=1,\n allow_international_letters=False,\n )\n assert not message\n assert address == extract_address_block(new_pdf).raw_address\n assert address_snippet in address.lower()\n\n\ndef test_rewrite_address_block_doesnt_overwrite_if_it_cant_redact_address():\n old_pdf = BytesIO(repeated_address_block)\n old_address = extract_address_block(old_pdf).raw_address\n\n new_pdf, address, message = rewrite_address_block(\n old_pdf,\n page_count=1,\n allow_international_letters=False,\n )\n\n # assert that the pdf is unchanged. Specifically we haven't written the new address over the old one\n assert new_pdf.getvalue() == old_pdf.getvalue()\n assert message == 'More than one match for address block during redaction procedure'\n # template preview still needs to return the address even though it's unchanged.\n assert old_address == address\n\n\ndef test_extract_address_block():\n assert extract_address_block(BytesIO(example_dwp_pdf)).raw_address == '\\n'.join([\n 'MR J DOE',\n '13 TEST LANE',\n 'TESTINGTON',\n 'TE57 1NG',\n ])\n\n\ndef test_add_address_to_precompiled_letter_puts_address_on_page():\n address = '\\n'.join([\n 'Queen Elizabeth,',\n 'Buckingham Palace',\n 'London',\n 'SW1 1AA',\n ])\n ret = add_address_to_precompiled_letter(BytesIO(blank_page), address)\n assert extract_address_block(ret).raw_address == address\n\n\ndef test_redact_precompiled_letter_address_block_redacts_address_block():\n address = extract_address_block(BytesIO(example_dwp_pdf))\n address_regex = address.raw_address.replace(\"\\n\", \"\")\n assert address_regex == 'MR J DOE13 TEST LANETESTINGTONTE57 1NG'\n new_pdf = redact_precompiled_letter_address_block(BytesIO(example_dwp_pdf), address_regex)\n assert extract_address_block(new_pdf).raw_address == \"\"\n\n\ndef test_redact_precompiled_letter_address_block_is_called_with_first_page(mocker):\n \"\"\"\n To test that `redact_precompiled_letter_address_block` is being called with the first page\n of a PDF we can:\n 1. Mock the function that gets the first page of a letter to return a particular 1 page PDF\n with an address of 'Queen Elizabeth Buckingham Palace London SW1 1AA'\n 2. We have a 2nd multiple page PDF with a different address\n 3. Call `redact_precompiled_letter_address_block` with the second PDF, but with the address\n regex of the 1 page PDF\n 4. `redact_precompiled_letter_address_block` works with no errors, showing it was passed the\n first PDF as its input\n \"\"\"\n replace_first_page_mock = mocker.patch('app.precompiled.replace_first_page_of_pdf_with_new_content')\n mocker.patch('app.precompiled.get_first_page_of_pdf', return_value=BytesIO(valid_letter))\n\n address_regex_of_new_first_page = 'Queen ElizabethBuckingham PalaceLondonSW1 1AA'\n\n redact_precompiled_letter_address_block(\n BytesIO(example_dwp_pdf),\n address_regex_of_new_first_page\n )\n assert replace_first_page_mock.called\n\n\ndef test_redact_precompiled_letter_address_block_tries_to_redact_address_from_first_page(mocker):\n \"\"\"\n To test that `redact_precompiled_letter_address_block` is being called with the first page\n of a PDF we can:\n 1. Mock the function that gets the first page of a letter to return a particular 1 page PDF\n 2. We have a 2nd multiple page PDF with a different address (MR J DOE 13 TEST LANE TESTINGTON TE57 1NG)\n 3. Call `redact_precompiled_letter_address_block` with the second PDF, and with the address\n regex of the second PDF\n 4. `redact_precompiled_letter_address_block` raises an error because it can't find the address\n 5. This shows it didn't get passed the first page of the multi-page PDF\n \"\"\"\n\n mocker.patch('app.precompiled.replace_first_page_of_pdf_with_new_content')\n mocker.patch('app.precompiled.get_first_page_of_pdf', return_value=BytesIO(valid_letter))\n\n original_letter_address_regex = 'MR J DOE13 TEST LANETESTINGTONTE57 1NG'\n with pytest.raises(RedactionException) as e:\n redact_precompiled_letter_address_block(BytesIO(example_dwp_pdf), original_letter_address_regex)\n assert str(e.value) == 'No matches for address block during redaction procedure'\n\n\ndef test_redact_precompiled_letter_address_block_address_repeated_on_2nd_page():\n address = extract_address_block(BytesIO(address_block_repeated_on_second_page))\n address_regex = address.raw_address.replace(\"\\n\", \"\")\n expected = 'PEA NUTTPEANUT BUTTER JELLY COURTTOAST WHARFALL DAY TREAT STREETTASTY TOWNSNACKSHIRETT7 PBJ'\n assert address_regex == expected\n\n new_pdf = redact_precompiled_letter_address_block(\n BytesIO(address_block_repeated_on_second_page), address_regex\n )\n assert extract_address_block(new_pdf).raw_address == \"\"\n\n document = PdfReader(new_pdf)\n assert len(document.pages) == 2\n\n\ndef test_redact_precompiled_letter_address_block_sends_log_message_if_no_matches():\n address_regex = 'MR J DOE13 UNMATCHED LANETESTINGTONTE57 1NG'\n with pytest.raises(RedactionException) as exc_info:\n redact_precompiled_letter_address_block(BytesIO(example_dwp_pdf), address_regex)\n assert \"No matches for address block during redaction procedure\" in str(exc_info.value)\n\n\ndef test_redact_precompiled_letter_address_block_sends_log_message_if_multiple_matches():\n address_regex = 'Queen ElizabethBuckingham PalaceLondonSW1 1AA'\n with pytest.raises(RedactionException) as exc_info:\n redact_precompiled_letter_address_block(BytesIO(repeated_address_block), address_regex)\n assert \"More than one match for address block during redaction procedure\" in str(exc_info.value)\n\n\n@pytest.mark.parametrize('string', [\n 'Queen Elizabeth 1 Buckingham Palace London SW1 1AA', # no special characters\n 'Queen Elizabeth (1) Buckingham Palace [London {SW1 1AA', # brackets\n 'Queen Eliz^beth * Buck|ngham Palace? London+ $W1 1AA.', # other special characters\n 'Queen Elizabeth 1 \\\\Buckingham Palace London SW1 1AA', # noqa backslash\n 'Queen Elizabeth 1 \\\\Buckingham \\\\Balace London SW1 1AA', # backslash before same letter twice\n 'Queen Elizabeth 1 Buckingham Palace London \\\\SW1 1AA', # backslash before big S (checking case sensitivity)\n])\ndef test_escape_special_characters_for_regex_matches_string(string):\n escaped_string = escape_special_characters_for_regex(string)\n regex = re.compile(escaped_string)\n assert regex.findall(string)\n\n\n@pytest.mark.parametrize('string', [\n 'Queen Elizabeth\\n1 Buckingham Palace London SW1 1AA', # newline character\n 'Queen Elizabeth 1 Buckingham Palace London\\tSW1 1AA', # noqa tab character\n])\ndef test_escape_special_characters_does_not_escape_backslash_in_whitespace_chars(string):\n assert string == escape_special_characters_for_regex(string)\n\n\n@pytest.mark.parametrize(\"irregular_address\", [\n 'MR J DOE 13 TEST LANETESTINGTONTE57 1NG',\n 'MR J DOE13 TEST LANETESTINGTONTE57 1NG',\n 'MR J DOE13 TEST LANETESTINGTON TE57 1NG',\n 'MR J DOE13 TEST LANETESTINGTONTE57 1NG',\n])\ndef test_handle_irregular_whitespace_characters(irregular_address):\n extracted_address = 'MR J DOE\\n13 TEST LANE\\nTESTINGTON\\nTE57 1NG'\n regex_ready = handle_irregular_whitespace_characters(extracted_address)\n regex = re.compile(regex_ready)\n assert regex.findall(irregular_address)\n\n\ndef test_replace_first_page_of_pdf_with_new_content():\n x2 = A4_WIDTH * mm\n y2 = A4_HEIGHT * mm\n\n assert _extract_text_from_first_page_of_pdf(BytesIO(single_sample_page), x1=0, y1=0, x2=x2, y2=y2) == 'Z'\n assert _extract_text_from_first_page_of_pdf(BytesIO(sample_pages), x1=0, y1=0, x2=x2, y2=y2) == 'A'\n\n modified_pdf = replace_first_page_of_pdf_with_new_content(BytesIO(sample_pages), BytesIO(single_sample_page))\n\n assert _extract_text_from_first_page_of_pdf(modified_pdf, x1=0, y1=0, x2=x2, y2=y2) == 'Z'\n assert pdf_page_count(modified_pdf) == 3\n","sub_path":"tests/test_precompiled.py","file_name":"test_precompiled.py","file_ext":"py","file_size_in_byte":27485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61948497","text":"from django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_delete\nfrom django.core.validators import MinValueValidator, MaxValueValidator\nfrom django.core.exceptions import ValidationError\nimport sys\n\n\"\"\"Checks the size of the image file, and raises an error\nif the file exceeds 150kb\n\"\"\"\ndef checkImageSize(image):\n\tsize = sys.getsizeof(image.file)\n\tlimit = 150\n\tif size > limit * 1024:\n\t\traise ValidationError(\"Exceeds max size of %sKB\" % limit)\n\n\"\"\"The model containing the fields that will be included in\nthe database\n\"\"\"\nclass Student(models.Model):\n\tuid = models.PositiveIntegerField(\n\t\tnull = False,\n\t\tvalidators = [MinValueValidator(0), MaxValueValidator(999)],\n\t\tunique = True\n\t)\n\tname = models.CharField(\n\t\tmax_length = 255,\n\t\tnull = False\n\t)\n\tage = models.PositiveIntegerField(\n\t\tnull = True,\n\t\tvalidators = [MinValueValidator(0), MaxValueValidator(100)]\n\t)\n\timage = models.ImageField(\n\t\tupload_to=\"images/\",\n\t\tnull = True,\n\t\tmax_length = 100,\n\t\tvalidators = [checkImageSize]\n\t)\n\tdate_created = models.DateTimeField(\n\t\tauto_now_add = True\n\t)\n\tdate_modified = models.DateTimeField(\n\t\tauto_now = True\n\t)\n\n\"\"\"Listens for a DELETE request. Deletes the image from local storage.\n\"\"\"\n@receiver(post_delete, sender=Student)\ndef submission_delete(sender, instance, **kwargs):\n\tinstance.image.delete(False)\n","sub_path":"src/users_api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288018849","text":"from os.path import dirname\r\nfrom underthesea.corpus import PlainTextCorpus, join, mkdir\r\nimport re\r\nfrom pipelines.data_preparation.corpus import TaggedCorpus, TaggedWord, TaggedSentence, TaggedDocument\r\nimport random\r\n\r\nraw_folder = join(dirname(dirname(dirname(__file__))), \"data\", \"raw\", \"version 2\")\r\nud_file = join(dirname(dirname(dirname(__file__))), \"data\", \"ud\", \"vi_ud_no_comment.conllu\")\r\ndev_file = join(dirname(dirname(dirname(__file__))), \"data\", \"ud\", \"dev.conllu\")\r\ntest_file = join(dirname(dirname(dirname(__file__))), \"data\", \"ud\", \"test.conllu\")\r\n# sample_ud_file = join(\"sample\", \"sample_vi_ud.conllu\")\r\n# ud_file = sample_ud_file\r\n\r\n\r\ndef extract_tokens(text):\r\n matched = re.match(\"(.*)/(.*)\", text, re.UNICODE)\r\n return [matched.group(1), matched.group(2)]\r\n\r\n\r\nif __name__ == '__main__':\r\n corpus = PlainTextCorpus()\r\n corpus.load(raw_folder)\r\n tagged_corpus = TaggedCorpus()\r\n tagged_documents = []\r\n documents = corpus.documents\r\n # documents = random.sample(documents, 10)\r\n for document in documents:\r\n sentences = []\r\n for sentence in document.sentences:\r\n tagged_tokens = sentence.split()\r\n tagged_words = [extract_tokens(token) for token in tagged_tokens]\r\n tagged_words = [TaggedWord(tagged_word[0].replace(\"_\", \" \"), tagged_word[1]) for tagged_word in\r\n tagged_words]\r\n sentence = TaggedSentence(tagged_words)\r\n if len(sentence.words) > 0:\r\n sentences.append(sentence)\r\n tagged_document = TaggedDocument(sentences)\r\n tagged_document.id = document.id\r\n tagged_documents.append(tagged_document)\r\n tagged_corpus.documents = tagged_documents\r\n n = int(0.8 * len(tagged_documents))\r\n tagged_corpus.documents = tagged_documents[:n]\r\n tagged_corpus.save(dev_file, comment=False)\r\n tagged_corpus.documents = tagged_documents[n:]\r\n tagged_corpus.save(test_file, comment=False)\r\n","sub_path":"pipelines/data_preparation/convert_to_ud.py","file_name":"convert_to_ud.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"33581550","text":"# Benutzer gibt eine Anzahl der gewünschten Interationen an\r\nInteration = int (input(\"Geben Sie die gewünschte Anzahl der Interationen ein (1-\\u221E): \"))\r\n\r\n#Abfrage ob die Zwischenergebnisse angezeigt werden sollen\r\nZwischenergebnisse = str (input(\"Wollen Sie die Zwischenergebnisse angezeigt bekommen?(yes/no):\"))\r\n\r\nif Zwischenergebnisse == \"yes\":\r\n print(\"Zwischenergebnisse\")\r\nelif Zwischenergebnisse == \"no\":\r\n print(\"\")\r\nelse:\r\n print(\"Falsche Eingabe. Aber Sie bekommem trotzdem ein Ergebnis für die Annäherung an Pi :)\")\r\n \r\n# Leibnitz-Reihe mit while Schleife\r\nErgebnis = 4\r\nk = 1\r\nwhile k < Interation:\r\n Ergebnis += (((-1)**k)/(2*k+1))*4\r\n if Zwischenergebnisse == \"yes\":\r\n print(round(Ergebnis,4),\"k=\",k)\r\n k += 1\r\n\r\n# Ausgabe des Wertes mit Anzahl der Interationen grammatikalisch angepasst\r\nif Interation == 1:\r\n print(\"Der Näherungswert für Pi mit einer Interation beträgt:\",round(Ergebnis,10))\r\nelse:\r\n print(\"Der Näherungswert für Pi mit\",Interation,\"Interationen beträgt:\",round(Ergebnis,10)) \r\n\r\n\r\n\r\n\r\n\r\nprint(\"--------------------------------------------------------\") # Absatz\r\n#Differenz zum Originalwert\r\nimport math\r\nx= math.pi\r\n\r\nif x>=Ergebnis:\r\n Differenz = ((x-Ergebnis)/Ergebnis)*100\r\nelse:\r\n Differenz = ((Ergebnis-x)/x)*100\r\n\r\nprint(\"Die Differenz zum Originalwert beträgt:\",round(Differenz,4),\"%\")\r\nif Differenz < 0.1:\r\n print(\"Also schon echt nah dran!\")\r\nelif Differenz > 2:\r\n print(\"Das ist schon noch ein ganzes Stück weit weg!\")\r\n\r\n","sub_path":"Langbauer_Beispiel 3_Leibnitz-Reihe.py","file_name":"Langbauer_Beispiel 3_Leibnitz-Reihe.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"122938191","text":"import numpy as np\nimport math\nimport time\nimport draw_manager\ndef calc_heuristics_kvazi_manthattan(aPoint, bPoint, lab):\n dist = 0\n prevPoint = aPoint.copy()\n while(abs(aPoint[0] - bPoint[0]) != 0):\n if(aPoint[0] > bPoint[0]):\n aPoint[0] -= 1\n else:\n aPoint[0] += 1\n\n if (lab[tuple(aPoint)] == -1 and lab[tuple(prevPoint)] != -1):\n dist += 2\n else:\n dist += 1\n prevPoint = aPoint.copy()\n\n\n while(abs(aPoint[1] - bPoint[1] != 0)):\n if (aPoint[1] > bPoint[1]):\n aPoint[1] -= 1\n else:\n aPoint[1] += 1\n\n if (lab[tuple(aPoint)] == -1 and lab[tuple(prevPoint)] != -1):\n dist += 2\n else:\n dist += 1\n prevPoint = aPoint.copy()\n\n return dist\n\ndef get_neighbors(current):\n neighbors = list()\n current = list(current)\n original = current.copy()\n\n #levo\n current[1] -= 1\n if current[1] >= 0:\n if narray[tuple(current)] >= 0 or narray[tuple(current)] == -3:\n neighbors.append(tuple(current))\n current = original.copy()\n\n #desno\n current[1] += 1\n if current[1] < np.size(narray, 1):\n if narray[tuple(current)] >= 0 or narray[tuple(current)] == -3:\n neighbors.append(tuple(current))\n current = original.copy()\n\n #gor\n current[0] -= 1\n if current[0] >= 0:\n if narray[tuple(current)] >= 0 or narray[tuple(current)] == -3:\n neighbors.append(tuple(current))\n current = original.copy()\n\n #dol\n current[0] += 1\n if current[0] < np.size(narray, 0):\n if narray[tuple(current)] >= 0 or narray[tuple(current)] == -3:\n neighbors.append(tuple(current))\n current = original.copy()\n\n return neighbors\n\ndef search(path, g, bound, end ):\n node = path[-1]\n f = g + calc_heuristics_kvazi_manthattan(list(node), end, narray)\n if f > bound:\n return f\n if node == end:\n return \"FOUND\"\n mini = math.inf\n neighbors = get_neighbors(node)\n for neighbor in neighbors:\n if neighbor not in path:\n path.append(neighbor)\n t = search(path, g + narray[tuple(neighbor)], bound, end)\n if t == \"FOUND\":\n return \"FOUND\"\n if t < mini:\n mini = t\n path.pop()\n return mini\n\n\n\ndef ida_star(end):\n bound = calc_heuristics_kvazi_manthattan(start.copy(), end, narray)\n path = list()\n path.append(tuple(start))\n while True:\n t = search(path, 0, bound, end)\n if t == \"FOUND\":\n return (path, bound)\n if t == math.inf:\n return \"NOT FOUND\"\n bound = t\n\n\nnarray = np.loadtxt(\"labyrinth_7.txt\", int, delimiter=\",\")\nstart = np.argwhere(narray == -2)\nstart = list(map(list, start))[0]\nends = np.argwhere(narray == -3)\nends = list(map(list,ends))\n\n\nminEnd = None\nminPrice = 0\nminTime = 0\nfor e in ends:\n timeStart = time.clock()\n tmp = ida_star(tuple(e))\n timeStart = time.clock() - timeStart\n price = tmp[1]\n\n if(not(minEnd)):\n minEnd = tmp[0]\n minPrice = tmp[1]\n minTime = timeStart\n else:\n if price < minPrice:\n minPrice = price\n minEnd = tmp[0]\n minTime = timeStart\n print(\"Time spent on finding path: {}s Price of path: {}\".format(timeStart, tmp[1]))\n\nprint(\"\\nFastest route has price {} with time {}s\".format(minPrice, minTime))\n\n\ndm = draw_manager.DrawManager(narray)\n\ndm.draw_lab()\n\ndm.draw_end_path(minEnd)\n\ndm.call_sys_exit()","sub_path":"seminarska_2/IDAstar.py","file_name":"IDAstar.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10518277","text":"\nimport inspect\n\nfrom maya import cmds\n\nimport apiExtensions\nimport serialization\nimport maya_decorators\n\n# load the tb_nodes plugin - we use a tb_storage node for storing export containers\ncmds.loadPlugin('zooStorageNode.py', quiet=True)\n\nNODE_TYPE = 'zooStorageNode'\n\ndef classFullname(cls):\n module = inspect.getmodule(cls)\n return '%s.%s' % (module.__name__, cls.__name__)\n\nclass Storage(object):\n\n @classmethod\n def IsA(cls, node):\n if cmds.nodeType(node) == NODE_TYPE:\n return True\n\n return False\n\n @classmethod\n def Iter(cls, skipReferenced=True):\n for node in cmds.ls(type=NODE_TYPE) or []:\n\n # this test exists so that subclasses can implement their own IsA methods\n try:\n if not cls.IsA(node):\n continue\n\n # if a node gets deleted while we're iterating then the node may not actually\n # exist. So catch runtime errors and assume they're because the node is gone\n except RuntimeError: continue\n\n if skipReferenced and cmds.referenceQuery(node, inr=True):\n continue\n\n yield cls(node)\n\n @classmethod\n @maya_decorators.d_maintainSceneSelection\n def Create(cls):\n node = apiExtensions.asMObject(cmds.createNode(NODE_TYPE))\n node.rename('tb_data')\n\n cmds.addAttr(node, ln='zooStorageClients', dt='string', multi=True)\n\n return cls(node)\n\n @classmethod\n def Get(cls):\n '''\n returns the first storage node found in this scene, otherwise None\n '''\n for storage in cls.Iter(True):\n return storage\n\n @classmethod\n def GetOrCreate(cls):\n return cls.Get() or cls.Create()\n\n @classmethod\n def Exists(cls):\n for storage in cls.Iter(True):\n return True\n\n return False\n\n def __init__(self, node):\n self._node = node\n\n def __repr__(self):\n return '%s(%r)' % (type(self).__name__, self._node)\n __str__ = __repr__\n\n def __eq__(self, other):\n return self._node == other._node\n\n @property\n def node(self):\n return self._node\n\n def registerClient(self, storageClientCls):\n\n # before we do anything, make sure the client cls implements the IsA class method\n if 'isUsed' not in storageClientCls.__dict__:\n raise TypeError(\"The client class must implement the isUsed method\")\n\n indices = cmds.getAttr('%s.zooStorageClients' % self._node, multiIndices=True) or []\n index = 0\n if indices:\n index = indices[-1] + 1\n\n attrname = 'zooStorageClients[%d]' % index\n clientDict = serialization.TypedSerializableDict(self._node, attrname)\n clientDict['clientClsPath'] = classFullname(storageClientCls)\n\n def getClientCls(self, index):\n attrname = 'zooStorageClients[%d]' % index\n clientDict = serialization.TypedSerializableDict(self._node, attrname)\n clientClsPath = clientDict['clientClsPath']\n toks = clientClsPath.split('.')\n clientClsName = toks.pop()\n clientClsModule = __import__('.'.join(toks))\n clientCls = getattr(clientClsModule, clientClsName)\n\n return clientCls\n\n def iterRegisteredClients(self):\n indices = cmds.getAttr('%s.zooStorageClients' % self._node, multiIndices=True) or []\n for idx in indices:\n yield self.getClientCls(idx)\n\n def isRegistered(self, storageClientCls):\n for clientCls in self.iterRegisteredClients():\n if clientCls is storageClientCls:\n return True\n\n def deregisterClient(self, storageClientCls):\n clsName = storageClientCls.__name__\n\n def isUsed(self):\n for clientCls in self.iterRegisteredClients():\n if clientCls(self._node).isUsed():\n return True\n\n return False\n\nclass StorageClient(object):\n '''\n basic super class for storage clients to inherit from\n '''\n\n @classmethod\n def Iter(cls, skipReferenced=True):\n for storage in Storage.Iter(skipReferenced):\n if storage.isRegistered(cls):\n yield cls(storage)\n\n @classmethod\n def Create(cls):\n storage = Storage.GetOrCreate()\n storage.registerClient(cls)\n\n return cls(storage)\n\n @classmethod\n def GetOrCreate(cls):\n for client in cls.Iter():\n return client\n\n return cls.Create()\n\n#end\n","sub_path":"CONFIG_v2.5/mayaConfig/modules_local/UTSMOD/2016/mac/quarantined_scripts/zoo/zmaya/scene_storage.py","file_name":"scene_storage.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"367405926","text":"from django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import last_modified\n\nfrom api.response import JsonError, JsonResponse, require_methods_api\nfrom groups.models import Group, Member\nfrom MangAdventure.utils.search import get_response\nfrom reader.models import Artist, Author, Category, Chapter, Series\n\n\ndef _chapter_response(request, _chapter):\n url = request.build_absolute_uri(_chapter.get_absolute_url())\n response = {\n 'title': _chapter.title,\n 'url': url,\n 'pages_root': url.replace(\n '/reader', '%s%s' % (settings.MEDIA_URL, 'series')\n ),\n 'pages_list': [p.get_file_name() for p in _chapter.pages.all()],\n 'date': _chapter.get_uploaded_date,\n 'final': _chapter.final,\n 'groups': []\n }\n for _group in _chapter.groups.all():\n response['groups'].append({\n 'id': _group.id,\n 'name': _group.name,\n })\n return response\n\n\ndef _volume_response(request, _series, vol):\n response = {}\n chapters = _series.chapters.filter(volume=vol)\n if chapters.count() == 0:\n return JsonError('Not found', 404)\n for _chapter in chapters:\n response['%g' % _chapter.number] = \\\n _chapter_response(request, _chapter)\n return response\n\n\ndef _series_response(request, _series):\n response = {\n 'slug': _series.slug,\n 'title': _series.title,\n 'aliases': [a.alias for a in _series.aliases.all()],\n 'url': request.build_absolute_uri(_series.get_absolute_url()),\n 'description': _series.description,\n 'authors': [],\n 'artists': [],\n 'categories': [],\n 'cover': request.build_absolute_uri(_series.cover.url),\n 'completed': _series.completed,\n 'volumes': {},\n }\n for _chapter in _series.chapters.all():\n if _chapter.volume not in response['volumes']:\n response['volumes'][_chapter.volume] = \\\n _volume_response(request, _series, _chapter.volume)\n for _author in _series.authors.all():\n names = [a.alias for a in _author.aliases.all()]\n names.insert(0, _author.name)\n response['authors'].append(names)\n for _artist in _series.artists.all():\n names = [a.alias for a in _artist.aliases.all()]\n names.insert(0, _artist.name)\n response['artists'].append(names)\n for _category in _series.categories.all():\n response['categories'].append({\n 'name': _category.name,\n 'description': _category.description\n })\n return response\n\n\ndef _person_response(request, _person):\n response = {\n 'id': _person.id,\n 'name': _person.name,\n 'aliases': [a.alias for a in _person.aliases.all()],\n 'series': [],\n }\n for _series in _person.series_set.all():\n response['series'].append({\n 'slug': _series.slug,\n 'title': _series.title,\n 'aliases': [a.alias for a in _series.aliases.all()],\n })\n return response\n\n\ndef _member_response(request, _member):\n return {\n 'id': _member.id,\n 'name': _member.name,\n 'roles': [r.get_role_display() for r in _member.roles.all()],\n 'twitter': _member.twitter,\n 'discord': _member.discord,\n }\n\n\ndef _group_response(request, _group):\n logo = ''\n if _group.logo:\n logo = request.build_absolute_uri(_group.logo.url)\n response = {\n 'id': _group.id,\n 'name': _group.name,\n 'description': _group.description,\n 'website': _group.website,\n 'discord': _group.discord,\n 'twitter': _group.twitter,\n 'logo': logo,\n 'members': [],\n 'series': [],\n }\n member_ids = _group.roles.values_list(\n 'member_id', flat=True\n ).distinct()\n for m_id in member_ids:\n response['members'].append(_member_response(\n request, Member.objects.get(id=m_id)\n ))\n _series = []\n for _chapter in _group.releases.all():\n if _chapter.series.id not in _series:\n response['series'].append({\n 'slug': _chapter.series.slug,\n 'title': _chapter.series.title,\n 'aliases': [a.alias for a in _chapter.series.aliases.all()]\n })\n _series.append(_chapter.series.id)\n return response\n\n\n@csrf_exempt\n@require_methods_api()\n@last_modified(lambda request: Series.objects.latest().modified)\ndef all_releases(request):\n _series = Series.objects.prefetch_related('chapters').all()\n response = []\n for s in _series:\n series_res = {\n 'slug': s.slug,\n 'title': s.title,\n 'url': request.build_absolute_uri(s.get_absolute_url()),\n 'cover': request.build_absolute_uri(s.cover.url),\n 'latest_chapter': {},\n }\n try:\n last_chapter = s.chapters.latest()\n series_res['latest_chapter'] = {\n 'title': last_chapter.title,\n 'volume': last_chapter.volume,\n 'number': last_chapter.number,\n 'date': last_chapter.get_uploaded_date,\n }\n except ObjectDoesNotExist:\n pass\n response.append(series_res)\n return JsonResponse(response, safe=False)\n\n\ndef _latest(request, slug=None, vol=None, num=None):\n try:\n if slug is None:\n return Series.objects.only('modified').latest().modified\n if vol is None:\n return Series.objects.only('modified').get(slug=slug).modified\n if num is None:\n return Chapter.objects.only('modified').filter(\n series__slug=slug, volume=vol\n ).latest().modified\n return Chapter.objects.only('modified').filter(\n series__slug=slug, volume=vol, number=num\n ).latest().modified\n except ObjectDoesNotExist:\n return None\n\n\n@csrf_exempt\n@require_methods_api()\n@last_modified(_latest)\ndef all_series(request):\n response = [\n _series_response(request, s)\n for s in get_response(request)\n ]\n return JsonResponse(response, safe=False)\n\n\n@csrf_exempt\n@require_methods_api()\n@last_modified(_latest)\ndef series(request, slug):\n try:\n _series = Series.objects.get(slug=slug)\n except ObjectDoesNotExist:\n return JsonError('Not found', 404)\n return JsonResponse(_series_response(request, _series))\n\n\n@csrf_exempt\n@require_methods_api()\n@last_modified(_latest)\ndef volume(request, slug, vol):\n try:\n vol = int(vol)\n if vol < 0:\n raise ValueError\n _series = Series.objects \\\n .prefetch_related('chapters__pages').get(slug=slug)\n except (ValueError, TypeError):\n return JsonError('Bad request', 400)\n except ObjectDoesNotExist:\n return JsonError('Not found', 404)\n return JsonResponse(_volume_response(request, _series, vol))\n\n\n@csrf_exempt\n@require_methods_api()\n@last_modified(_latest)\ndef chapter(request, slug, vol, num):\n try:\n vol, num = int(vol), float(num)\n if vol < 0 or num < 0:\n raise ValueError\n _chapter = Chapter.objects.prefetch_related('pages') \\\n .get(series__slug=slug, volume=vol, number=num)\n except (ValueError, TypeError):\n return JsonError('Bad request', 400)\n except ObjectDoesNotExist:\n return JsonError('Not found', 404)\n return JsonResponse(_chapter_response(request, _chapter))\n\n\ndef _is_author(request):\n return request.path.startswith('/api/v1/authors')\n\n\n@csrf_exempt\n@require_methods_api()\ndef all_people(request):\n prefetch = ('aliases', 'series_set__aliases')\n _type = Author if _is_author(request) else Artist\n people = _type.objects.prefetch_related(*prefetch).all()\n response = [_person_response(request, p) for p in people]\n return JsonResponse(response, safe=False)\n\n\n@csrf_exempt\n@require_methods_api()\ndef person(request, p_id):\n prefetch = ('aliases', 'series_set__aliases')\n try:\n p_id = int(p_id)\n if p_id < 1:\n raise ValueError\n _type = Author if _is_author(request) else Artist\n _person = _type.objects.prefetch_related(*prefetch).get(id=p_id)\n except (ValueError, TypeError):\n return JsonError('Bad request', 400)\n except ObjectDoesNotExist:\n return JsonError('Not found', 404)\n return JsonResponse(_person_response(request, _person))\n\n\n@csrf_exempt\n@require_methods_api()\ndef all_groups(request):\n prefetch = ('releases__series', 'roles__member')\n _groups = Group.objects.prefetch_related(*prefetch).all()\n response = [_group_response(request, g) for g in _groups]\n return JsonResponse(response, safe=False)\n\n\n@csrf_exempt\n@require_methods_api()\ndef group(request, g_id):\n prefetch = ('releases__series', 'roles__member')\n try:\n g_id = int(g_id)\n if g_id < 1:\n raise ValueError\n _group = Group.objects.prefetch_related(*prefetch).get(id=g_id)\n except (ValueError, TypeError):\n return JsonError('Bad request', 400)\n except ObjectDoesNotExist:\n return JsonError('Not found', 404)\n return JsonResponse(_group_response(request, _group))\n\n\n@csrf_exempt\n@require_methods_api()\ndef categories(request):\n values = list(Category.objects.values())\n return JsonResponse(values, safe=False)\n\n\n@csrf_exempt\n@require_methods_api()\ndef invalid_endpoint(request):\n return JsonError('Invalid API endpoint', 501)\n","sub_path":"api/v1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"242998062","text":"\"\"\"\nWindows Meta File\n\"\"\"\n\nfrom construct import *\n\n\nwmf_record = Struct(\n \"size\" / Int32ul, # size in words, including the size, function and params\n \"function\" / Enum(Int16ul,\n AbortDoc = 0x0052,\n Aldus_Header = 0x0001,\n AnimatePalette = 0x0436,\n Arc = 0x0817,\n BitBlt = 0x0922,\n Chord = 0x0830,\n CLP_Header16 = 0x0002,\n CLP_Header32 = 0x0003,\n CreateBitmap = 0x06FE,\n CreateBitmapIndirect = 0x02FD,\n CreateBrush = 0x00F8,\n CreateBrushIndirect = 0x02FC,\n CreateFontIndirect = 0x02FB,\n CreatePalette = 0x00F7,\n CreatePatternBrush = 0x01F9,\n CreatePenIndirect = 0x02FA,\n CreateRegion = 0x06FF,\n DeleteObject = 0x01F0,\n DibBitblt = 0x0940,\n DibCreatePatternBrush = 0x0142,\n DibStretchBlt = 0x0B41,\n DrawText = 0x062F,\n Ellipse = 0x0418,\n EndDoc = 0x005E,\n EndPage = 0x0050,\n EOF = 0x0000,\n Escape = 0x0626,\n ExcludeClipRect = 0x0415,\n ExtFloodFill = 0x0548,\n ExtTextOut = 0x0A32,\n FillRegion = 0x0228,\n FloodFill = 0x0419,\n FrameRegion = 0x0429,\n Header = 0x0004,\n IntersectClipRect = 0x0416,\n InvertRegion = 0x012A,\n LineTo = 0x0213,\n MoveTo = 0x0214,\n OffsetClipRgn = 0x0220,\n OffsetViewportOrg = 0x0211,\n OffsetWindowOrg = 0x020F,\n PaintRegion = 0x012B,\n PatBlt = 0x061D,\n Pie = 0x081A,\n Polygon = 0x0324,\n Polyline = 0x0325,\n PolyPolygon = 0x0538,\n RealizePalette = 0x0035,\n Rectangle = 0x041B,\n ResetDC = 0x014C,\n ResizePalette = 0x0139,\n RestoreDC = 0x0127,\n RoundRect = 0x061C,\n SaveDC = 0x001E,\n ScaleViewportExt = 0x0412,\n ScaleWindowExt = 0x0410,\n SelectClipRegion = 0x012C,\n SelectObject = 0x012D,\n SelectPalette = 0x0234,\n SetBKColor = 0x0201,\n SetBKMode = 0x0102,\n SetDibToDev = 0x0D33,\n SelLayout = 0x0149,\n SetMapMode = 0x0103,\n SetMapperFlags = 0x0231,\n SetPalEntries = 0x0037,\n SetPixel = 0x041F,\n SetPolyFillMode = 0x0106,\n SetReLabs = 0x0105,\n SetROP2 = 0x0104,\n SetStretchBltMode = 0x0107,\n SetTextAlign = 0x012E,\n SetTextCharExtra = 0x0108,\n SetTextColor = 0x0209,\n SetTextJustification = 0x020A,\n SetViewportExt = 0x020E,\n SetViewportOrg = 0x020D,\n SetWindowExt = 0x020C,\n SetWindowOrg = 0x020B,\n StartDoc = 0x014D,\n StartPage = 0x004F,\n StretchBlt = 0x0B23,\n StretchDIB = 0x0F43,\n TextOut = 0x0521,\n ),\n \"params\" / Array(this.size - 3, Int16ul),\n)\n\nwmf_placeable_header = Struct(\n \"key\" / Const(0x9AC6CDD7, Int32ul),\n \"handle\" / Int16ul,\n \"left\" / Int16sl,\n \"top\" / Int16sl,\n \"right\" / Int16sl,\n \"bottom\"/ Int16sl,\n \"units_per_inch\"/ Int16ul,\n Padding(4),\n \"checksum\" / Int16ul,\n)\n\nwmf_file = Struct(\n # --- optional placeable header ---\n \"placeable_header\" / Optional(wmf_placeable_header),\n\n # --- header ---\n \"type\" / Enum(Int16ul, \n InMemory = 0,\n File = 1,\n ),\n \"header_size\" / Const(9, Int16ul),\n \"version\" / Int16ul,\n \"size\" / Int32ul, # file size is in words\n \"number_of_objects\" / Int16ul,\n \"size_of_largest_record\" / Int32ul,\n \"number_of_params\" / Int16ul,\n\n # --- records ---\n \"records\" / GreedyRange(wmf_record)\n)\n","sub_path":"deprecated_gallery/wmf.py","file_name":"wmf.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"455292805","text":"#-*- coding: utf8 -*-\n\nimport os\nimport glob\nimport codecs\nimport tempfile\nimport subprocess\nimport platform\n\n'''\nTags text using STTS: http://www.deutschestextarchiv.de/doku/pos\n'''\nclass POStagger:\n \n def __init__(self):\n \n # set model and dirs\n self.m = 'models/german-fast.tagger'\n self.stagdir = os.path.join(os.path.dirname(__file__), 'dltk', 'stanford-postagger-full-2013-06-20')\n \n def tagit(self, infile):\n \n # set command\n if platform.system() == 'Windows':\n cmd = 'stanford-postagger.bat models\\\\german-fast.tagger ' + infile\n else:\n cmd = \"./stanford-postagger.sh \" + self.m + \" \" + infile\n\n # remember current dir and then set to stagdir\n currentDir = os.getcwd()\n os.chdir(self.stagdir)\n\n # get output\n tagout = os.popen(cmd).readlines() #GINA: issues in windows\n\n # return to orig directory and return ouput\n os.chdir(currentDir)\n return [i.strip() for i in tagout] \n\n\n # function to call from outside class, can handle multiple sentences \n def tag(self, sentences):\n \n file = self.write_temp_file(sentences)\n tagged = [unicode(x, encoding='utf8') for x in self.tagit(file)]\n #os.unlink(file) #GINA: issues in windows\n return tagged\n \n @staticmethod\n def write_temp_file(sentences):\n \n f, path = tempfile.mkstemp(text=True)\n\n with codecs.open(path, mode='w', encoding='utf8') as f:\n for s in sentences:\n f.write(s)\n f.write('\\n')\n f.close()\n return path\n ","sub_path":"src/germanPOStagger.py","file_name":"germanPOStagger.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"556582149","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\n\n# MNIST-Datensatz laden\n(x_train, _), (x_test, _) = tf.keras.datasets.mnist.load_data()\n\n# Daten formatieren\nx_train = x_train.astype('float32') / 255.0\nx_test = np.reshape(x_test, (len(x_test), 28, 28, 1))\nx_test = x_test.astype('float32') / 255.0\nx_train = np.reshape(x_train, (len(x_train), 28, 28, 1))\n\n# verrauschte Bilder (Input) generieren\nnoise_factor = 0.5\nx_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)\nx_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)\nx_train_noisy = np.clip(x_train_noisy, 0.0, 1.0)\nx_test_noisy = np.clip(x_test_noisy, 0.0, 1.0)\n\n# Modell definieren\ninput_data = tf.keras.Input(shape=(28, 28, 1))\neconv0 = tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='glorot_normal')(input_data)\nemaxpool0 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding='same')(econv0)\neconv1 = tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='glorot_normal')(emaxpool0)\nemaxpool1 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding='same')(econv1)\nencoded = emaxpool1\ndconv0 = tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='glorot_normal')(encoded)\ndupsample0 = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='nearest')(dconv0)\ndconv1 = tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='glorot_normal')(dupsample0)\ndupsample1 = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='nearest')(dconv1)\ndconv2 = tf.keras.layers.Conv2D(filters=1, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='sigmoid', kernel_initializer='glorot_normal')(dupsample1)\ndecoded = dconv2\n\n# Modell kompilieren\nautoencoder = tf.keras.Model(input_data, decoded)\nautoencoder.compile(optimizer='sgd', loss='mean_squared_error')\n\nprint(autoencoder.summary())\n\n# Modell trainieren und als Modelldatei speichern\nautoencoder.fit(x=x_train_noisy, y=x_train, batch_size=128, epochs=100, shuffle=True, validation_data=(x_test_noisy, x_test), callbacks=[tf.keras.callbacks.TensorBoard(log_dir='/tmp/denoiser', histogram_freq=0, write_graph=False)])\nautoencoder.save('denoiser.model')\n\n# Vorhersagen zum Testdatensatz erstellen\ndecoded_imgs = autoencoder.predict(x_test)\n\n# Matplotlib Abbildung anzeigen\nn = 10 # jeweils 10 Bilder\nplt.figure()\nfor i in range(n):\n # verrauschte Bilder\n ax = plt.subplot(3, n, 1+i)\n plt.imshow(x_test_noisy[i].reshape(28, 28))\n plt.gray()\n\n # entrauschte Bilder\n ax = plt.subplot(3, n, 1+n+i)\n plt.imshow(decoded_imgs[i].reshape(28, 28))\n plt.gray()\n\n # Original-Bilder\n ax = plt.subplot(3, n, 1+2*n+i)\n plt.imshow(x_test[i].reshape(28, 28))\n plt.gray()\nplt.show()\n","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616942040","text":"#!/usr/bin/env python3\n\nimport hail as hl\nimport sys \n\npart = sys.argv[1]\n\nhl.init(tmp_dir='/net/scratch/people/plggosborcz', default_reference='GRCh38')\n\nrpmk = hl.read_table('/net/archive/groups/plggneuromol/imdik-zekanowski-gts/data/external-data/repeatmasker-extended-keyed.ht')\ncov = hl.read_table('/net/scratch/people/plggosborcz/temp-mts/gnomad-cov-keyed.ht')\n\n\n\nhl.import_vcf('/net/archive/groups/plggneuromol/imdik-zekanowski-gts/data/joint-with-sportsmen/vcf-parts/'+str(part)+'-part.vcf.gz', \n\treference_genome='GRCh38',\n force_bgz = True,\n array_elements_required = False).write('/net/scratch/people/plggosborcz/temp-mts/'+str(part)+'-part.mt')\n\nmt = hl.read_matrix_table('/net/scratch/people/plggosborcz/temp-mts/'+str(part)+'-part.mt')\nmt = mt.filter_rows(hl.is_defined(rpmk[mt.locus]), keep = False)\n\nmt.checkpoint('/net/scratch/people/plggosborcz/temp-mts/'+str(part)+'-part-rpmk.mt')\n\n\n\nmt = mt.filter_rows(hl.is_defined(cov[mt.locus]), keep = True)\n\nmt.checkpoint('/net/scratch/people/plggosborcz/temp-mts/'+str(part)+'-part-cov.mt')\n\n\n\nmt = mt.annotate_cols(group = hl.if_else(mt.s.contains('B'), 'sport', 'GTS'))\nmt = mt.annotate_rows(dp_qc = hl.agg.group_by(mt.group, hl.agg.stats(mt.DP)),\n gq_qc = hl.agg.group_by(mt.group, hl.agg.stats(mt.GQ)),\n hwe = hl.agg.group_by(mt.group, hl.agg.hardy_weinberg_test(mt.GT)))\n\nmt = mt.annotate_rows(n_below_dp_3 = hl.agg.group_by(mt.group, hl.agg.count_where(mt.DP < 3)),\n n_below_gq_30 = hl.agg.group_by(mt.group, hl.agg.count_where(mt.GQ <30)))\n\nmt.checkpoint('/net/scratch/people/plggosborcz/temp-mts/'+str(part)+'-qc.mt')\n\nmt = mt.filter_rows((mt.dp_qc['sport'].mean > 5) &\n (mt.dp_qc['GTS'].mean > 5) &\n (mt.gq_qc['sport'].mean > 50) &\n (mt.gq_qc['GTS'].mean > 50) &\n (mt.hwe['sport'].p_value > 0.05) &\n (mt.hwe['GTS'].p_value > 0.05) &\n (mt.n_below_dp_3['sport'] < 3) &\n (mt.n_below_gq_30['sport'] < 30) &\n (mt.n_below_dp_3['GTS'] < 3) &\n (mt.n_below_gq_30['GTS'] <30))\n\nmt.checkpoint('/net/scratch/people/plggosborcz/temp-mts/'+str(part)+'-filtered.mt')\n\n","sub_path":"preprocessing/burden-and-family/python-scripts/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"272626611","text":"import torch\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\ndef load_data(dataset, directory, mean, std, batch_size, image_size):\n if dataset == 'train':\n data_transforms = transforms.Compose([transforms.RandomRotation(25),\n transforms.RandomResizedCrop(image_size),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean, std)])\n\n elif dataset in {'valid', 'test'}:\n data_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(image_size),\n transforms.ToTensor(),\n transforms.Normalize(mean, std)])\n\n # Load the datasets with ImageFolder\n data = datasets.ImageFolder(directory, transform=data_transforms)\n # Define the dataloaders\n dataloader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True)\n # Note that DataLoader orders the folders that it reads from so the indexing may change!\n classes = data.classes\n class_to_idx = data.class_to_idx\n \n return dataloader, classes, class_to_idx\n","sub_path":"python/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"345272382","text":"# coding: UTF-8\nfrom django.shortcuts import render\nfrom character.models import character\nfrom character.models import type_character\nfrom sagas.models import saga\nfrom fusion.models import type_fusion\nfrom fusion.models import fusion\nfrom django.http import HttpResponse\nimport json\n\n# Create your views here.\ndef get_all_types(request):\n alltypes = type_character.objects.all()\n races = []\n for tipo in alltypes:\n race = {}\n race[\"id\"] = tipo.id\n race[\"race\"] = tipo.nm_type_character\n races.append(race)\n \n return HttpResponse(json.dumps(races), content_type='application/json')\n\ndef get_type(request, type_character_id):\n tipo = type_character.objects.get(id=int(type_character_id))\n race = {}\n race[\"id\"]=tipo.id\n race[\"nm_type_character\"]= tipo.nm_type_character\n \n return HttpResponse(json.dumps(race), content_type='application/json')\n\ndef get_character_by_saga_id(request, id_saga): \n characters = character.objects.filter(saga_id=int(id_saga))\n personagens = []\n for chares in characters:\n charc = {}\n charc[\"id\"] = chares.id\n charc[\"nm_character\"] = chares.nm_character\n charc[\"img_character\"]= chares.img_character\n charc[\"fighting_power\"]= chares.fighting_power\n charc[\"saga\"]= saga.objects.get(id=int(chares.saga_id_id)).nm_saga\n charc[\"saga_id\"]= int(chares.saga_id_id)\n charc[\"race\"]= type_character.objects.get(id=int(chares.type_id_id)).nm_type_character\n personagens.append(charc)\n return HttpResponse(json.dumps(personagens), content_type='application/json')\n\ndef get_characters(request):\n allcharacters = character.objects.all()\n personagens = []\n for chares in allcharacters:\n charc = {}\n charc[\"id\"] = chares.id\n charc[\"nm_character\"] = chares.nm_character\n charc[\"img_character\"]= chares.img_character\n charc[\"fighting_power\"]= chares.fighting_power\n charc[\"saga\"]= saga.objects.get(id=int(chares.saga_id_id)).nm_saga\n charc[\"saga_id\"]= int(chares.saga_id_id)\n charc[\"race\"]= type_character.objects.get(id=int(chares.type_id_id)).nm_type_character\n personagens.append(charc)\n return HttpResponse(json.dumps(personagens), content_type='application/json')\n\ndef get_character(request,name_or_id):\n result = {}\n if name_or_id.isnumeric():\n allcharacters = character.objects.get(id=int(name_or_id))\n result[\"id\"] = allcharacters.id\n result[\"nm_character\"] = allcharacters.nm_character\n result[\"img_character\"] = allcharacters.img_character\n result[\"fighting_power\"] = allcharacters.fighting_power\n result[\"race\"] = type_character.objects.get(id=int(allcharacters.type_id_id)).nm_type_character\n result[\"saga\"] = saga.objects.get(id=int(allcharacters.saga_id_id)).nm_saga\n else:\n alllike = []\n allcharacters = character.objects.filter(string__contains=name_or_id)\n for chares in allcharacters:\n charc = {}\n charc[\"id\"] = chares.id\n charc[\"nm_character\"] = chares.nm_character\n charc[\"img_character\"]= chares.img_character\n charc[\"fighting_power\"]= chares.fighting_power\n charc[\"race\"]= type_character.objects.get(id=int(chares.type_id_id)).nm_type_character\n charc[\"saga\"]= saga.objects.get(id=int(chares.saga_id_id)).nm_saga\n charc[\"saga_id\"]= int(chares.saga_id_id)\n alllike.append(chares)\n result[\"characters\"] = alllike\n return HttpResponse(json.dumps(result), content_type='application/json')\n \ndef seeds(request):\n \n sg1 = saga(\n nm_saga=\"Dragon Ball\",\n ds_saga=\"Dragon Ball ist die erste von drei Fernsehserien, die auf dem gleichnamigen Manga von Akira Toriyama basieren. Für die Erstausstrahlung im japanischen Fernsehen auf dem Fernsehsender Fuji TV vom 26. Februar 1986 bis 12. April 1989 wurden vom Animationsstudio Toei insgesamt 153 Episoden produziert, die weltweit exportiert und durch eine angepasste Synchronisation in lokalen Fernsehstationen ausgestrahlt wurden. Zusätzlich zu der Fernsehserie wurden noch vier Kinofilme produziert. Die Handlung wird in der Fernsehserie Dragon Ball Z fortgesetzt, die ebenfalls auf dem Manga basiert.\",\n img_saga=\"https://i.pinimg.com/originals/77/82/f0/7782f08f34d373c4caf42aee9160a32d.jpg\")\n sg1.save()\n\n sg2 = saga(\n nm_saga=\"Dragon Ball Z\",\n ds_saga=\"Dragon Ball Z ist eine japanische 291 Episoden umfassende Animeserie, die dem Shōnen-Genre zuzuordnen ist und die Fortsetzung der Fernsehserie Dragon Ball darstellt. Beide Animes beruhen auf der von 1984 bis 1995 erschienenen, international erfolgreichen 42-bändigen Manga-Serie Dragon Ball des Zeichners Akira Toriyama. Während der Dragon-Ball-Anime die Manga-Handlung bis Band 17, Kapitel 194 umsetzt und Geschehnisse in der Kindheit der Hauptfigur Son-Goku schildert, führt Dragon Ball Z die Geschichte mit Son-Goku als Erwachsenem ab Band 17, Kapitel 195 weiter.\",\n img_saga=\"http://ptanime.com/wp-content/uploads/2015/05/Dragon_Ball_Z_Analise_Imagem_Saga_Majin_Buu.jpg\")\n sg2.save()\n sg3 = saga(\n nm_saga=\"Dragon Ball GT\",\n ds_saga=\"Dragon Ball GT ist die zweite Fortsetzungsserie der Animeserie Dragon Ball. Sie wurde von Beginn an als Anime konzipiert und basiert nicht, wie die vorhergehenden Animeserien Dragon Ball und Dragon Ball Z, auf der Originalhandlung des Mangas des japanischen Zeichners Akira Toriyama. Toriyama wirkte bei Dragon Ball GT lediglich als künstlerischer Berater mit.\",\n img_saga=\"https://vignette2.wikia.nocookie.net/dbz-dokkanbattle/images/9/95/Black_Star_DB_Saga.png/revision/latest?cb=20160910202651\")\n sg3.save()\n sg4 = saga(\n nm_saga=\"Dragon Ball Super\",\n ds_saga=\"Dragon Ball Super ist eine Animeserie, die von Tōei Animation produziert wird. Die erste Folge wurde am 5. Juli 2015 ausgestrahlt. Sie ist der direkte Nachfolger zu Dragon Ball Z. Die Handlung spielt in der zehn Jahre umfassenden Lücke zwischen dem Sieg über Boo und dem Turnier, bei dem Son Goku auf Boos Wiedergeburt Oob trifft. Die Handlung beginnt 4 Jahre nach dem Sieg über Boo. Bei den ersten 27 Folgen handelt es sich inhaltlich um Neuerzählungen der Filme Kampf der Götter und Resurrection ‚F‘.\",\n img_saga=\"https://i.pinimg.com/originals/81/57/19/81571933f0d137e2d6c98304e0376311.png\")\n sg4.save()\n\n sg5 = saga(\n nm_saga=\"Dragon Ball AF\",\n ds_saga=\"Dragonball AF ist eine Art Fan-Fiction über den Manga und Anime Dragonball von Akira Toriyama, der darauf folgte, dass viele Fans sehr traurig darüber waren, dass Dragonball mit Dragonball GT als beendet galt. AF steht dabei für After Future. Manche Leute glauben, dass Dragonball AF auch wirklich existiert, aber das ist wohl jedem selbst überlassen. Im Internet geistert dieser Begriff allerdings schon seit mehreren Jahren umher und gewann so mehr und mehr an Bekanntheit, sodass immer mehr Seiten auf Dragonball AF hinweisen und sehr viele Bilder und Ähnliches entstanden.\",\n img_saga=\"https://i.ytimg.com/vi/-xNbJ803Kkw/maxresdefault.jpg\")\n sg5.save()\n\n tpf = type_fusion(nm_type_fusion=\"Potara Fusion\")\n tpf.save()\n tpf2 = type_fusion(nm_type_fusion=\"Fusionstanz\")\n tpf2.save()\n\n tpp = type_character(nm_type_character=\"Mensch\")\n tpp.save()\n tpp = type_character(nm_type_character=\"Saiyajin\")\n tpp.save()\n tpp = type_character(nm_type_character=\"Namikianer\")\n tpp.save()\n tpp = type_character(nm_type_character=\"Android\")\n tpp.save()\n tpp = type_character(nm_type_character=\"Majin\")\n tpp.save()\n\n p = character(\n nm_character=\"Kid Goku\",\n img_character=\"http://www.imagenswiki.com/Uploads/imagenswiki.com/ImagensGrandes/son-goku-crianca.jpg\",\n fighting_power=\"260\")\n p.type_id_id = 2\n p.saga_id = sg1\n p.save()\n p = character(\n nm_character=\"Goku\",\n img_character=\"https://vignette.wikia.nocookie.net/dragonball/images/5/5b/Gokusteppingoutofaspaceship.jpg/revision/latest/scale-to-width-down/224?cb=20150325220848\",\n fighting_power=\"924\")\n p.type_id_id = 2\n p.saga_id = sg2\n p.save()\n p = character(\n nm_character=\"Goku Super Saiyajin 1\",\n img_character=\"https://dreager1.files.wordpress.com/2011/08/snap2149516qs7.jpg\",\n fighting_power=\"150000000\")\n p.type_id_id = 2\n p.saga_id = sg2\n p.save()\n p = character(\n nm_character=\"Goku Super Saiyajin 2\",\n img_character=\"https://vignette.wikia.nocookie.net/dragonball/images/a/ac/Goku-Super-Saiyan-2-.jpg/revision/latest?cb=20110426171840\",\n fighting_power=\"6000000000\")\n p.type_id_id = 2\n p.saga_id = sg2\n p.save()\n p = character(\n nm_character=\"Goku Super Saiyajin 3\",\n img_character=\"https://vignette2.wikia.nocookie.net/dragonuniverse/images/8/89/SSJ3.png/revision/latest?cb=20160928233848\",\n fighting_power=\"10000000000\")\n p.type_id_id = 2\n p.saga_id = sg2\n p.save()\n goku = character(\n nm_character=\"Goku\",\n img_character=\"https://vignette.wikia.nocookie.net/dragonball/images/5/5b/Gokusteppingoutofaspaceship.jpg/revision/latest/scale-to-width-down/224?cb=20150325220848\",\n fighting_power=\"924\")\n goku.type_id_id = 2\n goku.saga_id_id = 4\n goku.save()\n p = character(\n nm_character=\"Goku Super Saiyajin 1\",\n img_character=\"https://dreager1.files.wordpress.com/2011/08/snap2149516qs7.jpg\",\n fighting_power=\"150000000\")\n p.type_id_id = 2\n p.saga_id_id = 4\n p.save()\n p = character(\n nm_character=\"Goku Super Saiyajin 2\",\n img_character=\"https://vignette.wikia.nocookie.net/dragonball/images/a/ac/Goku-Super-Saiyan-2-.jpg/revision/latest?cb=20110426171840\",fighting_power=\"6000000000\")\n p.type_id_id = 2\n p.saga_id_id = 4\n p.save()\n p = character(nm_character=\"Goku Super Saiyajin 3\",img_character=\"https://vignette2.wikia.nocookie.net/dragonuniverse/images/8/89/SSJ3.png/revision/latest?cb=20160928233848\",fighting_power=\"10000000000\")\n p.type_id_id = 2\n p.saga_id_id = 4\n p.save()\n p = character(nm_character=\"Goku Super Saiyajin Blue\",img_character=\"http://vignette1.wikia.nocookie.net/dragonball/images/1/12/SSGSS_GOKU.png/revision/latest?cb=20151025084338\",fighting_power=\"100000000000\")\n p.type_id_id = 2\n p.saga_id_id = 4\n p.save()\n p = character(nm_character=\"(GT) Goku\",img_character=\"https://i.stack.imgur.com/6HrTE.jpg\",fighting_power=\"10000000\")\n p.type_id_id = 2\n p.saga_id_id = 3\n p.save()\n p = character(nm_character=\"(GT) Goku Super Saiyajin 1\",img_character=\"https://static.comicvine.com/uploads/original/14/149746/3647183-4101411823-Goku_.jpg\",fighting_power=\"150000000\")\n p.type_id_id = 2\n p.saga_id_id = 3\n p.save()\n p = character(nm_character=\"(GT) Goku Super Saiyajin 2\",img_character=\"http://vignette2.wikia.nocookie.net/dragonball/images/7/7f/GT_Kid_Goku_Super_Saiyan_2_by_dbzataricommunity.jpg/revision/latest?cb=20110412181525\",fighting_power=\"6000000000\")\n p.type_id_id = 2\n p.saga_id_id = 3\n p.save()\n p = character(nm_character=\"(GT) Goku Super Saiyajin 3\",img_character=\"http://pm1.narvii.com/6152/0abf4a01f38c1f84e7ea32e9601aaa1575b93e7e_hq.jpg\",fighting_power=\"10000000000\")\n p.type_id_id = 2\n p.saga_id_id = 3\n p.save()\n p = character(nm_character=\"Goku Super Saiyajin 4\",img_character=\"http://vignette4.wikia.nocookie.net/p__/images/f/f1/Goku_Super_Saiyan_4.png/revision/latest?cb=20130805024507&path-prefix=protagonist\",fighting_power=\"100000000000\")\n p.type_id_id = 2\n p.saga_id_id = 3\n p.save()\n p = character(nm_character=\"Vegeta\",img_character=\"https://upload.wikimedia.org/wikipedia/en/8/88/Vegeta_Dragon_Ball.jpg\",fighting_power=\"1200\")\n p.type_id_id = 2\n p.saga_id_id = 2\n p.save()\n p = character(nm_character=\"Vegeta Super Saiyajin 1\",img_character=\"https://vignette.wikia.nocookie.net/dragonball/images/6/6b/Vegeta_becomes_Super_Saiyan.JPG/revision/latest?cb=20120214203120\",fighting_power=\"2200\")\n p.type_id_id = 2\n p.saga_id_id = 2\n p.save()\n p = character(nm_character=\"Vegeta Super Saiyajin 2\",img_character=\"https://i.pinimg.com/originals/94/f3/b7/94f3b7f8bbda987da4eaa53e2cc99655.jpg\",fighting_power=\"\")\n p.type_id_id = 2\n p.saga_id_id = 2\n p.save()\n p = character(nm_character=\"Vegeta\",img_character=\"\",fighting_power=\"\")\n p.type_id_id = 2\n p.saga_id_id = 3\n p.save()\n p = character(nm_character=\"Vegeta Super Saiyajin 1\",img_character=\"\",fighting_power=\"\")\n p.type_id_id = 2\n p.saga_id_id = 3\n p.save()\n p = character(nm_character=\"Vegeta Super Saiyajin 2\",img_character=\"\",fighting_power=\"\")\n p.type_id_id = 2\n p.saga_id_id = 3\n p.save()\n p = character(nm_character=\"Vegeta Super Saiyajin 4\",img_character=\"https://vignette2.wikia.nocookie.net/poohadventures/images/4/40/Vegeta-super-saiyan-4.jpg/revision/latest?cb=20150403211313\",fighting_power=\"\")\n p.type_id_id = 2\n p.saga_id_id = 2\n p.save()\n vegeta = character(nm_character=\"Vegeta\",img_character=\"\",fighting_power=\"\")\n vegeta.type_id_id = 2\n vegeta.saga_id_id = 4\n vegeta.save()\n p = character(nm_character=\"Vegeta Super Saiyajin 1\",img_character=\"\",fighting_power=\"\")\n p.type_id_id = 2\n p.saga_id_id = 4\n p.save()\n p = character(nm_character=\"Vegeta Super Saiyajin 2\",img_character=\"\",fighting_power=\"\")\n p.type_id_id = 2\n p.saga_id_id = 4\n p.save()\n p = character(nm_character=\"Vegeta Super Saiyajin Blue\",img_character=\"https://res.cloudinary.com/jerrick/image/upload/f_auto,fl_progressive,q_auto,c_fit,w_1140/a54xtelfenxa1wyidccv\",fighting_power=\"\")\n p.type_id_id = 2\n p.saga_id_id = 4\n p.save()\n \n tp = fusion(type_fusion_id=tpf,character1_id=goku,character2_id=vegeta,nm_character_fusion=\"Vegetto\")\n tp.character1_id_id = 2\n tp.character2_id_id = 15\n tp.type_fusion_id_id = 1\n tp.save()\n tp = fusion(type_fusion_id=tpf2,character1_id=goku,character2_id=vegeta,nm_character_fusion=\"Gojeta\")\n tp.character1_id_id = 14\n tp.character2_id_id = 21\n tp.type_fusion_id_id = 2\n tp.save()\n \n return HttpResponse(\"201\")","sub_path":"character/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645984934","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 15 22:41:09 2021\n\n@author: Tracy\n\"\"\"\nimport json\nimport pandas as pd\nimport joblib\nfrom sklearn.metrics import roc_curve, confusion_matrix, roc_auc_score, average_precision_score,accuracy_score, precision_recall_curve\nimport math\n\ntest = pd.read_csv('./data/test.csv')\nclf = joblib.load('model.pkl')\n\nX_test, Y_test = test[['Pclass', 'Sex','SibSp','Parch','AgeBand']], test['Survived']\npred = clf.predict(X_test)\nacc = accuracy_score(Y_test, pred)\nprint(acc)\n\n \nprecision, recall, prc_thresholds = precision_recall_curve(Y_test, pred)\nfpr, tpr, roc_thresholds = roc_curve(Y_test, pred)\n\navg_prec = average_precision_score(Y_test, pred)\nroc_auc = roc_auc_score(Y_test, pred)\n\nwith open('scores.json', \"w\") as fd:\n json.dump({\"avg_prec\": avg_prec, \"roc_auc\": roc_auc, 'accuracy': acc}, fd)\n\n\n\n# dvc run -n evaluate -d src/evaluate.py -d data/test.csv -d model.pkl -M scores.json python src/evaluate.py\n\n# nth_point = math.ceil(len(prc_thresholds) / 1000)\n# prc_points = list(zip(precision, recall, prc_thresholds))[::nth_point]\n# with open('prc.json', \"w\") as fd:\n# json.dump(\n# {\n# \"prc\": [\n# {\"precision\": p, \"recall\": r, \"threshold\": t}\n# for p, r, t in prc_points\n# ]\n# },\n# fd,\n# indent=4,\n# )\n\n# with open('roc.json', \"w\") as fd:\n# json.dump(\n# {\n# \"roc\": [\n# {\"fpr\": fp, \"tpr\": tp, \"threshold\": t}\n# for fp, tp, t in zip(fpr, tpr, roc_thresholds)\n# ]\n# },\n# fd,\n# indent=4,\n# )\n \n ","sub_path":"src/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626003150","text":"from sqlalchemy.sql import and_\nimport globals\nimport os\n\nparentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nos.sys.path.insert(0, parentdir)\n\nfrom models import *\n\n\n# Function that check if a gps_car_id was supposed\n# to run a service with the headcode\ndef isPlanned(gps_car_id, headcode):\n globals.db_lock.acquire()\n result = db.session.query(Schedule).filter(and_(\n Schedule.unit == gps_car_id, Schedule.headcode == headcode\n ))\n globals.db_lock.release()\n try:\n result[0].as_dict()\n return True\n except:\n return False\n\n\n# Gets the unit from a gps_car_id by querying\n# the UnitToGPSMapping table\n# NOT USING THIS FUNCTION ANYMORE\ndef getUnitFromCarId(gps_car_id):\n globals.db_lock.acquire()\n print(\"WARNING - This function should not be used!\")\n result = db.session.query(UnitToGPSMapping).filter(\n UnitToGPSMapping.gps_car_id == gps_car_id)\n globals.db_lock.release()\n try:\n return result[0].as_dict()['unit']\n except:\n return ''\n\n\n# Gets the diagram_service row for a\n# particular headcode\ndef getDiagramServiceByHeadcode(headcode):\n globals.db_lock.acquire()\n result = db.session.query(DiagramService).filter(\n DiagramService.headcode == headcode\n )\n globals.db_lock.release()\n try:\n return result[0].as_dict()\n except:\n return None\n\n\n# gets the rows from diagram_stop for a particular\n# diagram service\ndef getDiagramStopsByService(diagram_service):\n if diagram_service is None:\n return []\n globals.db_lock.acquire()\n result = db.session.query(DiagramStop).filter(\n DiagramStop.diagram_service_id == diagram_service['id']\n )\n globals.db_lock.release()\n return map(lambda x: x.as_dict(), result)\n\n\n# Gets all of the diagram stops for a service\ndef getDiagramStopsByHeadcode(headcode):\n diagram_service = getDiagramServiceByHeadcode(headcode)\n return getDiagramStopsByService(diagram_service)\n\n\n# Gets the cif_uid from the Schedule using unit and headcode\n# NOT IN USE\ndef cif_uidFromUnitAndHeadcode(unit, headcode):\n globals.db_lock.acquire()\n result = db.session.query(Schedule).filter(and_(\n Schedule.unit == unit, Schedule.headcode == headcode\n ))\n globals.db_lock.release()\n try:\n temp = result[0].as_dict()['cif_uid']\n if temp is None:\n return ''\n return temp\n except:\n return ''\n\n\ndef cif_uidFromHeadcode(headcode):\n globals.db_lock.acquire()\n result = db.session.query(DiagramService).filter(\n DiagramService.headcode == headcode)\n globals.db_lock.release()\n try:\n temp = result[0].as_dict()['cif_uid']\n return temp\n except:\n return None\n","sub_path":"algorithm/db_queries.py","file_name":"db_queries.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629719592","text":"#!/usr/bin/python3\n\nchunk_size = 1024*1024\nno_of_files = 1\nchunks_name = \"image_chunks_\"\n\nwith open(\"image1.jpg\", \"rb\") as fp1 :\n read_data = fp1.read(chunk_size)\n while read_data :\n with open(f\"{chunks_name}{no_of_files}.jpg\", \"wb\") as fp2 :\n fp2.write(read_data)\n read_data = fp1.read(chunk_size)\n no_of_files = no_of_files + 1\n","sub_path":"reference_codes/chunks.py","file_name":"chunks.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"198166722","text":"import math\r\n\r\n# 二分 python 可暴力\r\n# 执行用时 :36 ms, 在所有 python 提交中击败了98.94% 的用户\r\n# 内存消耗 :12 MB, 在所有 python 提交中击败了33.00%的用户\r\nclass Solution(object):\r\n def findMin(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: int\r\n \"\"\"\r\n nums.sort()\r\n return nums[0]\r\nif __name__ == '__main__':\r\n\r\n\r\n\r\n n = [3,4,5,1,2]\r\n p = Solution()\r\n a = p.findMin(n)\r\n print(a)\r\n\r\n\r\n\r\n #p.compare(A,B)\r\n\r\n\r\n\r\n\r\n\r\n #print(s)\r\n #print(test.lastSubstring(\"abab\"))\r\n","sub_path":"Number theory/154/154.py","file_name":"154.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558851727","text":"from utils import most_common_words, most_common_nouns, create_bag_of_words, similarity, nearest_cos, \\\n change_to_emb, mean_vectors\nfrom files import load_data, load_file_to_string, load_files_to_string, load_vectors, load_paths_from_dir\nimport pandas as pd\n\n# Settings\ndata = 'data/shows'\nnumber_of_words = 100\nmax_len = 20000\nemb_dir = 'embedding/'\nemb_file = 'wiki.en'\n\n# Load names and paths of shows from chosen directory\nnames, paths = load_paths_from_dir(data)\nprint(names)\n\n\n# Choose most common nouns from shows subtitles\nmovies_common_words = []\nprint(\"Most common words.\")\nfor path in paths:\n print(path)\n movies_common_words.append(most_common_nouns(load_files_to_string(path, how_many=10), number_of_words))\n\n# Make lists of most common nouns\nmovies_words_lists = []\nsum_list = []\nprint(\"Words lists.\")\nfor m in movies_common_words:\n word_list = [t[0] for t in m]\n movies_words_lists.append(word_list)\n sum_list += word_list\n\n# Create embeddings for most common nouns\nvectors_list = []\nprint(len(names))\ni = 1\nprint(\"Mean vectors.\")\nfor name, m in zip(names, movies_words_lists):\n print(name)\n emb_dict = load_vectors(emb_dir + emb_file + '.vec', m)\n vectors_list.append(change_to_emb(m, emb_dict))\n print(i)\n i += 1\n\ndf_vectors = pd.DataFrame({'show': names, 'vector': vectors_list, \"words\": movies_words_lists})\ndf_vectors.to_csv(\"emb_top_vectors.csv\")\n\n\n\n","sub_path":"GHR/src/word_embeddings_for_docs.py","file_name":"word_embeddings_for_docs.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37844801","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport markdown\nfrom mdx_math import MathExtension\n\n\nhtml_head_file = open(\"html_head.txt\",\"r\",encoding='utf-8')\nhtml_head = html_head_file.read()\nhtml_head_file.close()\n\nhtml_tail = \"\\n\\n\"\nhtml_body = \"\"\n\n# 所支持的复杂元素\nexts = ['markdown.extensions.extra', 'markdown.extensions.codehilite','markdown.extensions.tables','markdown.extensions.toc',MathExtension(enable_dollar_delimiter=True)]\n\nfile_dir = input(\"输入需转换文件所在目录:\")\nfor filename in os.listdir(file_dir):\n if filename[-3:] == '.md':\n html_body_file = open(file_dir+filename,\"r\",encoding='utf-8')\n html_body_txt = html_body_file.read()\n html_body_file.close()\n\n md = markdown.Markdown(extensions = exts)\n html_body = md.convert(html_body_txt)\n\n html = html_head + html_body + html_tail\n html_file = open(file_dir+filename[:-3]+\".html\",\"w\",encoding='utf-8')\n html_file.write(html)\n html_file.close()\n print(\"{}转换完毕\".format(filename[:-3]))\n\n\n\n","sub_path":"ZONE/hyj1999.github.io/Python/实用例程/CrawTencentCourseName/md2html.py","file_name":"md2html.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300266467","text":"class OxoBoard:\n\n def __init__(self):\n \"\"\" The initialiser. Initialise any fields you need here. \"\"\"\n self.board_rows = 3\n self.board_columns = 3\n self.board_array = []\n # create the board array\n for x in range(self.board_rows):\n self.board_array.append([])\n\n for y in range(self.board_columns):\n self.board_array[x].append(0)\n\n self.show()\n\n def get_square(self, x, y):\n \"\"\" Return 0, 1 or 2 depending on the contents of the specified square. \"\"\"\n\n square_content = self.board_array[x][y]\n return square_content\n\n def set_square(self, x, y, mark):\n \"\"\" If the specified square is currently empty (0), fill it with mark and return True.\n If the square is not empty, leave it as-is and return False. \"\"\"\n\n if self.board_array[x][y] == 0:\n self.board_array[x][y] = mark\n return True\n else:\n return False\n\n def is_board_full(self):\n \"\"\" If there are still empty squares on the board, return False.\n If there are no empty squares, return True. \"\"\"\n\n full_columns = 0\n\n # check if all of the columns are full\n for x in range(self.board_rows):\n if 0 in self.board_array[x]:\n return False\n else:\n full_columns += 1\n if full_columns == self.board_rows:\n return True\n\n def check_horizontal(self):\n \"\"\"Check if a player has connected a row horizontally.\"\"\"\n\n for x in range(self.board_rows):\n player1_score = 0\n player2_score = 0\n for y in range(self.board_columns):\n if 1 == self.board_array[y][x]:\n player1_score += 1\n else:\n player1_score = 0\n if player1_score == self.board_columns:\n return 1\n\n if 2 == self.board_array[y][x]:\n player2_score += 1\n else:\n player2_score = 0\n if player2_score == self.board_columns:\n return 2\n\n return 0\n\n def check_diagonal(self):\n \"\"\"Check if a player has connected a row diagonally.\"\"\"\n\n connected_o_1 = 0\n connected_x_1 = 0\n\n # check first diagonal line\n for y in range(self.board_columns - 1, -1, -1):\n\n # check for player 1\n if self.board_array[y][y] == 1:\n connected_o_1 += 1\n else:\n connected_o_1 = 0\n if connected_o_1 == self.board_columns:\n return 1\n\n # check for player 2\n if self.board_array[y][y] == 2:\n connected_x_1 += 1\n else:\n connected_x_1 = 0\n if connected_x_1 == self.board_columns:\n return 2\n\n connected_o_2 = 0\n connected_x_2 = 0\n x = -1\n\n # check second diagonal line\n for y in range(self.board_columns - 1, -1, -1):\n x += 1\n\n # check for player 1\n if self.board_array[x][y] == 1:\n connected_o_2 += 1\n else:\n connected_o_2 = 0\n if connected_o_2 == self.board_columns:\n return 1\n\n # check for player 2\n if self.board_array[x][y] == 2:\n connected_x_2 += 1\n else:\n connected_x_2 = 0\n if connected_x_2 == self.board_columns:\n return 2\n\n return 0\n\n def check_vertical(self):\n \"\"\"Check if a player has connected a row vertically.\"\"\"\n\n for x in range(self.board_rows):\n\n # check for player 1\n if 0 not in self.board_array[x] and 2 not in self.board_array[x]:\n return 1\n\n # check for player 2\n if 0 not in self.board_array[x] and 1 not in self.board_array[x]:\n return 2\n\n return 0\n\n def get_winner(self):\n \"\"\" If a player has connected a row, return 1 or 2 depending on which player.\n Otherwise, return 0. \"\"\"\n\n # get results\n diagonal = self.check_diagonal()\n vertical = self.check_vertical()\n horizontal = self.check_horizontal()\n\n # compare all results\n if diagonal == 1 or vertical == 1 or horizontal == 1:\n return 1\n elif diagonal == 2 or vertical == 2 or horizontal == 2:\n return 2\n else:\n return 0\n\n def show(self):\n \"\"\" Display the current board state in the terminal. You should not need to edit this. \"\"\"\n\n for y in range(3):\n if y > 0:\n print(\"--+---+--\")\n for x in range(3):\n if x > 0:\n print('|',)\n\n # Print a space for empty (0), an O for player 1, or an X for player 2\n print(\" OX\"[self.get_square(x, y)],)\n print\n","sub_path":"oxo.py","file_name":"oxo.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"223060941","text":"from unittest import TestCase\n\nfrom cjax.utils.math_trees import *\nimport jax.numpy as np\nfrom examples.conv_nn.conv_nn import ConvNeuralNetwork\nimport copy\n\n\nclass TestPytree(TestCase):\n def setUp(self):\n self.x = [np.array([0.5, 0.5]), 0.5, {\"beta\": 0.5}]\n self.y = [np.array([0.5, 0.5]), 0.5, {\"beta\": 0.5}]\n self.z = [np.array([0.0, 0.0]), 0.0, {\"beta\": 0.0}]\n self.x1 = [np.array([1.0, 1.0]), 1.0, {\"beta\": 1.0}]\n self.cnn_problem = ConvNeuralNetwork()\n self.flax_conv, self.bparams = self.cnn_problem.initial_value()\n self.flax_conv1 = copy.deepcopy(self.flax_conv)\n\n\nclass TestPytreeDot(TestPytree):\n def test_dot(self):\n self.assertEqual(1.0, pytree_dot(self.x, self.y))\n self.assertEqual(pytree_array_equal(self.flax_conv, self.flax_conv1), True)\n self.assertEqual(361.93063, pytree_dot(self.flax_conv, self.flax_conv1))\n\n\nclass TestPytreeOnesLike(TestPytree):\n def test_dot(self):\n self.assertEqual(pytree_array_equal(self.x1, pytree_ones_like(self.x)), True)\n\n\nclass TestPytreeSub(TestPytree):\n def test_sub(self):\n self.assertEqual(pytree_array_equal(self.z, pytree_sub(self.x, self.y)), True)\n self.assertEqual(pytree_array_equal(self.flax_conv, self.flax_conv1), True)\n self.assertEqual(\n pytree_array_equal(\n pytree_zeros_like(self.flax_conv),\n pytree_sub(self.flax_conv, self.flax_conv1),\n ),\n True,\n )\n","sub_path":"build/lib/tests/utils/test_pytree.py","file_name":"test_pytree.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"5854659","text":"# -*- coding: utf-8 -*-\n\nimport json\n\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import bulk\n\nimport tensorflow_hub as hub\nimport tensorflow_text\nimport kss, numpy\n\n\n##### INDEXING #####\n\ndef index_data():\n print(\"Creating the 'posts' index.\")\n client.indices.delete(index=INDEX_NAME, ignore=[404])\n\n with open(INDEX_FILE) as index_file:\n source = index_file.read().strip()\n client.indices.create(index=INDEX_NAME, body=source)\n\n count = 0\n\n with open(DATA_FILE) as data_file:\n for line in data_file:\n line = line.strip()\n\n json_data = json.loads(line)\n\n docs = []\n for j in json_data:\n count += 1\n\n docs.append(j)\n if count % BATCH_SIZE == 0:\n index_batch(docs)\n docs = []\n print(\"Indexed {} documents.\".format(count))\n\n if docs:\n index_batch(docs)\n print(\"Indexed {} documents.\".format(count))\n\n client.indices.refresh(index=INDEX_NAME)\n print(\"Done indexing.\")\n\n\ndef paragraph_index(paragraph):\n # 문장단위 분리\n avg_paragraph_vec = numpy.zeros((1, 512))\n sent_count = 0\n for sent in kss.split_sentences(paragraph):\n # 문장을 embed 하기\n # vector들을 평균으로 더해주기\n avg_paragraph_vec += embed_text([sent])\n sent_count += 1\n avg_paragraph_vec /= sent_count\n return avg_paragraph_vec.ravel(order='C')\n\n\ndef index_batch(docs):\n titles = [doc[\"title\"] for doc in docs]\n title_vectors = embed_text(titles)\n paragraph_vectors = [paragraph_index(doc[\"paragraph\"]) for doc in docs]\n requests = []\n for i, doc in enumerate(docs):\n request = doc\n request[\"_op_type\"] = \"index\"\n request[\"_index\"] = INDEX_NAME\n request[\"title_vector\"] = title_vectors[i]\n request[\"paragraph_vector\"] = paragraph_vectors[i]\n requests.append(request)\n bulk(client, requests)\n\n\n##### EMBEDDING #####\n\ndef embed_text(input):\n vectors = model(input)\n return [vector.numpy().tolist() for vector in vectors]\n\n\n##### MAIN SCRIPT #####\n\nif __name__ == '__main__':\n INDEX_NAME = \"korquad\"\n INDEX_FILE = \"./index.json\"\n\n DATA_FILE = \"./KorQuAD_v1.0_train_convert.json\"\n BATCH_SIZE = 100\n\n SEARCH_SIZE = 3\n\n print(\"Downloading pre-trained embeddings from tensorflow hub...\")\n module_url = \"https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\"\n print(\"module %s loaded\" % module_url)\n model = hub.load(module_url)\n\n client = Elasticsearch()\n\n index_data()\n\n print(\"Done.\")\n","sub_path":"put_data.py","file_name":"put_data.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"523156159","text":"import re\nimport os\nimport sys\nimport time\nimport getopt\nimport string\nimport logging\nimport subprocess\nimport showprocess\nfrom dwarf_variable_location import *\n\nlogging.getLogger('CU_process').setLevel(logging.ERROR)\nlogging.getLogger('dwarf_expr').setLevel(logging.ERROR)\nlogging.getLogger('dwarf_variable_location').setLevel(logging.DEBUG)\nlogging.getLogger('typesupport').setLevel(logging.WARNING)\n\ndef parse(cpppath, update, resultdir):\n compiler = None\n suffix = None\n if cpppath.endswith('.cpp'):\n compiler = \"g++-4.8\"\n suffix = \".cpp\"\n elif cpppath.endswith('.c') :\n compiler = \"gcc-4.8\"\n suffix = \".c\"\n if compiler != None:\n srcname = cpppath.split(b'/')[-1]\n # resultfile = resultdir +'/' + srcname[0:srcname.find(suffix)]\n elffile = cpppath[0:cpppath.find(suffix)]\n # print(srcname[0:srcname.find('.cpp')])\n # print(elffile)\n # print(resultfile)\n result = resultdir + '/' + elffile.split(b'/')[-1] + \".out\" \n if os.path.exists(result):\n print(\"Skip processed file: %s\" % result)\n return\n print(cpppath)\n compilercmd = [compiler, '-fno-pie', '-fno-pic', '-fno-stack-protector', '-g3', '-o', elffile, cpppath, '-static', '-m32']\n try:\n print(compilercmd)\n trace = subprocess.check_output(compilercmd)\n print(trace)\n if trace.find(\"error:\") == -1:\n elf = ElfDwarf(elffile, None, resultdir)\n\n except subprocess.CalledProcessError as e:\n print(\"run gcc error(%s)\")\n return None\n \n \ndef dirlist(path, update, result, process_bar): \n allfile = []\n\n filelist = os.listdir(path) \n for filename in filelist: \n filepath = os.path.join(path, filename) \n if not os.path.isdir(filepath): \n allfile.append(filepath)\n #print filepath\n if os.path.exists(filepath):\n process_bar.show_process(filepath)\n parse(filepath, update, result)\n else:\n print(\"[%s] file does not exist\" %(filepath))\n else: \n dirlist(filepath, update, result, process_bar) \n\ndef dir_size_calculation(path):\n filenum = 0\n filelist = os.listdir(path) \n for filename in filelist: \n filepath = os.path.join(path, filename) \n if os.path.isdir(filepath): \n filenum += dir_size_calculation(filepath) \n else: \n if os.path.exists(filepath):\n filenum += 1\n \n return filenum\n\ndef usage():\n print(\"usage: %s [options]\" % __file__)\n print(\" -p, --program the program to be run\")\n print(\" -i, --input input of the program\")\n print(\" -r, --result dir to save the result\")\n print(\"\")\n print(\"Example: python %s -p ./target_program -i ./inputfile -r resultdir\" % __file__) \n\ndef checkpath(path):\n if not os.path.exists(path):\n try:\n os.makedirs(path)\n except OSError as exc: # Guard against race condition\n raise\n\ndef getopts():\n try:\n usage_opt = [\n \"srcdir\", \"program\", \"inputfile\", \"result\", \"update\",\n ]\n\n opts, args = getopt.getopt(sys.argv[1:], \"s:p:i:r:u\", usage_opt)\n except getopt.GetoptError as err:\n print(str(err))\n usage()\n sys.exit(2)\n filename = None\n inputfile = None\n resultdir = None\n srcdir = None\n update = False\n for opt, arg in opts:\n if opt in (\"-s\", \"--srcdir\"):\n srcdir = arg\n elif opt in (\"-p\", \"--program\"):\n filename = arg\n elif opt in (\"-i\", \"--input\"):\n inputfile = arg\n elif opt in (\"-r\", \"--result\"):\n resultdir = arg\n elif opt in (\"-u\", \"--update\"):\n update = True\n else:\n print(opt)\n assert False, \"unhandled option\" \n\n print(srcdir)\n process_bar = showprocess.ShowProcess(dir_size_calculation(srcdir), 'OK')\n\n if srcdir != None and os.path.exists(srcdir):\n dirlist(srcdir, update, resultdir, process_bar)\n else:\n print(\"[%s] dir does not exist\" %(objdir))\n \n\nif __name__ == '__main__':\n # debug\n # process_bar = showprocess.ShowProcess(dir_size_calculation(\"/home/zzw169/Desktop/VariableTypeClarify/testcases/leetcode/algorithms/cpp\"), 'OK')\n # dirlist(\"/home/zzw169/Desktop/VariableTypeClarify/testcases/leetcode/algorithms/cpp\", True, \"/home/zzw169/Desktop/VariableTypeClarify/results\", process_bar)\n\n if len(sys.argv) <= 1:\n usage()\n else:\n getopts()\n \n # if sys.argv[1] == '--p':\n # for filename in sys.argv[2:]:\n # elf = ElfDwarf(filename)","sub_path":"analyzer/re_analyzer.py","file_name":"re_analyzer.py","file_ext":"py","file_size_in_byte":4783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"410398397","text":"# -*- coding:utf-8 -*-\n\"\"\"小说爬虫配置文件\"\"\"\n\n\nclass BookQzone(object):\n # 小说书名\n BOOK_NAME = u'天上掉下个靖王妃'\n\n # 爬取目标网站的域名\n BOOK_DOMAINS = '3qzone.com'\n\n # 小说目录页面\n BOOK_LIST_URL = 'http://www.3qzone.com/17_17987/'\n\n # 小说目录页面章节超链接XPATH\n BOOK_LIST_XPATH = '//dd/a/@href'\n\n # 小说章节页面URL拼接前缀\n BOOK_DETAIL_URL_PREFIX = 'http://www.3qzone.com/17_17987/'\n\n # 小说详情页面小说章节名XPATH\n BOOK_CHAPTER_TITLE_XPATH = '//div/h1/text()'\n\n # 小说章节详情内容XPATH\n BOOK_CHAPTER_TEXT_XPATH = '//*[@id=\"content\"]/text()'\n","sub_path":"BookSpider/conf/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"162949841","text":"# coding: utf-8\n\nfrom urllib.parse import urlparse\nimport requests\nfrom urllib.request import urlopen\n\nimport csv\nfrom datetime import datetime\nimport json\nimport multiprocessing as mp\nimport os\nimport psycopg2\nfrom psycopg2 import extras as ext\nimport re\nimport requests\nimport sys\nimport time\n\nimport sql_statements\n\nUPDATE_STMT = \"UPDATE expanded_url_map SET resolved_url = %s, domain = %s WHERE expanded_url_0 = %s;\"\n\n\ndatabase_name = \"database_name\"\ndb_config_file = \"database_config.txt\"\n\n\nif not os.path.isdir(\"cache_3\"):\n os.makedirs(\"cache_3\")\n\n#############################\n## URL expansion functions ##\n#############################\n\n## Returns the domain, or None if the URL is invalid\ndef get_domain(url):\n p = urlparse(url)\n if p.netloc:\n return p.netloc.lower()\n\n## Resolves the URL, but returns None if the expanded_url is invalid or couldn't be resolved.\n## The `url_timeout` parameter can be used to specify how many seconds to wait for each URL.\n## If domain_equivalence = True (default False), we'll stop as soon as the URL domain remains constant.\n## Otherwise, keep unwinding until the entire URL is equivalent\n'''\nLogic:\n(0) if it's a twitter.com domain, the URL has already been fully expanded, so return it\n(1) expanded_url = follow_url(short_url)\n(2) if expanded_url is not a valid URL, return short_url\n(3) if expanded_url is a valid URL and but isn't a redirect or expanded_url == short_url\n we assume short_url has already been completely expanded and return short_url\n(4) otherwise set short_url <- expanded_url and repeat from beginning\n\nReturns: (original_url, expanded_url (or None), expanded_domain (or None))\n'''\ndef expand_url(orig_url, short_url, url_timeout=60, steps_remaining=25, domain_equivalence=False):\n print(\"{} -> {}\".format(orig_url, short_url), flush=True) \n short_domain = get_domain(short_url)\n if short_domain == \"twitter.com\":\n return (short_url, short_domain, orig_url)\n\n expanded_url = None\n try:\n response = urlopen(short_url, timeout=url_timeout)\n if response.getcode() == 200:\n expanded_url = response.url\n else:\n print(\"{}: {}\".format(short_url, response.getcode()), flush=True)\n\n except Exception as ex:\n template = \"An exception of type {0} occurred. URL: {1}\"\n message = template.format(type(ex).__name__, short_url)\n print(message, flush=True)\n return (None, None, orig_url)\n\n\n ## We weren't able to expand the URL, so the URL is broken\n if not expanded_url:\n return (None, None, orig_url)\n\n expanded_domain = get_domain(expanded_url)\n\n ## The expanded_url isn't valid\n if not expanded_domain:\n return (None, None, orig_url)\n\n ## Expanding the URL took us to the same place, so it was already completely expanded\n if domain_equivalence:\n if short_domain == expanded_domain:\n return (short_url, short_domain, orig_url)\n else:\n if short_url == expanded_url:\n return (short_url, short_domain, orig_url)\n \n ## Otherwise, following the URL took us to a new URL or domain so start again with the new URL to see if there's more expansion to do\n if steps_remaining > 0:\n return expand_url(orig_url, expanded_url, url_timeout=url_timeout, steps_remaining=(steps_remaining-1), domain_equivalence=domain_equivalence)\n else:\n return (short_url, short_domain, orig_url)\n\n########################\n## Database functions ##\n########################\n\ndef open_connection():\n config = {\"database\": database_name}\n for line in open(db_config_file).readlines():\n key, value = line.strip().split(\"=\")\n config[key] = value\n\n database = psycopg2.connect(**config)\n cursor = database.cursor()\n return database, cursor\n\ndef close_connection(database, cursor):\n cursor.close()\n database.commit()\n database.close()\n\n\n###############################################\n## 1. Load the distinct short urls to expand ##\n###############################################\n\nshort_urls = []\n\n# If there's no cached file, pull them from the database\n# Note: it's important that the URLs remain in the same order, which is why they're also sorted\nif not os.path.isfile(\"cache_3/distinct_urls_\" + database_name + \".json\"):\n database, cursor = open_connection()\n cursor.execute(\"SELECT expanded_url_0 FROM expanded_url_map WHERE domain IS NULL\")\n short_urls = sorted([u[0] for u in cursor.fetchall()])\n close_connection(database, cursor)\n\n with open(\"cache_3/distinct_urls_\" + database_name + \".json\", \"w+\") as f:\n json.dump(short_urls, f)\n\n## Otherwise we have a cached file of URLs already, so we can just use that\nelse:\n with open(\"cache_3/distinct_urls_\" + database_name + \".json\") as f:\n short_urls = json.load(f)\n\nprint(\"{} URLs pulled\".format(len(short_urls)), flush=True)\n\n\n##########################################################################\n## 2. Split the URLs into chunks that can be passed to parallel workers ##\n##########################################################################\n\nchunk_size = 1000 ## how many URLs per chunk - can be adjusted\nurl_chunks = []\n\nindex = 0\nwhile index < len(short_urls):\n chunk_id = index // chunk_size\n chunk = (chunk_id, short_urls[index : (index + chunk_size)])\n url_chunks.append(chunk)\n index = index + chunk_size\n\n\n###################################################################################\n## 3. Start parallel jobs to process each chunk with as many cores as we can get ##\n###################################################################################\n\ndef process_chunk(chunk):\n chunk_id, urls_to_expand = chunk\n print(\"{}/{}\".format(chunk_id, len(url_chunks)), flush=True)\n\n ## Only expand the URLs if we haven't already expanded and cached them\n if not os.path.isfile(\"cache_3/{}.json\".format(chunk_id)):\n print(\"Processing chunk {}\".format(chunk_id), flush=True)\n expanded_urls = [expand_url(short_url, short_url, url_timeout=60, steps_remaining=25) for short_url in urls_to_expand]\n\n ## Cache the chunk so if something goes wrong later we don't have to expand everything again\n with open(\"cache_3/{}.json\".format(chunk_id), \"w+\") as f:\n json.dump(expanded_urls, f)\n\n else:\n print(\"Chunk {} already expanded\".format(chunk_id), flush=True)\n\n\npool = mp.Pool()\n_ = pool.map_async(process_chunk, url_chunks)\npool.close()\npool.join()\n\nprint(\"Finished processing URLs\", flush=True)\n\n\n###############################\n## 4. Compile all URL chunks ##\n###############################\n\n# Make sure we've got them all\nfor chunk_id, _ in url_chunks:\n assert os.path.isfile(\"cache_3/{}.json\".format(chunk_id)), \"No file exists for chunk {}\".format(chunk_id)\n\n## Compile all URL chunks into one big file\ncompiled_urls = []\nfor chunk_id, _ in url_chunks:\n fname = \"cache_3/{}.json\".format(chunk_id)\n print(fname, flush=True)\n with open(fname) as f:\n chunk_urls = json.load(f)\n compiled_urls.extend(chunk_urls)\ncompiled_urls = [c for c in compiled_urls if c[1]] # No need to update if resolving the URL wasn't successful\nprint(\"Finished compiling {} URLs\".format(len(compiled_urls)), flush=True)\n\n\n###############################\n## 5. Load into the database ##\n###############################\ndatabase, cursor = open_connection()\next.execute_batch(cursor, UPDATE_STMT, compiled_urls)\nclose_connection(database, cursor)\n\nprint(\"Updated database\", flush=True)\n\n##############\n## 6. Done! ##\n##############\n\nprint(\"Done!\")\n\n","sub_path":"url_unwinder_3.py","file_name":"url_unwinder_3.py","file_ext":"py","file_size_in_byte":7595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"640127053","text":"#!/usr/bin/python3\n#The string counts is converted to a list using the split and , delimiter\n#Then it is iterated upon using the for loop to print out a specified format\n\n\ncounts = '8,3,6,2,12,5'\n\nlist = counts.split(\",\")\n\nfor i in list:\n sum = 48/int(i)\n print(\"48/{0} = {1}\".format(i,sum))\n\n\n\n","sub_path":"Classwork/Pratical Computationl Conceps in Bioinformatics/week09/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"305416301","text":"#import libaries create plot\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom netCDF4 import Dataset\nfrom matplotlib import cm\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\n\nw_file = '/Users/brownscholar/Desktop/AMNH2021Internship/ocean-motion-2021/dates/2-25/test/ss1a2ww.gr' # open file (fortan code)\n\nw = open(w_file, \"r\")\n\n#open netcdf file\n\noriginal_data = Dataset(\"/Users/brownscholar/Desktop/AMNH2021Internship/ocean-motion-2021/intern-data-t0.nc\")\n\n#get latitude and longitude from netcdf file:\n# here:\nlat = original_data.variables['latitude']\nlon = original_data.variables['longitude']\n\n#print(lat.shape) #158\n#print(lon.shape) #122\n\nnum_lat = 158\nnum_lon = 122\nlevels = 1\n\n# make empty numpy array of shape lat, lon depth shape for storing w:\n\nw_values = np.zeros((levels,num_lat,num_lon)) # fills the array with zeros, import data in to a structured arrary (multidemisional geography )\n\n# use a loop to read w_file into the variable\n#(skip first two lines of the file)\nw.readline() #reads the line of code and by putting two you skip the first two it lets you only read the numbers in the loop\nw.readline()\nfor i in range(0,levels): # range 0 to 1\n for j in range(0, num_lat): # ranges 0 to 158\n for k in range(0, num_lon): # range 0 to 122\n w_values[i,j,k] = w.readline() # reads in the numbers in the empty array\n\n\n#this stuff defines the colorspace (we can google colormaps to learn more if we want to)\ntop = cm.get_cmap('Blues_r', 128)\nbottom = cm.get_cmap('Reds', 128)\n\nnewcolors = np.vstack((top(np.linspace(0, 1, 128)),\n bottom(np.linspace(0, 1, 128))))\nnewcmp = ListedColormap(newcolors, name='RedBlue')\n\n\n#now use the following function to plot your data:\n#function to make colorplot is:\n# p = plt.pcolormesh(V,cmap = newcmp), where V is the numpy array with the data\np = plt.pcolormesh(w_values[0,2:-2,2:-2],cmap = newcmp)\n\nplt.xlabel(\"Longitude\")# labels x axis\nplt.ylabel(\"Latitude\")# labels the y axis\nplt.title(\"ColorMap\")# labels the entire map\nplt.scatter([],[], color = \"blue\", label = \"going down\")#lables legend\nplt.scatter([],[], color = \"red\", label = \"going up\")#lables legend\nplt.legend(bbox_to_anchor=[1.0,1.0])# create legend\nplt.xticks(np.arange(0,num_lon,10),lon[::10])\nplt.yticks(np.arange(0,num_lat,10),lat[::10])\nplt.show()\n\n# you can use these to add the x and y ticks to your plot:\n# I am happy to talk to you about why this works\n","sub_path":"dates/2-25/color_plot.py","file_name":"color_plot.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"40281596","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 19 12:27:09 2020\r\n\r\n@author: Xp\r\n\"\"\"\r\n\r\n\r\nnombre=input(\"Ingresa tu nombre:\")\r\napellido=input(\"Ingresa tu apellido:\")\r\nlocalidad=input(\"Ingresa tu localidad:\")\r\nedad=input(\"Ingresa tu edad:\")\r\nedad=int(edad)\r\nif edad>=1 and edad<=12:\r\n print(\"es niño\")\r\nelif edad>=12 and edad <=18:\r\n print(\"es adolecente\")\r\nelif edad>=18 and edad<=30:\r\n print(\"es adulto\")\r\nelse:\r\n print(\"es adulto mayor\")\r\nspace=\" \"\r\nprint(\"YO SOY \" , space , nombre , space , apellido , space , \"VIVO EN\" , space , localidad , space , \"Y TENGO\", space , edad , space , \"AÑOS\" )\r\n","sub_path":"TAREA 1.py","file_name":"TAREA 1.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"334033738","text":"\"\"\"This script is dedicated to test the 3aransia transliteration function\"\"\"\n\nimport unittest\nimport logging\n\nfrom aaransia.transliteration import transliterate\nfrom aaransia.exceptions import SourceLanguageError\nfrom aaransia.text_samples import TEXT_SAMPLES\nfrom aaransia.defaults import (\n BASE_DIR, LOG_DIR, TEST_LOGGER_NAME, TEST_TRANSLITERATION_LOG_FILE, ALPHABETS,\n LEN_LANGUAGES\n)\n\n# Logging config\nlogging.root.setLevel(logging.INFO)\nFORMATTER = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n# Loggers\nTEST_LOGGER = logging.getLogger(TEST_LOGGER_NAME)\n\nclass TestTransliteration(unittest.TestCase):\n \"\"\"This class is meant for test purposes\"\"\"\n\n def test_transliteration(self):\n \"\"\"This script is dedicated to test the moroccan alphabet transliteration\n\n @self -- the instance of the testing class\"\"\"\n test_logget_file_handler = logging.FileHandler(BASE_DIR + LOG_DIR +\n TEST_TRANSLITERATION_LOG_FILE, 'w')\n test_logget_file_handler.setFormatter(FORMATTER)\n test_logget_file_handler.setLevel(logging.INFO)\n TEST_LOGGER.addHandler(test_logget_file_handler)\n\n for text_sample in TEXT_SAMPLES:\n count_infos, count_errors = 0, 0\n for word in text_sample['text'].split():\n try:\n for target_language in list(ALPHABETS):\n transliteration = transliterate(word,\n text_sample['language'],\n target_language)\n count_infos += 1\n except SourceLanguageError as source_language_error:\n TEST_LOGGER.error(f'{text_sample[\"language\"].capitalize()} - '\n f'Transliteration of {word}, '\n f'{source_language_error}')\n count_errors += 1\n\n info_percentage = round(count_infos/len(text_sample['text'].split())*100/LEN_LANGUAGES, 2)\n error_percentage = round(count_errors/len(text_sample['text'].split())*100, 2)\n\n TEST_LOGGER.info(f'{text_sample[\"language\"].capitalize()} - '\n f'Total INFO logs {count_infos/LEN_LANGUAGES} '\n f'({info_percentage}%), \\n\\t'\n f'Total ERROR logs {count_errors} '\n f'({error_percentage}%)')\n\ndef run_tests():\n \"\"\"This function is meant to run all the tests\"\"\"\n unittest.main()\n","sub_path":"aaransia/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"360015421","text":"from tensorboard.backend.event_processing.event_accumulator import EventAccumulator\nimport os\nimport argparse\nimport pdb\nimport glob\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom utils import SignReader\n# signnames = SignReader(\"victim_0/signnames.csv\")\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except:\n \tpass\n\n# def plot_imagenet(\n# \texpt_dir = None,\n# \t):\n# \tlogging_dir = 'adversarial_objects/output/{}/'.format(expt_dir)\n# \tevent_paths = glob.glob(os.path.join(logging_dir, \"*\", \"tensorboard\"))\n# \ttf.logging.set_verbosity(tf.logging.ERROR)\n# \tfor metric in ['surface_area','fna_ad','edge_length','edge_variance', 'attack_accuracy']:\n# \t\tfor path in event_paths:\n# \t\t\tevent_acc = EventAccumulator(path)\n# \t\t\tevent_acc.Reload()\n# \t\t\ttry:\n# \t\t\t\tprint(metric, event_acc.Scalars('{}'.format(metric))[-1].value, event_acc.Scalars('{}'.format(metric))[-1].step, path.split('/')[-2], sep = ', ')\n# \t\t\texcept:\n# \t\t\t\tprint(\"Didnt find\")\n\n\n# plot_imagenet(\n# \texpt_dir = 'regularization_experiments_adv_tex_2',\n# )\n\n\n\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n\ndef plot(\n\texpt_dir = None,\n\tmetric = None,\n\texpt_list = None,\n\texpt_list_x_label = None,\n\twildcards = [''],\n\tlegend_labels = ['Pass some label for each wildcard'],\n\txlabel = 'Pass some label pls',\n\tylabel = 'Pass some label pls',\n\ttitle = \"Somethign please\",\n\tplotname = 'default.png',\n\tdpi = 500,\n\tmatcher = 1,\n\t):\n\tlogging_dir = 'adversarial_objects/output/course_expts/{}/'.format(expt_dir)\n\tmetric_dict = {}\n\tseeds = [42, 53345, 1337, 80085, 8008]\n\tplt.figure()\n\tfor widx, wildcard in enumerate(wildcards):\n\t\tx = []\n\t\ty = []\n\t\tyerr = []\n\t\tfor jidx, j in enumerate(expt_list):\n\t\t\tif matcher == 1:\n\t\t\t\tevent_paths = glob.glob(os.path.join(logging_dir, \"*{}\".format(wildcard), \"tensorboard_*_{}\".format(j)))\n\t\t\telif matcher == 2:\n\t\t\t\tevent_paths = glob.glob(os.path.join(logging_dir, \"*{}\".format(wildcard), \"tensorboard_{}*\".format(j)))\n\t\t\telif matcher == 3:\n\t\t\t\tevent_paths = glob.glob(os.path.join(logging_dir, \"{}\".format(j), \"tensorboard_{}*\".format(j)))\n\t\t\t# pdb.set_trace()\t\n\t\t\tif isinstance(j,int) and j==14:\n\t\t\t\tcontinue\n\t\t\tmetric_dict[j] = []\n\t\t\tfor path in event_paths:\n\t\t\t\tprint(path)\n\t\t\t\tevent_acc = EventAccumulator(path)\n\t\t\t\tevent_acc.Reload()\n\t\t\t\ttry:\n\t\t\t\t\tmetric_dict[j].append((event_acc.Scalars('{}'.format(metric))[0].value))\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"Didnt find\")\n\t\t\tif j > 9 and j!=16:\n\t\t\t\tx.append(jidx)\n\t\t\t\ty.append(np.mean(metric_dict[j]))\n\t\t\t\tyerr.append(np.std(metric_dict[j]))\n\t\t\telse:\n\t\t\t\tcolors = ['-','--','-.',':']\n\t\t\t\tcolors2 = ['r','g','m','c']\n\t\t\t\tplt.axhline(y=np.mean(metric_dict[j]), label = \"{}\".format(expt_list_x_label[jidx]), linewidth = 1, color = colors2[jidx-6], linestyle=colors[jidx-6])\n\t\tif legend_labels is not None:\n\t\t\tplt.errorbar(x, y, yerr=yerr, fmt = 'o', label=legend_labels[widx])\n\t\telse:\n\t\t\tplt.errorbar(x, y, yerr=yerr, fmt = 'o')\n\tplt.xticks(x, expt_list_x_label)\n\tplt.xlabel(xlabel)\n\tplt.ylabel(ylabel)\n\t# plt.grid()\n\t# plt.yscale(\"log\")\n\tplt.title(title)\n\t# if legend_labels is not None:\n\tplt.legend(loc=2) # 'upper left')\n\tmkdir_p('adversarial_objects/plots/{}'.format(expt_dir))\n\tplt.savefig('adversarial_objects/plots/{}/{}'.format(expt_dir,plotname),dpi=dpi)\n\ndef plot_lines(\n\texpt_dir = None,\n\tmetric = None,\n\texpt_list = None,\n\texpt_list_x_label = None,\n\twildcards = [''],\n\tlegend_labels = ['Pass some label for each wildcard'],\n\txlabel = 'Pass some label pls',\n\tylabel = 'Pass some label pls',\n\ttitle = \"Somethign please\",\n\tplotname = 'default.png',\n\tdpi = 500,\n\tmatcher = 1,\n\t):\n\tlogging_dir = 'adversarial_objects/output/{}/'.format(expt_dir)\n\tseeds = [42, 53345, 1337, 80085, 8008]\n\tplt.figure()\n\tfor widx, wildcard in enumerate(wildcards):\n\t\tx = []\n\t\ty = []\n\t\tyerr = []\n\n\t\tfor jidx, j in enumerate(expt_list):\n\t\t\tif matcher == 1:\n\t\t\t\tevent_paths = glob.glob(os.path.join(logging_dir, \"*{}\".format(wildcard), \"tensorboard_*_{}\".format(j)))\n\t\t\telif matcher == 2:\n\t\t\t\tevent_paths = glob.glob(os.path.join(logging_dir, \"*{}\".format(wildcard), \"tensorboard_{}*\".format(j)))\n\t\t\telif matcher == 3:\n\t\t\t\tevent_paths = glob.glob(os.path.join(logging_dir, \"{}\".format(j), \"tensorboard_{}*\".format(j)))\n\t\t\t# pdb.set_trace()\n\t\t\tif isinstance(j,int) and j==14:\n\t\t\t\tcontinue\n\n\t\t\tmetric_dict = np.zeros((len(event_paths),500))\n\t\t\tfor pidx, path in enumerate(event_paths):\n\t\t\t\tprint(path)\n\t\t\t\tevent_acc = EventAccumulator(path)\n\t\t\t\tevent_acc.Reload()\n\t\t\t\t# pdb.set_trace()\n\t\t\t\ttry:\n\t\t\t\t\tx = [i.step for i in (event_acc.Scalars('{}'.format(metric)))]\n\t\t\t\t\tytmp = [i.value for i in (event_acc.Scalars('{}'.format(metric)))]\n\t\t\t\t\tmetric_dict[pidx,:] = np.array(ytmp)\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"Didnt find\")\n\t\t\ty = np.mean(metric_dict,axis=0)\n\t\t\tyerr = np.std(metric_dict,axis=0)\n\t\t\t# pdb.set_trace()\n\t\t\tskip=1\n\t\t\tif matcher==3:\n\t\t\t\tx = x[-500:]\n\t\t\tif legend_labels is not None:\n\t\t\t\tplt.plot(x, y, label=legend_labels[jidx])\n\t\t\telse:\n\t\t\t\tplt.plot(x, y)\n\tif expt_list_x_label is not None:\n\t\tplt.xticks(x, expt_list_x_label)\n\tplt.xlabel(xlabel)\n\tplt.ylabel(ylabel)\n\tplt.grid()\n\t# plt.yscale(\"log\")\n\tplt.title(title)\n\tif legend_labels is not None:\n\t\tplt.legend()\n\tmkdir_p('adversarial_objects/plots/{}'.format(expt_dir))\n\tplt.savefig('adversarial_objects/plots/{}/{}'.format(expt_dir,plotname),dpi=dpi)\n\n\nseeds = [42, 53345, 1337, 80085, 8008]\nexpt_list = [2,3,4,5,6,7,8]\nexpt_list = [i for i in range(42)]\n\n\n\nmatplotlib.rcParams.update({'font.size': 8})\nmetrics = ['nps','fna_ad','edge_length','edge_variance','surface_area','stop_sign_probability']\nylabels = ['NPS','Surface Normal Deviation', 'Mean Edge Length','Variance of Edge Length', 'Total Surface Area', 'P(Stop Sign)']\n\t\t\n\n\n# What to plot\nplot_regularization = False\nplot_nobj = False\nplot_shapes = False\nplot_tex = False\nplot_training_range = True\n\nif False:\n\tplot(\n\t\texpt_dir = 'varying_targets',\n\t\tmetric = 'targeted_attack',\n\t\texpt_list = [i for i in range(42)],\n\t\texpt_list_x_label = [i for i in range(42)],\n\t\twildcards = ['fna_ad_edge_length','fna_ad_edge_length_nps'],\n\t\tlegend_labels = ['No NPS regularization','NPS regularization'],\n\t\txlabel = 'Target Class IDs',\n\t\tylabel = 'Targeted Attack Success Rate',\n\t\ttitle = \"Targeted Attack\",\n\t\tplotname = 'targeted.png',\n\t\tdpi = 500,\n\t)\n\t\nif plot_training_range:\n\ttraining_range_expt_list = [10,20,30,45,50,60,0,3,6,16]\n\ttraining_range_expt_labels = ['10','20','30','40','50','60','1 fixed angle','3 fixed angles','5 fixed angles','15 fixed angles']\n\tfor expt_dir in ['varying_training_range']:\n\t\ttitles = ['Attack Success Rate' for i in range(len(ylabels))]\n\t\t# for idx in range(len(metrics)):\n\t\t# \tplot_lines(\n\t\t# \t\texpt_dir = expt_dir,\n\t\t# \t\tmetric = metrics[idx],\n\t\t# \t\texpt_list = training_range_expt_list,\n\t\t# \t\texpt_list_x_label = None,\n\t\t# \t\twildcards = [''],\n\t\t# \t\tlegend_labels = training_range_expt_labels,\n\t\t# \t\txlabel = 'Iterations',\n\t\t# \t\tylabel = ylabels[idx],\n\t\t# \t\ttitle = titles[idx],\n\t\t# \t\tplotname = '{}.png'.format(metrics[idx]),\n\t\t# \t\tdpi = 500,\n\t\t# \t)\n\t\tplot(\n\t\t\texpt_dir = expt_dir,\n\t\t\tmetric = 'attack_accuracy',\n\t\t\texpt_list = training_range_expt_list,\n\t\t\texpt_list_x_label = training_range_expt_labels,\n\t\t\twildcards = ['*'],\n\t\t\tlegend_labels = None,\n\t\t\txlabel = 'Training Range',\n\t\t\tylabel = 'Attack Success Rate',\n\t\t\ttitle = \"Effect of varying training range\",\n\t\t\tplotname = 'training_range_attack_acc.png',\n\t\t\tdpi = 500,\n\t\t)\n\nif plot_regularization:\n\treg_expt_list = ['no_regularization', 'surface_area','aabb_volume','radius_volume','edge_length', \"fna_ad\", \"fna_ad_edge_length_nps\", \"fna_ad_edge_length\", \"fna_ad_edge_length_surface_area\"]\n\treg_expt_labels = ['No \\n Regular-\\nization','Surface\\nArea \\n (SA)','AABB\\nVolume \\n(AV)',\n\t'Radius\\nVolume\\n(RV)','Edge\\nLength\\n(EL)', \"Surface Normal\\n (SN)\",\n\t\"SN\\nEL\\nNPS\",\"SN\\nEL\",\"SN\\nEL\\nSA\"]\n\texpt_dir = 'varying_regularization_largest_w'\n\ttitles = ['Effect of Varying Regularization' for i in range(len(ylabels))]\n\tfor idx in range(len(metrics)):\n\t\tplot_lines(\n\t\t\texpt_dir = expt_dir,\n\t\t\tmetric = metrics[idx],\n\t\t\texpt_list = reg_expt_list,\n\t\t\texpt_list_x_label = None,\n\t\t\twildcards = [''],\n\t\t\tlegend_labels = reg_expt_labels,\n\t\t\txlabel = 'Iterations',\n\t\t\tylabel = ylabels[idx],\n\t\t\ttitle = titles[idx],\n\t\t\tplotname = '{}.png'.format(metrics[idx]),\n\t\t\tdpi = 500,\n\t\t\tmatcher=3,\n\t\t)\n\n\tplot(\n\t\texpt_dir = expt_dir,\n\t\tmetric = 'attack_accuracy',\n\t\texpt_list = reg_expt_list,\n\t\texpt_list_x_label = reg_expt_labels,\n\t\twildcards = [''],\n\t\tlegend_labels = None,\n\t\txlabel = '',\n\t\tylabel = titles[0],\n\t\ttitle = \"Attack Success Rate for Varying Regularization\",\n\t\tplotname = 'attack_accuracy.png',\n\t\tdpi = 500,\n\t\tmatcher=3,\n\t)\n\nif plot_tex:\n\ttex_expt_list = [2,3,4,5,6,7,8]\n\ttex_expt_labels = [2,3,4,5,6,7,8]\n\tfor expt_dir in ['varying_tex','varying_rand_tex']:\n\t\ttitles = ['Effect of Number of Textures on Face' for i in range(len(ylabels))]\n\t\tfor idx in range(len(metrics)):\n\t\t\tplot_lines(\n\t\t\t\texpt_dir = expt_dir,\n\t\t\t\tmetric = metrics[idx],\n\t\t\t\texpt_list = tex_expt_list,\n\t\t\t\texpt_list_x_label = None,\n\t\t\t\twildcards = [''],\n\t\t\t\tlegend_labels = tex_expt_labels,\n\t\t\t\txlabel = 'Iterations',\n\t\t\t\tylabel = ylabels[idx],\n\t\t\t\ttitle = titles[idx],\n\t\t\t\tplotname = '{}.png'.format(metrics[idx]),\n\t\t\t\tdpi = 500,\n\t\t\t)\n\t\tplot(\n\t\t\texpt_dir = expt_dir,\n\t\t\tmetric = 'attack_accuracy',\n\t\t\texpt_list = tex_expt_list,\n\t\t\texpt_list_x_label = tex_expt_labels,\n\t\t\twildcards = ['*'],\n\t\t\tlegend_labels = None,\n\t\t\txlabel = 'Objects',\n\t\t\tylabel = titles[0],\n\t\t\ttitle = titles[0],\n\t\t\tplotname = 'tex_attack_acc.png',\n\t\t\tdpi = 500,\n\t\t)\n\nif plot_shapes:\n\tshapes_expt_list = ['obj3.obj', 'obj2.obj', 'obj4.obj','evil_cube_1.obj']\n\t# shapes_expt_list = [1,2,4,8,16]\n\tshapes_expt_labels = ['Icosphere with\\n42 vertices', 'Icosphere with \\n12 vertices', 'Cylinder', 'Cube']\n\texpt_dir = 'varying_shapes'\n\ttitles = ['Effect of Shapes Used' for i in range(len(ylabels))]\n\tfor idx in range(len(metrics)):\n\t\tplot_lines(\n\t\t\texpt_dir = expt_dir,\n\t\t\tmetric = metrics[idx],\n\t\t\texpt_list = shapes_expt_list,\n\t\t\texpt_list_x_label = None,\n\t\t\twildcards = [''],\n\t\t\tlegend_labels = shapes_expt_labels,\n\t\t\txlabel = 'Iterations',\n\t\t\tylabel = ylabels[idx],\n\t\t\ttitle = titles[idx],\n\t\t\tplotname = '{}.png'.format(metrics[idx]),\n\t\t\tdpi = 500,\n\t\t)\n\tplot(\n\t\texpt_dir = expt_dir,\n\t\tmetric = 'attack_accuracy',\n\t\texpt_list = shapes_expt_list,\n\t\texpt_list_x_label = shapes_expt_labels,\n\t\twildcards = ['*'],\n\t\tlegend_labels = None,\n\t\txlabel = 'Objects',\n\t\tylabel = 'Attack Success Rate',\n\t\ttitle = titles[0],\n\t\tplotname = 'shapes_attack_acc.png',\n\t\tdpi = 500,\n\t)\n\nif plot_nobj:\n\tnobj_expt_list = [1,2,4,8,16]\n\tnobj_expt_labels = ['1','2','4','8','16']\n\texpt_dir = 'varying_nobj'\n\ttitles = ['Effect of Number of Objects Used' for i in range(len(ylabels))]\n\tfor idx in range(len(metrics)):\n\t\tplot_lines(\n\t\t\texpt_dir = expt_dir,\n\t\t\tmetric = metrics[idx],\n\t\t\texpt_list = nobj_expt_list,\n\t\t\texpt_list_x_label = None,\n\t\t\twildcards = [''],\n\t\t\tlegend_labels = nobj_expt_labels,\n\t\t\txlabel = 'Iterations',\n\t\t\tylabel = ylabels[idx],\n\t\t\ttitle = titles[idx],\n\t\t\tplotname = '{}.png'.format(metrics[idx]),\n\t\t\tdpi = 500,\n\t\t)\n\tplot(\n\t\texpt_dir = expt_dir,\n\t\tmetric = 'attack_accuracy',\n\t\texpt_list = [1,2,4,8,16],\n\t\texpt_list_x_label = [1,2,4,8,16],\n\t\twildcards = ['*'],\n\t\tlegend_labels = None,\n\t\txlabel = 'Number of objects',\n\t\tylabel = 'Attack Success Rate',\n\t\ttitle = titles[0],\n\t\tplotname = 'nobj_attack_acc.png',\n\t\tdpi = 500,\n\t)\n\n\n\n\n\n\n","sub_path":"adversarial_objects/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":11334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"606938042","text":"\n\"\"\"\n\n爬去分期乐的商品的详情和评论,保存在 mongodb 中\n\n\"\"\"\nimport json\n\nimport requests\n\nfrom .utils.functions import etree_xpath\nfrom .utils.mongo_conn import COLLECTION # mongodb的数据集\n\n\ndef get_good_page_url(url, category_id):\n \"\"\"\n 获取详情每个商品的详情页面的 url\n\n :param url: 发送 post 请求的 url\n :return: 所有详情页面的 url \"https://item.fenqile.com/S201709120586965.html\"\n \"\"\"\n # 所有的大类型:如:66-手机 327-腕表配饰 65-电脑办公 67-相机单反 217-平板数码 179-运动户外 255-家电家居\n # category_id_1_list = [66, 327, 65, 67, 217, 179]\n # for category_id_1 in category_id_1_list:\n\n # post 请求的表单数据\n url_list = []\n page = 0\n flag = True\n while flag:\n try:\n page += 1\n data = {\n 'category_id_1': category_id, # 来自 category_id_1_list\n 'category_id_2': 0, # 手机系统类型 id 0-全部 如: ios-99 Android-597\n 'category_id_3': 0, # 暂时无用\n 'feature_id_1': 0, # 暂时无用\n 'feature_id_2': 0, # 暂时无用\n 'feature_id_3': 0, # 暂时无用\n 'brand_id': 0, # 0-全部 品牌 id 如:小米-12\n 'amount': 0, # 暂时无用\n 'undefined': 0, # 暂时无用\n 'page': page, # 页码, 最后会有一个 total_page\n }\n\n # 解析 url 获取数据\n res = requests.post(url, data)\n json_data = json.loads(res.content.decode(\"utf-8\"))\n html = json_data.get('html')\n url_xpath = '//ul[@class=\"list-li fn-clear js-noraml-li\"]/li/@data-url'\n # 获取每一页的 url 列表\n page_url_list = etree_xpath(html, url_xpath)\n url_list += [\"https:\" + url for url in page_url_list]\n except:\n print(\"获取详情每个商品的详情页面的 url 错误:\", page, url)\n print()\n continue\n # 达到最后一页,停止循环\n if page == json_data.get(\"total_page\"):\n flag = False\n return url_list\n\n\ndef get_goods_details(good_id):\n \"\"\"\n 获取商品的详情\n\n get_details_insert_db 函数内调用\n :param good_id: str 商品的编号\n :return: 商品的所有信息\n \"\"\"\n base_url = \"https://item.fenqile.com/item/query_sku_info.json?sku_id={good_id}&province_id=19&city_id=1601&area_id=36953&direct_send=1&product_type=normal&index_flag=1\"\n url = base_url.format(good_id=good_id)\n res = requests.get(url)\n if int(res.status_code) == 200:\n good_data = json.loads(res.content.decode(\"utf-8\")).get(\"sku\")\n return good_data\n\n\ndef get_comments(product_id):\n \"\"\"\n 获取商品的评论\n\n :param product_id: int 商品的id\n :return: 商品的所有评论列表\n \"\"\"\n comment_list = []\n comment_url = \"https://item.fenqile.com/item/query_product_comment.json?product_id={product_id}&page={page}\"\n page = 0\n flag = True\n while flag:\n page += 1\n url = comment_url.format(product_id=product_id, page=page)\n res = requests.get(url)\n data = json.loads(res.content.decode(\"utf-8\"))\n comments = data.get(\"comment_list\")\n total_page = data.get(\"total_page\")\n comment_list += comments\n if page == int(total_page):\n flag = False\n return comment_list\n\n\ndef get_details_insert_db(detail_urls, category_id):\n \"\"\"\n 获取商品的详情 插入数据库\n\n :param detail_urls: list 商品详情页面的 url 列表\n :return:\n \"\"\"\n for url in detail_urls:\n try:\n goods = {}\n # 商品的 id\n good_id = url.split('/')[-1].split(\".\")[0]\n goods[\"good_id\"] = good_id\n goods[\"category_id\"] = category_id\n res = requests.get(url)\n html = res.content.decode(\"utf-8\")\n # 展示商品的轮播图\n slider_xpath = '//ul[@class=\"fn-clear\"]//img/@src'\n slider_imgs = etree_xpath(html, slider_xpath)\n goods[\"slider_imgs\"] = slider_imgs\n # 详情图片 大图\n detail_img_xpath = '//div[@class=\"product-msg\"]//img/@data-original'\n detail_imgs = etree_xpath(html, detail_img_xpath)\n goods[\"detail_imgs\"] = detail_imgs\n # 获取商品的详情数据\n detail_data = get_goods_details(good_id)\n goods[\"detail_data\"] = detail_data\n # 品牌 id\n brand_id = detail_data.get(\"brand_id\")\n goods[\"brand_id\"] = brand_id\n # product_id\n product_id = detail_data.get(\"product_id\")\n comments = get_comments(product_id)\n goods[\"comments\"] = comments\n # 将图片插入数据库 mongodb\n COLLECTION.update({\"good_id\": good_id}, {\"$set\": goods}, upsert=True)\n except:\n print(\"获取商品的详情 插入数据库 出错了:\", url)\n print()\n continue\n\n\ndef main():\n # 获取数据的 url 发送 post 请求\n post_url = 'https://channel.fenqile.com/product/get_more.json'\n # 商品种类 如:66-手机 327-腕表配饰 65-电脑办公 67-相机单反 217-平板数码 179-运动户外 255-家电家居\n category_id_list = [66, 327, 65, 67, 217, 179, 255]\n for category_id in category_id_list:\n try:\n # category_id = 66\n # 获取单个种类的详情页面的 url\n detail_urls = get_good_page_url(post_url, category_id)\n # detail_urls = [\"https://item.fenqile.com/S201709120586965.html\"] # 测试用\n # 获取商品的的详情并插入数据库\n get_details_insert_db(detail_urls, category_id)\n except:\n print(\"出错了:category_id:\", category_id)\n print()\n continue\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"fenqile_spider/fenqile.py","file_name":"fenqile.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"146117700","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^register/$', views.UserRegisterView.as_view(), name=\"register\"),\n url(r'^login/$', views.UserLoginView.as_view(), name=\"login\"),\n url(r'^logout/$', views.logout, name=\"logout\"),\n # url(r'^profile/$', views.UserProfile.as_view(), name=\"profile\"),\n # url(r'^profile_update/$', views.UserProfileUpdate.as_view(), name=\"profile_update\"),\n # url(r'^password_change/$', views.UserPasswordChange.as_view(), name=\"password_change\"),\n]","sub_path":"src/apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"612845789","text":"import numpy as np\r\nfrom math import floor, ceil\r\nimport time\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib.ticker import MultipleLocator\r\nfrom collections import defaultdict\r\n\r\n\r\nclass RRT:\r\n def __init__(self, filename, start_state=None, goal_state=None):\r\n self.maze_array = self.from_pgm(filename)\r\n self.cols, self.rows = self.maze_array.shape\r\n if start_state is None:\r\n self.start_state = (0, 0)\r\n if goal_state is None:\r\n self.goal_state = (self.cols - 1, self.rows - 1)\r\n self.start_node_tree = [self.start_state]\r\n self.goal_node_tree = [self.goal_state]\r\n self.map_size = self.rows * self.cols\r\n self.parent = defaultdict(lambda: defaultdict(lambda: None))\r\n self.start_tree = [self.start_state]\r\n self.path_length=0\r\n\r\n def from_pgm(self, filename):\r\n with open(filename, 'r', encoding='latin1') as infile:\r\n # Get header information and move file pointer past header\r\n header = infile.readline()\r\n width, height, _ = [int(item) for item in header.split()[1:]]\r\n # Read the rest of the image into a numpy array and normalize\r\n image = np.fromfile(infile, dtype=np.uint8).reshape((height, width)) / 255\r\n return image.T\r\n\r\n def compute_distance(self, start, goal):\r\n \"\"\"compute euclidean distance given start and goal state\"\"\"\r\n return np.sqrt(np.power(goal[0] - start[0], 2) + np.power(goal[1] - start[1], 2))\r\n\r\n def find_nearest_node_on_tree(self, tree, sampled_node):\r\n distance_nodes = np.array([self.compute_distance(node, sampled_node) for node in tree])\r\n return tree[np.argmin(distance_nodes)]\r\n\r\n def check_collision(self, maze_array, node):\r\n floor_node_x,floor_node_y=int(floor(node[0])),int(floor(node[1]))\r\n ceil_node_x, ceil_node_y = int(ceil(node[0])), int(ceil(node[1]))\r\n if ceil_node_x==self.cols:\r\n ceil_node_x -=1\r\n if ceil_node_y==self.rows:\r\n ceil_node_y -=1\r\n if maze_array[floor_node_x, floor_node_y] == 0 \\\r\n or maze_array[ceil_node_x, ceil_node_y] == 0 \\\r\n or maze_array[floor_node_x, ceil_node_y] == 0 \\\r\n or maze_array[ceil_node_x, floor_node_y] == 0:\r\n return True\r\n else:\r\n return False\r\n\r\n def find_delta_node(self, near_node, sampled_node, delta):\r\n delta_node_x = delta * (sampled_node[0] - near_node[0]) / self.compute_distance(near_node, sampled_node)\r\n delta_node_y = delta * (sampled_node[1] - near_node[1]) / self.compute_distance(near_node, sampled_node)\r\n new_node = (near_node[0] + delta_node_x, near_node[1] + delta_node_y)\r\n return new_node\r\n\r\n def check_proximity_goal(self, node, goal, threshold=1.0):\r\n if self.compute_distance(node, goal) <= threshold:\r\n return True\r\n else:\r\n return False\r\n\r\n def get_random_sample(self, goal_sample_prob):\r\n if np.random.random() > goal_sample_prob:\r\n # rand_node = (np.random.random() * (self.cols - 1), np.random.random() * (self.rows - 1))\r\n rand_node = (np.random.uniform(0, self.cols - 1), np.random.uniform(0, self.rows - 1))\r\n else:\r\n rand_node = self.goal_state\r\n return rand_node\r\n\r\n def compute_path(self, start, goal):\r\n path = [goal]\r\n while goal != start:\r\n goal = self.parent[goal[0]][goal[1]]\r\n path.append(goal)\r\n return path\r\n\r\n def compute_RRT(self, delta, goal_sample_prob,show_graph=False):\r\n # Perform random sampling with some goal sampling rate to get a random node\r\n while True:\r\n rand_node = self.get_random_sample(goal_sample_prob)\r\n\r\n # Find nearest node to sampled node on start tree\r\n near_node = self.find_nearest_node_on_tree(self.start_tree, rand_node)\r\n\r\n # Find delta node in the direction towards sampled random node\r\n delta_node = self.find_delta_node(near_node, rand_node, delta)\r\n\r\n if self.check_collision(self.maze_array, delta_node):\r\n continue\r\n\r\n self.start_tree.append(delta_node)\r\n self.parent[delta_node[0]][delta_node[1]] = near_node\r\n if show_graph==True:\r\n self.plot_path('Tree', [], 'Maze_RRT')\r\n\r\n if self.check_proximity_goal(delta_node, self.goal_state, delta):\r\n self.parent[self.goal_state[0]][self.goal_state[1]] = delta_node\r\n self.plot_path('Path', self.compute_path(self.start_state, self.goal_state), 'Maze_RRT')\r\n print(\"goal found\")\r\n break\r\n\r\n def plot_path(self, graph_mode, path, title_name=None):\r\n \"\"\"\r\n Plots the provided path on the maze\r\n \"\"\"\r\n\r\n fig = plt.figure(1)\r\n ax1 = fig.add_subplot(1, 1, 1)\r\n\r\n spacing = 1.0 # Spacing between grid lines\r\n minor_location = MultipleLocator(spacing)\r\n\r\n # Set minor tick locations.\r\n ax1.yaxis.set_minor_locator(minor_location)\r\n ax1.xaxis.set_minor_locator(minor_location)\r\n\r\n # Set grid to use minor tick locations.\r\n ax1.grid(which='minor')\r\n\r\n colors = ['b', 'r', 'g']\r\n plt.imshow(self.maze_array.T, cmap=plt.get_cmap('bone'))\r\n if title_name is not None:\r\n fig.suptitle(title_name, fontSize=20)\r\n if graph_mode == 'Path':\r\n path = np.array(path)\r\n for i in range(len(path) - 1):\r\n cidx = i % 3\r\n plt.plot([path[i, 0], path[i + 1, 0]], [path[i, 1], path[i + 1, 1]], \\\r\n color=colors[cidx], linewidth=2)\r\n self.path_length += self.compute_distance((path[i,0],path[i,1]),(path[i+1,0],path[i+1,1]))\r\n elif graph_mode == 'Tree':\r\n tree = np.array(self.start_tree)\r\n for i, node in enumerate(tree):\r\n cidx = i % 2\r\n parent = self.parent[node[0]][node[1]]\r\n if parent is not None:\r\n plt.plot([node[0], parent[0]], [node[1], parent[1]], color=colors[cidx], linewidth=2)\r\n plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n print(\"rrt started\")\r\n rrt = RRT('maze2.pgm')\r\n delta = 1.0\r\n goal_sample_rate = 0.20\r\n past_time=time.time()\r\n rrt.compute_RRT(delta, goal_sample_rate,show_graph=False)\r\n compute_time=time.time()-past_time\r\n print(\"Path_length=\",rrt.path_length)\r\n print(\"Compute_time=\",compute_time)","sub_path":"kino_rrt.py","file_name":"kino_rrt.py","file_ext":"py","file_size_in_byte":6587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"453601294","text":"# coding:utf-8\n\nimport math\nimport random\n\ndef closet_pair(p_x, p_y):\n if len(p_x) <= 3:\n return brute(p_x)\n\n mid = len(p_x)//2 # mid must be int\n L_x = p_x[:mid]\n R_x = p_x[mid:]\n\n L_set = set(L_x)\n L_y = []\n R_y = []\n for point in p_y:\n if point in L_set:\n L_y.append(point)\n else:\n R_y.append(point)\n\n (x_l, y_l, d_l) = closet_pair(L_x, L_y)\n (x_r, y_r, d_r) = closet_pair(R_x, R_y)\n\n if d_l <= d_r:\n d_min = d_l\n pair = (x_l, y_l)\n else:\n d_min = d_r\n pair = (x_r, y_r)\n\n # closet pair maybe on the split line\n (x_s, y_s, d_s) = closet_split_pair(p_x, p_y, d_min, pair)\n\n if d_min <= d_s:\n return pair[0], pair[1], d_min\n else:\n return x_s, y_s, d_s\n\ndef closet_split_pair(p_x, p_y, d, best_pair):\n mid_x = p_x[len(p_x)//2][0]\n\n # create a subarray of points not further than delta from\n # midpoint on x-sorted array\n s_y = [x for x in p_y if (mid_x-d) <= x[0] <= (mid_x+d)]\n\n d_min = d\n for i in range(len(s_y)-1):\n for j in range(i+1, len(s_y)):\n d_new = dist(s_y[i], s_y[j])\n if d_new <= d_min:\n d_min = d_new\n best_pair = s_y[i], s_y[j]\n\n return best_pair[0], best_pair[1], d_min\n\ndef brute(p_x):\n p1, p2 = p_x[0], p_x[1]\n d_min = dist(p_x[0], p_x[1])\n\n if len(p_x) == 2:\n return p_x[0], p_x[1], d_min\n\n for i in range(len(p_x)-1):\n for j in range(i+1, len(p_x)):\n d_new = dist(p_x[i], p_x[j])\n if d_new <= d_min:\n d_min = d_new\n p1, p2 = p_x[i], p_x[j]\n\n return p1, p2, d_min\n\ndef main():\n # test\n points = random_create(20) # length = 20\n print(points)\n \n p_x = sorted(points, key = lambda x: x[0]) # preshorting X_wise\n p_y = sorted(points, key = lambda x: x[1]) # preshorting Y_wise\n (p1, p2, d_min) = closet_pair(p_x, p_y)\n print(\"Closet pair:\",p1, p2)\n print(\"Distance:\", d_min)\n\ndef random_create(length):\n points = []\n temp_pair = (0,0)\n x_list = [random.randint(-20, 20) for i in range(length)]\n y_list = [random.randint(-20, 20) for i in range(length)]\n\n for i in range(length):\n temp_pair = x_list[i], y_list[i]\n points.append(temp_pair)\n\n return points\n\ndef dist(p1, p2):\n return math.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Closet_Pair.py","file_name":"Closet_Pair.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"236528981","text":"import torch\nimport torch.distributions as torchdist\nfrom torch.distributions import constraints\nfrom torch.distributions.distribution import Distribution\n\n\nclass DoubleSidedStandardMaxwell(Distribution):\n \"\"\"\n Adapted from https://github.com/deepmind/mc_gradients\n Creates a Double-Sided Standard Maxwell distribution with parameters loc=0., scale=1.\n This distribution is useful to compute measure valued derivatives for Gaussian distributions.\n\n #### Mathematical details\n\n The double-sided Maxwell distribution generalizes the Maxwell distribution to the entire real line.\n\n ```none\n pdf(x; mu, sigma) = 1/(sigma*sqrt(2*pi)) * ((x-mu)/sigma)^2 * exp(-0.5 ((x-mu)/sigma)^2)\n ```\n where `loc = mu` and `scale = sigma`.\n\n The DoublesidedMaxwell distribution is a member of the\n [location-scale family](https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be constructed as,\n\n ```none\n X ~ DoublesidedMaxwell(loc=0, scale=1)\n Y = loc + scale * X\n ```\n\n The double-sided Maxwell is a symmetric distribution that extends the one-sided maxwell from R+ to the\n entire real line. Their densities are therefore the same up to a factor of 0.5.\n\n It has several methods for generating random variates from it. The version here uses 3 Gaussian variates and a\n uniform variate to generate the samples. The sampling path for a double-sided Maxwell(mu, sigma) is:\n mu + sigma* sgn(U-0.5)* sqrt(X^2 + Y^2 + Z^2) U~Unif; X,Y,Z ~N(0,1)\n\n For the STANDARD double-sided Maxwell(0., 1.), the sampling path is\n sgn(U-0.5)* sqrt(X^2 + Y^2 + Z^2) U~Unif; X,Y,Z ~N(0,1)\n\n In the sampling process above, the random variates generated by sqrt(X^2 + Y^2 + Z^2) are samples from the\n one-sided Maxwell (or Maxwell-Boltzmann) distribution.\n\n \"\"\"\n\n support = constraints.real\n has_rsample = True\n\n def __init__(self, validate_args=None):\n # TODO: Extend to the general Double-Sided Maxwell with loc and scale\n self._uniform = torchdist.uniform.Uniform(low=0., high=1.)\n\n self._gaussian1 = torchdist.normal.Normal(loc=0., scale=1.)\n self._gaussian2 = torchdist.normal.Normal(loc=0., scale=1.)\n self._gaussian3 = torchdist.normal.Normal(loc=0., scale=1.)\n\n batch_shape = torch.Size()\n super(DoubleSidedStandardMaxwell, self).__init__(batch_shape, validate_args=validate_args)\n\n def rsample(self, sample_shape=torch.Size(())):\n # TODO: Do not sample the gaussians one after the other. Try to sample all at the same time to reduce computation.\n shape = self._extended_shape(sample_shape)\n X = self._gaussian1.rsample(sample_shape).view(shape)\n Y = self._gaussian2.rsample(sample_shape).view(shape)\n Z = self._gaussian3.rsample(sample_shape).view(shape)\n\n U = self._uniform.rsample(sample_shape).view(shape)\n\n sgn = torch.sign(U - 0.5)\n # Samples from the one-sided Maxwell-Boltzamnn distribution\n MB = torch.sqrt(torch.pow(X, 2) + torch.pow(Y, 2) + torch.pow(Z, 2))\n\n dsm = sgn * MB\n\n # TODO: remove to increase speedup?\n # self._validate_sample(dsm)\n\n return dsm\n\n\ndef std_gaussian_from_std_dsmaxwell(std_dsmaxwell_samples):\n \"\"\"\n Adapted from https://github.com/deepmind/mc_gradients\n Generate Gaussian variates from Double-sided Maxwell variates.\n\n Useful for coupling samples from Gaussian and double_sided Maxwell dist.\n 1. Generate ds-maxwell variates: dsM ~ dsMaxwell(0,1)\n 2. Generate uniform variates: u ~ Unif(0,1)\n 3. multiply y = u * dsM\n The result is Gaussian distribution N(0,1) which can be loc-scale adjusted.\n\n Args:\n std_dsmaxwell_samples: Samples generated from a zero-mean, unit variance\n double-sided Maxwell distribution M(0,1).\n Returns:\n Tensor of Gaussian variates with the same shape as the input.\n \"\"\"\n unif_rvs = torchdist.uniform.Uniform(low=0., high=1.).sample(std_dsmaxwell_samples.shape)\n gaussian_rvs = unif_rvs * std_dsmaxwell_samples\n\n return gaussian_rvs\n","sub_path":"Pyrado/pyrado/algorithms/torchdist_utils.py","file_name":"torchdist_utils.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"575343075","text":"from app.utils.parameters.BaseTaskParameters import BaseTaskParameters\nfrom app.utils.parameters.AssignationStepParameters import AssignationStepParameters\n\n\nclass AssignationTaskParameters(BaseTaskParameters):\n\n def __init__(\n self,\n task_type='duplicates',\n task_name='Bugzilla-DecisionTreeClassifier',\n task_id=0,\n task_description='Detección de incidencias duplicadas',\n task_corpus='Bugzilla',\n steps=None\n ):\n if steps is None:\n steps = [\n AssignationStepParameters()\n ]\n super().__init__(task_type, task_name, task_id, task_description, task_corpus)\n self.steps = steps\n","sub_path":"app/utils/parameters/AssignationTaskParameters.py","file_name":"AssignationTaskParameters.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"640431919","text":"'''\nWe implement principal component analysis with MNIST handwritten digits dataset.\nThe data is available at http://www.cs.nyu.edu/~roweis/data.html . \nIn particular we apply pca to the images of digit 9 which consists of 5949 training examples. \nWe pick the number of principal components such that 95% variance is retained. \nWe display the first 16 principal components. We also display an example of a handwritten\ndigit before and pca is applied. \n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io as spio\nfrom scipy import ndimage\nfrom scipy import linalg\nfrom sklearn import preprocessing\nfrom mpl_toolkits.axes_grid1 import ImageGrid\n\n\ndef loadData(filename):\n\tdata = spio.loadmat(filename)\n\tX = data['train9'].astype(float)\n\treturn X\n\n\ndef featureNormalize(X):\n\t# normalize the features with mean=0 and std=1\n\tscaler = preprocessing.StandardScaler()\n\tscaler.fit(X)\n\tX_norm = scaler.transform(X)\n\treturn X_norm\t\n\t\n\t\ndef pca(X):\n\t# compute the covariance matrix\n\tsigma = np.cov(X, rowvar=0)\n\n\t# compute the singular value decomposition of sigma\n\tU, S, Vh = linalg.svd(sigma)\n\t\n\t# return the eigenvectors and the singular values\n\treturn U, S\n\t\n\t\ndef projectData(X, U, K):\n\t# project the data onto the eigenspace\n\tU_reduce = U[:,range(K)]\n\treturn np.dot(X, U_reduce)\n\n\ndef recoverData(Z, U, K):\n\tU_reduce = U[:, range(K)]\n\treturn np.dot(Z, U_reduce.T)\n\t\t\n\t\t\t\ndef displayData(image):\n\timage = image.reshape(28,28)\n\tplt.imshow(image, cmap = plt.cm.gray)\n\t\n\ndef displayExample(image1, image2):\t\n\tplt.figure()\n\t\n\tplt.subplot(121)\n\tdisplayData(image1)\n\tplt.xticks([])\n\tplt.yticks([])\n\tplt.title('Original')\n\t\n\tplt.subplot(122)\n\tdisplayData(image2)\n\tplt.xticks([])\n\tplt.yticks([])\n\tplt.title('Recovered after PCA')\t\n\t\n\t\ndef displayEigenvectors(U):\t\n\tU = U.reshape(28,28,16)\n\tfig = plt.figure(1, (6., 6.))\n\tplt.title('First 16 Principal Components')\n\tplt.xticks([])\n\tplt.yticks([])\n\t\t\n\tgrid = ImageGrid(fig, 111, nrows_ncols = (4, 4), axes_pad=0.0)\n\tfor i in range(16):\n\t\tax = grid[i] \n\t\tax.imshow(U[:,:,i], cmap = plt.cm.gray)\n\t\tax.get_xaxis().set_visible(False)\t\n\t\tax.get_yaxis().set_visible(False)\t\n\n\n\t\ndef main():\n\tX = loadData('mnist_all.mat')\n\n\t# normalize features with mean=0 and std=1\n\tX_norm = featureNormalize(X)\n\t\n\t# run PCA and get the array of eigenvectors\tand the singular values\n\tU, S = pca(X_norm)\n\t\n\t# pick the number of principal components so that 95% of variance is retained\n\tK = 0\t\t\t\t# number of principal components\n\tfor i in range(len(S)):\n\t\tif (np.sum(S[:i+1]) / np.sum(S)) >= 0.95:\n\t\t\tK = i\n\t\t\tbreak\t\n\t\t\n\t# plot the first 16 principal components \n\tdisplayEigenvectors(U[:,:16])\n\n\t# project the images of digits to eigenspace spanned by K vectors\n\tZ = projectData(X_norm, U, K)\n\t\n\t# recover back the images of digits projected on the eigenspace\n\tX_rec = recoverData(Z, U, K)\n\t\n\t# display an example of a handwritten digit before and after PCA\n\tdisplayExample(X_norm[2], X_rec[2])\n\n\n\t\n\tplt.show()\t\t\t\n\t\t\n\t\t\nif __name__ == '__main__':\n\tmain()\t\t\n","sub_path":"Principal-Component-Analysis/pca_mnist.py","file_name":"pca_mnist.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"183903868","text":"a=sorted('QWERTYUIOPLKJHGFDSAZXCVBNM')\r\nb={}\r\nn=1\r\nfor i in a:\r\n b[i]=n\r\n n+=1\r\nprint(b)\r\nf=open(\"f.txt\",'r')\r\ndata=(f.readlines())\r\nprint(len(data))\r\ndata=sorted(data[0].strip().split(','))\r\nprint(len(data))\r\ntot=0\r\nn=0\r\n\r\nfor i in data:\r\n k=0\r\n n+=1\r\n for j in i: \r\n if j!='\"':\r\n k+=b[j]\r\n val= n*k\r\n tot=tot+val\r\nprint(tot)\r\n","sub_path":"022/PE022.py","file_name":"PE022.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"56078679","text":"'''\nWrite a Program which detects whether the entered number is\nperfect or not .\n{Note: If sum of perfect divisors of number is equal to the entered number\nthan it is considered as perfect one.}\nInput : 6\nOutput : 6 is a Perfect number.\n\n'''\n\nnum = int(input(\"Enter a number : \"))\nsum = 0\nfor i in range (1,num):\n\tif(num % i == 0):\n\t\tsum = sum + i\nif(sum == num):\n\tprint(num,\"is a perfect number\")\nelse:\n\tprint(num,\"is not a perfect number\")\n\n","sub_path":"Python/DailyFlash/28jan2020/MySolutions/program1.py","file_name":"program1.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"382517980","text":"import os\nimport logging\nimport subprocess\nimport struct\nimport elftools\n\ntry:\n import claripy\nexcept ImportError:\n claripy = None\n\n__all__ = ('Loader',)\n\nl = logging.getLogger(\"cle.loader\")\n\nclass Loader(object):\n \"\"\"\n The loader loads all the objects and exports an abstraction of the memory of the process. What you see here is an\n address space with loaded and rebased binaries.\n\n :ivar memory: The loaded, rebased, and relocated memory of the program.\n :vartype memory: cle.memory.Clemory\n :ivar main_bin: The object representing the main binary (i.e., the executable).\n :ivar shared_objects: A dictionary mapping loaded library names to the objects representing them.\n :ivar all_objects: A list containing representations of all the different objects loaded.\n :ivar requested_objects: A set containing the names of all the different shared libraries that were marked as a\n dependency by somebody.\n :ivar tls_object: An object dealing with the region of memory allocated for thread-local storage.\n\n When reference is made to a dictionary of options, it requires a dictionary with zero or more of the following keys:\n\n - backend : \"elf\", \"pe\", \"ida\", \"blob\": which loader backend to use\n - custom_arch : The archinfo.Arch object to use for the binary\n - custom_base_addr : The address to rebase the object at\n - custom_entry_point : The entry point to use for the object\n\n More keys are defined on a per-backend basis.\n \"\"\"\n\n def __init__(self, main_binary, auto_load_libs=True,\n force_load_libs=None, skip_libs=None,\n main_opts=None, lib_opts=None, custom_ld_path=None,\n ignore_import_version_numbers=True, rebase_granularity=0x1000000,\n except_missing_libs=False, gdb_map=None, gdb_fix=False, aslr=False):\n \"\"\"\n :param main_binary: The path to the main binary you're loading, or a file-like object with the binary\n in it.\n\n The following parameters are optional.\n\n :param auto_load_libs: Whether to automatically load shared libraries that loaded objects depend on.\n :param force_load_libs: A list of libraries to load regardless of if they're required by a loaded object.\n :param skip_libs: A list of libraries to never load, even if they're required by a loaded object.\n :param main_opts: A dictionary of options to be used loading the main binary.\n :param lib_opts: A dictionary mapping library names to the dictionaries of options to be used when\n loading them.\n :param custom_ld_path: A list of paths in which we can search for shared libraries.\n :param ignore_import_version_numbers:\n Whether libraries with different version numbers in the filename will be considered\n equivalent, for example libc.so.6 and libc.so.0\n :param rebase_granularity: The alignment to use for rebasing shared objects\n :param except_missing_libs: Throw an exception when a shared library can't be found.\n :param gdb_map: The output of `info proc mappings` or `info sharedlibrary` in gdb. This will be used\n to determine the base address of libraries.\n :param gdb_fix: If `info sharedlibrary` was used, the addresses gdb gives us are in fact the\n addresses of the .text sections. We need to fix them to get the real load addresses.\n :param aslr Load libraries in symbolic address space.\n \"\"\"\n\n if hasattr(main_binary, 'seek') and hasattr(main_binary, 'read'):\n self._main_binary_path = None\n self._main_binary_stream = main_binary\n else:\n self._main_binary_path = os.path.realpath(str(main_binary))\n self._main_binary_stream = None\n self._auto_load_libs = auto_load_libs\n self._unsatisfied_deps = [] if force_load_libs is None else list(force_load_libs)\n self._satisfied_deps = set([] if skip_libs is None else skip_libs)\n self._main_opts = {} if main_opts is None else main_opts\n self._lib_opts = {} if lib_opts is None else lib_opts\n self._custom_ld_path = [] if custom_ld_path is None else custom_ld_path\n self._ignore_import_version_numbers = ignore_import_version_numbers\n self._rebase_granularity = rebase_granularity\n self._except_missing_libs = except_missing_libs\n self._relocated_objects = set()\n\n self.aslr = aslr\n self.memory = None\n self.main_bin = None\n self.shared_objects = {}\n self.all_objects = []\n self.requested_objects = set()\n self.tls_object = None\n self._load_main_binary()\n\n if gdb_map is not None:\n self._gdb_fix = gdb_fix\n gdb_lib_opts = self._gdb_load_options(gdb_map)\n self._lib_opts = self._merge_opts(gdb_lib_opts, self._lib_opts)\n\n self._load_dependencies()\n self._load_tls()\n self._perform_reloc(self.main_bin)\n self._finalize_tls()\n\n def close(self):\n for obj in self.all_objects:\n obj.close()\n\n def __repr__(self):\n if self._main_binary_stream is None:\n return '' % (os.path.basename(self._main_binary_path), self.min_addr(), self.max_addr())\n else:\n return '' % (self.min_addr(), self.max_addr())\n\n def get_initializers(self):\n \"\"\"\n Return a list of all the initializers that should be run before execution reaches the entry point, in the order\n they should be run.\n \"\"\"\n return sum(map(lambda x: x.get_initializers(), self.all_objects), [])\n\n def get_finalizers(self):\n \"\"\"\n Return a list of all the finalizers that should be run before the program exits.\n I'm not sure what order they should be run in.\n \"\"\"\n return sum(map(lambda x: x.get_initializers(), self.all_objects), [])\n\n @property\n def linux_loader_object(self):\n for obj in self.all_objects:\n if obj.provides is None:\n continue\n if self._is_linux_loader_name(obj.provides) is True:\n return obj\n return None\n\n @staticmethod\n def _is_linux_loader_name(name):\n \"\"\"\n ld can have different names such as ld-2.19.so or ld-linux-x86-64.so.2 depending on symlinks and whatnot.\n This determines if `name` is a suitable candidate for ld.\n \"\"\"\n return 'ld.so' in name or 'ld64.so' in name or 'ld-linux' in name\n\n def _load_main_binary(self):\n options = dict(self._main_opts)\n options['aslr'] = self.aslr\n self.main_bin = self.load_object(self._main_binary_path\n if self._main_binary_stream is None\n else self._main_binary_stream,\n self._main_opts,\n is_main_bin=True)\n self.memory = Clemory(self.main_bin.arch, root=True)\n base_addr = self._main_opts.get('custom_base_addr', None)\n if base_addr is None and self.main_bin.requested_base is not None:\n base_addr = self.main_bin.requested_base\n if base_addr is None and self.main_bin.pic:\n l.warning(\"The main binary is a position-independent executable. \"\n \"It is being loaded with a base address of 0x400000.\")\n base_addr = 0x400000\n if base_addr is None:\n base_addr = 0\n self.add_object(self.main_bin, base_addr)\n\n def _load_dependencies(self):\n while len(self._unsatisfied_deps) > 0:\n dep = self._unsatisfied_deps.pop(0)\n options = {}\n if isinstance(dep, (str, unicode)):\n if os.path.basename(dep) in self._satisfied_deps:\n continue\n if self._ignore_import_version_numbers and dep.strip('.0123456789') in self._satisfied_deps:\n continue\n\n path = self._get_lib_path(dep)\n\n for path in self._possible_paths(dep):\n libname = os.path.basename(path)\n if self.identify_object(path) == 'elf':\n soname = self._extract_soname(path)\n else:\n soname = libname\n\n if libname in self._lib_opts.keys():\n options = dict(self._lib_opts[libname])\n elif soname in self._lib_opts.keys():\n options = dict(self._lib_opts[soname])\n\n try:\n options['aslr'] = self.aslr\n obj = self.load_object(path, options, compatible_with=self.main_bin)\n break\n except (CLECompatibilityError, CLEFileNotFoundError):\n continue\n else:\n if self._except_missing_libs:\n raise CLEFileNotFoundError(\"Could not find shared library: %s\" % dep)\n continue\n elif isinstance(dep, Backend):\n obj = dep\n else:\n raise CLEError(\"Bad library: %s\" % path)\n\n base_addr = options.get('custom_base_addr', None)\n self.add_object(obj, base_addr)\n\n @staticmethod\n def load_object(path, options=None, compatible_with=None, is_main_bin=False):\n \"\"\"\n Load a file with some backend. Try to identify the type of the file to autodetect which backend to use.\n\n :param str path: The path to the file to load\n\n The following parameters are optional.\n\n :param dict options: A dictionary of keyword arguments to the backend. Can contain a `backend` key to\n force the use of a specific backend\n :param compatiable_with: Another backend object that this file must be compatible with.\n This method will throw a :class:`CLECompatibilityError `\n if the file at the given path is not compatibile with this parameter.\n :param bool is_main_bin: Whether this file is the main executable of whatever process we are loading\n \"\"\"\n # Try to find the filetype of the object. Also detect if you were given a bad filepath\n if options is None:\n options = {}\n try:\n filetype = Loader.identify_object(path)\n except OSError:\n raise CLEFileNotFoundError('File %s does not exist!' % path)\n\n # Verify that that filetype is acceptable\n if compatible_with is not None and filetype != compatible_with.filetype:\n raise CLECompatibilityError('File %s is not compatible with %s' % (path, compatible_with))\n\n # Check if the user specified a backend as...\n backend_option = options.get('backend', None)\n if isinstance(backend_option, type) and issubclass(backend_option, Backend):\n # ...an actual backend class\n backends = [backend_option]\n elif backend_option in ALL_BACKENDS:\n # ...the name of a backend class\n backends = [ALL_BACKENDS[backend_option]]\n elif isinstance(backend_option, (list, tuple)):\n # ...a list of backends containing either names or classes\n backends = []\n for backend_option_item in backend_option:\n if isinstance(backend_option_item, type) and issubclass(backend_option_item, Backend):\n backends.append(backend_option_item)\n elif backend_option_item in ALL_BACKENDS:\n backends.append(ALL_BACKENDS[backend_option_item])\n else:\n raise CLEError('Invalid backend: %s' % backend_option_item)\n elif backend_option is None:\n backends = ALL_BACKENDS.values()\n else:\n raise CLEError('Invalid backend: %s' % backend_option)\n\n backends = filter(lambda x: filetype in x.supported_filetypes, backends)\n if len(backends) == 0:\n raise CLECompatibilityError('No compatible backends specified for filetype %s (file %s)' % (filetype, path))\n\n for backend in backends:\n try:\n loaded = backend(path, compatible_with=compatible_with, filetype=filetype, is_main_bin=is_main_bin, **options)\n return loaded\n except CLECompatibilityError:\n raise\n except CLEError:\n l.exception(\"Loading error when loading %s with backend %s\", path, backend.__name__)\n raise CLEError(\"All backends failed loading %s!\" % path)\n\n def get_loader_symbolic_constraints(self):\n if not self.aslr:\n return []\n if not claripy:\n l.error(\"Please install claripy to get symbolic constraints\")\n return []\n outputlist = []\n for obj in self.all_objects:\n #TODO Fix Symbolic for tls whatever\n if obj.aslr and isinstance(obj.rebase_addr_symbolic, claripy.ast.BV):\n outputlist.append(obj.rebase_addr_symbolic == obj.rebase_addr)\n return outputlist\n\n @staticmethod\n def identify_object(path):\n \"\"\"\n Returns the filetype of the file `path`. Will be one of the strings in {'elf', 'elfcore', 'pe', 'mach-o',\n 'unknown'}.\n \"\"\"\n if hasattr(path, 'seek') and hasattr(path, 'read'):\n path.seek(0)\n stream = path\n plsclose = False\n else:\n stream = open(path, 'rb')\n plsclose = True\n\n identstring = stream.read(0x1000)\n stream.seek(0)\n\n if identstring.startswith('\\x7fELF'):\n if elftools.elf.elffile.ELFFile(stream).header['e_type'] == 'ET_CORE':\n if plsclose: stream.close()\n return 'elfcore'\n if plsclose: stream.close()\n return 'elf'\n elif identstring.startswith('MZ') and len(identstring) > 0x40:\n peptr = struct.unpack('I', identstring[0x3c:0x40])[0]\n if peptr < len(identstring) and identstring[peptr:peptr+4] == 'PE\\0\\0':\n return 'pe'\n elif identstring.startswith('\\xfe\\xed\\xfa\\xce') or \\\n identstring.startswith('\\xfe\\xed\\xfa\\xcf') or \\\n identstring.startswith('\\xce\\xfa\\xed\\xfe') or \\\n identstring.startswith('\\xcf\\xfa\\xed\\xfe'):\n return 'mach-o'\n elif identstring.startswith('\\x7fCGC'):\n return 'cgc'\n return 'unknown'\n\n def add_object(self, obj, base_addr=None):\n \"\"\"\n Add object `obj` to the memory map, rebased at `base_add`. If `base_addr` is None CLE will pick a safe one.\n Registers all its dependencies.\n \"\"\"\n\n if self._auto_load_libs:\n self._unsatisfied_deps += obj.deps\n self.requested_objects.update(obj.deps)\n\n if obj.provides is not None:\n self._satisfied_deps.add(obj.provides)\n if self._ignore_import_version_numbers:\n self._satisfied_deps.add(obj.provides.strip('.0123456789'))\n\n obj.rebase_addr = 0\n obj_offset = obj.get_min_addr()\n obj_size = obj.get_max_addr() - obj_offset\n\n if base_addr is not None and self._is_range_free(base_addr + obj_offset, obj_size):\n pass\n elif obj.requested_base is not None and self._is_range_free(obj.requested_base + obj_offset, obj_size):\n base_addr = obj.requested_base\n else:\n base_addr = self._get_safe_rebase_addr()\n\n self.all_objects.append(obj)\n if obj.provides is not None:\n self.shared_objects[obj.provides] = obj\n\n l.info(\"[Rebasing %s @%#x]\", obj.binary, base_addr)\n self.memory.add_backer(base_addr, obj.memory)\n obj.rebase_addr = base_addr\n\n def _is_range_free(self, addr, size):\n for o in self.all_objects:\n if (addr >= o.get_min_addr() and addr < o.get_max_addr()) or \\\n (o.get_min_addr() >= addr and o.get_min_addr() < addr + size):\n return False\n return True\n\n\n def _possible_paths(self, path):\n if os.path.exists(path): yield path\n dirs = [] # if we say dirs = blah, we modify the original\n dirs += self._custom_ld_path\n if self._main_binary_path is not None:\n dirs += [os.path.dirname(self._main_binary_path)]\n dirs += self.main_bin.arch.library_search_path()\n for libdir in dirs:\n fullpath = os.path.realpath(os.path.join(libdir, path))\n if os.path.exists(fullpath): yield fullpath\n if self._ignore_import_version_numbers:\n try:\n for libname in os.listdir(libdir):\n if libname.strip('.0123456789') == path.strip('.0123456789'):\n yield os.path.realpath(os.path.join(libdir, libname))\n except (IOError, OSError): pass\n\n def relocate(self):\n \"\"\"\n Attemts to resolve all yet-unresolved relocations in all loaded objects.\n It is appropriate to call this repeatedly.\n \"\"\"\n\n self._relocated_objects = set()\n for obj in self.all_objects:\n self._perform_reloc(obj)\n\n def _perform_reloc(self, obj):\n if id(obj) in self._relocated_objects:\n return\n self._relocated_objects.add(id(obj))\n\n dep_objs = [self.shared_objects[dep_name] for dep_name in obj.deps if dep_name in self.shared_objects]\n for dep_obj in dep_objs:\n self._perform_reloc(dep_obj)\n\n if isinstance(obj, (MetaELF, PE)):\n for reloc in obj.relocs:\n if not reloc.resolved:\n reloc.relocate(([self.main_bin] if self.main_bin is not obj else []) + dep_objs + [obj])\n\n def provide_symbol(self, owner, name, offset, size=0, binding='STB_GLOBAL', st_type='STT_FUNC', st_info='CLE'):\n newsymbol = Symbol(owner, name, offset, size, binding, st_type, st_info)\n owner._symbol_cache[name] = newsymbol\n solist = [owner]\n\n for obj in self.all_objects:\n if isinstance(obj, (MetaELF, PE)):\n for reloc in obj.relocs:\n if reloc.symbol and reloc.symbol.name == name:\n reloc.relocate(solist, bypass_compatibility=True)\n\n\n def _get_safe_rebase_addr(self):\n \"\"\"\n Get a \"safe\" rebase addr, i.e., that won't overlap with already loaded stuff. This is used as a fallback when we\n cannot use LD to tell use where to load a binary object. It is also a workaround to IDA crashes when we try to\n rebase binaries at too high addresses.\n \"\"\"\n granularity = self._rebase_granularity\n return self.max_addr() + (granularity - self.max_addr() % granularity)\n\n def _load_tls(self):\n \"\"\"\n Set up an object to store TLS data in.\n \"\"\"\n elf_modules = []\n pe_modules = []\n\n for obj in self.all_objects:\n if isinstance(obj, MetaELF) and obj.tls_used:\n elf_modules.append(obj)\n elif isinstance(obj, PE) and obj.tls_used:\n pe_modules.append(obj)\n num_elf_modules = len(elf_modules)\n num_pe_modules = len(pe_modules)\n\n # TODO: This assert ensures that we have either ELF or PE modules, but not both.\n # Do we need to handle the case where we have both ELF and PE modules?\n assert num_elf_modules != num_pe_modules or num_elf_modules == 0 or num_pe_modules == 0\n if len(elf_modules) > 0:\n self.tls_object = ELFTLSObj(elf_modules)\n elif len(pe_modules) > 0:\n self.tls_object = PETLSObj(pe_modules)\n\n if self.tls_object:\n self.add_object(self.tls_object)\n\n def _finalize_tls(self):\n \"\"\"\n Lay out the TLS initialization images into memory.\n \"\"\"\n if self.tls_object is not None:\n self.tls_object.finalize()\n\n def addr_belongs_to_object(self, addr):\n for obj in self.all_objects:\n if not (addr >= obj.get_min_addr() and addr < obj.get_max_addr()):\n continue\n\n if isinstance(obj.memory, str):\n return obj\n\n elif isinstance(obj.memory, Clemory):\n if addr - obj.rebase_addr in obj.memory:\n return obj\n\n else:\n raise CLEError('Unsupported memory type %s' % type(obj.memory))\n\n return None\n\n def whats_at(self, addr):\n \"\"\"\n Tells you what's at `addr` in terms of the offset in one of the loaded binary objects.\n \"\"\"\n o = self.addr_belongs_to_object(addr)\n\n if o is None:\n return None\n\n off = addr - o.rebase_addr\n nameof = 'main binary' if o is self.main_bin else o.provides\n\n if isinstance(o, ELF):\n if addr in o.plt.values():\n for k,v in o.plt.iteritems():\n if v == addr:\n return \"PLT stub of %s in %s (offset %#x)\" % (k, nameof, off)\n\n if off in o.symbols_by_addr:\n name = o.symbols_by_addr[off].name\n return \"%s (offset %#x) in %s\" % (name, off, nameof)\n\n return \"Offset %#x in %s\" % (off, nameof)\n\n def max_addr(self):\n \"\"\"\n The maximum address loaded as part of any loaded object (i.e., the whole address space).\n \"\"\"\n return max(map(lambda x: x.get_max_addr(), self.all_objects))\n\n def min_addr(self):\n \"\"\"\n The minimum address loaded as part of any loaded object (i.e., the whole address space).\n \"\"\"\n return min(map(lambda x: x.get_min_addr(), self.all_objects))\n\n # Search functions\n\n def find_symbol_name(self, addr):\n \"\"\"\n Return the name of the function starting at `addr`.\n \"\"\"\n for so in self.all_objects:\n if addr - so.rebase_addr in so.symbols_by_addr:\n return so.symbols_by_addr[addr - so.rebase_addr].name\n return None\n\n def find_plt_stub_name(self, addr):\n \"\"\"\n Return the name of the PLT stub starting at `addr`.\n \"\"\"\n for so in self.all_objects:\n if isinstance(so, MetaELF):\n if addr in so.reverse_plt:\n return so.reverse_plt[addr]\n return None\n\n def find_module_name(self, addr):\n \"\"\"\n Return the name of the loaded module containing `addr`.\n \"\"\"\n for o in self.all_objects:\n # The Elf class only works with static non-relocated addresses\n if o.contains_addr(addr - o.rebase_addr):\n return o.provides\n\n def find_symbol_got_entry(self, symbol):\n \"\"\"\n Look for the address of a GOT entry for `symbol`.\n\n :returns: The address of the symbol if found, None otherwise.\n \"\"\"\n if isinstance(self.main_bin, IDABin):\n if symbol in self.main_bin.imports:\n return self.main_bin.imports[symbol]\n elif isinstance(self.main_bin, ELF):\n if symbol in self.main_bin.jmprel:\n return self.main_bin.jmprel[symbol].addr\n\n def _ld_so_addr(self):\n \"\"\"\n Use LD_AUDIT to find object dependencies and relocation addresses.\n \"\"\"\n\n qemu = 'qemu-%s' % self.main_bin.arch.qemu_name\n env_p = os.getenv(\"VIRTUAL_ENV\", \"/\")\n bin_p = os.path.join(env_p, \"local/lib\", self.main_bin.arch.name.lower())\n\n # Our LD_AUDIT shared object\n ld_audit_obj = os.path.join(bin_p, \"cle_ld_audit.so\")\n\n #LD_LIBRARY_PATH\n ld_path = os.getenv(\"LD_LIBRARY_PATH\")\n if ld_path is None:\n ld_path = bin_p\n else:\n ld_path = ld_path + \":\" + bin_p\n\n cross_libs = self.main_bin.arch.lib_paths\n if self.main_bin.arch.name in ('AMD64', 'X86'):\n ld_libs = self.main_bin.arch.lib_paths\n elif self.main_bin.arch.name == 'PPC64':\n ld_libs = map(lambda x: x + 'lib64/', self.main_bin.arch.lib_paths)\n else:\n ld_libs = map(lambda x: x + 'lib/', self.main_bin.arch.lib_paths)\n ld_libs = ':'.join(ld_libs)\n ld_path = ld_path + \":\" + ld_libs\n\n # Make LD look for custom libraries in the right place\n if self._custom_ld_path is not None:\n ld_path = self._custom_ld_path + \":\" + ld_path\n\n var = \"LD_LIBRARY_PATH=%s,LD_AUDIT=%s,LD_BIND_NOW=yes\" % (ld_path, ld_audit_obj)\n\n # Let's work on a copy of the binary\n binary = self._binary_screwup_copy(self._main_binary_path)\n\n #LD_AUDIT's output\n log = \"./ld_audit.out\"\n\n cmd = [qemu, \"-strace\", \"-L\", cross_libs, \"-E\", var, binary]\n s = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\n # Check stderr for library loading issues\n err = s.stderr.readlines()\n msg = \"cannot open shared object file\"\n\n deps = self.main_bin.deps\n\n for dep in deps:\n for str_e in err:\n if dep in str_e and msg in str_e:\n l.error(\"LD could not find dependency %s.\", dep)\n l.error(\"GNU LD will stop looking for libraries to load if \"\n \"it doesn't find one of them.\")\n #self.ld_missing_libs.append(dep)\n break\n\n s.communicate()\n\n # Our LD_AUDIT library is supposed to generate a log file.\n # If not we're in trouble\n if os.path.exists(log):\n libs = {}\n with open(log, 'r') as f:\n for i in f.readlines():\n lib = i.split(\",\")\n if lib[0] == \"LIB\":\n libs[lib[1]] = int(lib[2].strip(), 16)\n l.debug(\"---\")\n for o, a in libs.iteritems():\n l.debug(\" -> Dependency: %s @ %#x)\", o, a)\n\n l.debug(\"---\")\n os.remove(log)\n return libs\n\n else:\n\n l.error(\"Could not find library dependencies using ld.\"\n \" The log file '%s' does not exist, did qemu fail ? Try to run \"\n \"`%s` manually to check\", log, \" \".join(cmd))\n raise CLEOperationError(\"Could not find library dependencies using ld.\")\n\n def _binary_screwup_copy(self, path):\n \"\"\"\n When LD_AUDIT cannot load CLE's auditing library, it unfortunately falls back to executing the target, which we\n don't want ! This is a problem specific to GNU LD, we can't fix this.\n\n This is a simple hack to work around it: set the address of the entry point to 0 in the program header\n This will cause the main binary to segfault if executed.\n \"\"\"\n\n # Let's work on a copy of the main binary\n copy = self._make_tmp_copy(path, suffix=\".screwed\")\n with open(copy, 'r+b') as f:\n # Looking at elf.h, we can see that the the entry point's\n # definition is always at the same place for all architectures.\n off = 0x18\n f.seek(off)\n count = self.main_bin.arch.bits / 8\n\n # Set the entry point to address 0\n screw_char = \"\\x00\"\n screw = screw_char * count\n f.write(screw)\n return copy\n\n @staticmethod\n def _make_tmp_copy(path, suffix=None):\n \"\"\"\n Makes a copy of obj into CLE's tmp directory.\n \"\"\"\n if not os.path.exists('/tmp/cle'):\n os.mkdir('/tmp/cle')\n\n if hasattr(path, 'seek') and hasattr(path, 'read'):\n stream = path\n else:\n try:\n stream = open(path, 'rb')\n except IOError:\n raise CLEFileNotFoundError(\"File %s does not exist :(. Please check that the\"\n \" path is correct\" % path)\n bn = os.urandom(5).encode('hex')\n if suffix is not None:\n bn += suffix\n dest = os.path.join('/tmp/cle', bn)\n l.info(\"\\t -> copy obj %s to %s\", path, dest)\n\n with open(dest, 'wb') as dest_stream:\n while True:\n dat = stream.read(1024*1024)\n if len(dat) == 0:\n break\n dest_stream.write(dat)\n\n return dest\n\n @staticmethod\n def _parse_gdb_map(gdb_map):\n \"\"\"\n Parser for gdb's ``info proc mappings``, or ``info sharedlibs``, or custom\n mapping file of the form base_addr : /path/to/lib.\n \"\"\"\n if os.path.exists(gdb_map):\n with open(gdb_map, 'rb') as f:\n data = f.readlines()\n gmap = {}\n for line in data:\n line_items = line.split()\n if line == '\\n':\n continue\n # Get rid of all metadata, just extract lines containing addresses\n if \"0x\" not in line_items[0]:\n continue\n elif \"linux-vdso\" in line_items[-1]:\n continue\n addr, objfile = int(line_items[0], 16), line_items[-1].strip()\n\n # Get the smallest address of each libs' mappings\n try:\n gmap[objfile] = min(gmap[objfile], addr)\n except KeyError:\n gmap[objfile] = addr\n return gmap\n\n def _gdb_load_options(self, gdb_map_path):\n \"\"\"\n Generate library options from a gdb proc mapping.\n \"\"\"\n lib_opts = {}\n gmap = self._parse_gdb_map(gdb_map_path)\n\n # Find lib names\n #libnames = filter(lambda n: '.so' in n, gmap.keys())\n\n # Find base addr for each lib (each lib is mapped to several segments,\n # we take the segment that is loaded at the smallest address).\n for lib, addr in gmap.items():\n if not \".so\" in lib:\n continue\n if not os.path.exists(lib):\n lib = self._get_lib_path(lib)\n\n soname = self._extract_soname(lib)\n\n # address of .text -> base address of the library\n if self._gdb_fix:\n addr = addr - self._get_text_offset(lib)\n\n l.info(\"gdb_plugin: mapped %s to %#x\", lib, addr)\n lib_opts[soname] = {\"custom_base_addr\":addr}\n return lib_opts\n\n @staticmethod\n def _get_text_offset(path):\n \"\"\"\n Offset of .text in the binary.\n \"\"\"\n if not os.path.exists(path):\n raise CLEError(\"Path %s does not exist\" % path)\n\n with open(path, 'rb') as f:\n e = elftools.elf.elffile.ELFFile(f)\n return e.get_section_by_name(\".text\").header.sh_offset\n\n @staticmethod\n def _extract_soname(path):\n \"\"\"\n Extracts the soname from the ELF binary at `path`.\n \"\"\"\n if not os.path.exists(path):\n raise CLEError(\"Path %s does not exist\" % path)\n\n with open(path, 'rb') as f:\n try:\n e = elftools.elf.elffile.ELFFile(f)\n dyn = e.get_section_by_name('.dynamic')\n soname = [ x.soname for x in list(dyn.iter_tags()) if x.entry.d_tag == 'DT_SONAME']\n if not soname:\n return os.path.basename(path)\n return soname[0]\n except elftools.common.exceptions.ELFError:\n return None\n\n def _check_compatibility(self, path):\n \"\"\"\n This checks whether the object at `path` is binary compatible with the main binary.\n \"\"\"\n try:\n filetype = Loader.identify_object(path)\n except OSError:\n raise CLEFileNotFoundError('File %s does not exist!' % path)\n\n return self.main_bin.filetype == filetype\n\n def _get_lib_path(self, libname):\n \"\"\"\n Get a path for `libname`. We pick the first plausible candidate that is binary compatible.\n \"\"\"\n # Valid path\n if os.path.exists(libname) and self._check_compatibility(libname):\n return libname\n\n # Wrong path and not a lib name\n elif not os.path.exists(libname) and libname != os.path.basename(libname):\n raise CLEFileNotFoundError(\"Invalid path or soname: %s\" % libname)\n paths = list(self._possible_paths(os.path.basename(libname)))\n for p in paths:\n if self._check_compatibility(p):\n return p\n\n @staticmethod\n def _merge_opts(opts, dest):\n \"\"\"\n Return a new dict corresponding to merging *opts* into *dest*. This makes sure we don't override previous\n options.\n \"\"\"\n for k,v in opts.iteritems():\n if k in dest and v in dest[k]:\n raise CLEError(\"%s/%s is overriden by gdb's\" % (k,v))\n return dict(opts.items() + dest.items())\n\n @property\n def all_elf_objects(self):\n return [o for o in self.all_objects if isinstance(o, MetaELF)]\n\n def perform_irelative_relocs(self, resolver_func):\n for obj in self.all_objects:\n for resolver, dest in obj.irelatives:\n val = resolver_func(resolver)\n if val is not None:\n obj.memory.write_addr_at(dest, val)\n\nfrom .errors import CLEError, CLEOperationError, CLEFileNotFoundError, CLECompatibilityError\nfrom .memory import Clemory\nfrom .tls import ELFTLSObj, PETLSObj\nfrom .backends import IDABin, MetaELF, ELF, PE, ALL_BACKENDS, Backend, Symbol\n","sub_path":"cle/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":34034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371641517","text":"\nimport re\nfrom math import exp\nfrom json import dumps\nfrom collections import defaultdict\nfrom random import uniform\nfrom operator import itemgetter\n\n# from pymystem3 import Mystem as M\n\nr_alphabet = re.compile(u'[а-яА-Я0-9-]+|[.,:;?!]+')\n\ndef gen_lines(corpus):\n data = open(corpus)\n for line in data:\n yield line.lower()\n\ndef gen_tokens(lines):\n for line in lines:\n for token in r_alphabet.findall(line):\n yield token\n\ndef gen_trigrams(tokens):\n t0, t1 = '$', '$'\n for t2 in tokens:\n yield t0, t1, t2\n if t2 in '.!?':\n yield t1, t2, '$'\n yield t2, '$','$'\n t0, t1 = '$', '$'\n else:\n t0, t1 = t1, t2\n\ndef train(text):\n\tlines = gen_lines(text)\n\ttokens = gen_tokens(lines)\n\ttrigrams = gen_trigrams(tokens)\n\n\tbi, tri = defaultdict(lambda: 0.0), defaultdict(lambda: 0.0)\n\t\n\tfor t0, t1, t2 in trigrams:\n\t\tbi[t0, t1] += 1\n\t\ttri[t0, t1, t2] += 1\n\n\tmodel = {}\n\tfor (t0, t1, t2), freq in tri.items():\n\t\tif (t0, t1) in model:\n\t\t\tmodel[t0, t1].append((t2, freq/bi[t0, t1]))\n\t\telse:\n\t\t\tmodel[t0, t1] = [(t2, freq/bi[t0, t1])]\n\treturn model\n\n# words=[('я', 1), ('поражают', 0.1), ('деревья', 0.1), ('впечатление', 0.1)]\n\ndef generate_sentence(words, model):\n\tphrase = []\n\tt0, t1 = '$', '$'\n\twhile 1:\n\t\tt0, t1 = t1, uni_not_rand(words=words, seq=model[t0, t1])\n\t\tif t1 == '$': break\n\t\tphrase += [t1]\n\treturn phrase\n\ndef uni_not_rand(words, seq):\n\tmax_fig = max(words.items(), key=itemgetter(1))[0]\n\tfor w, freq in seq:\n\t\tif w == max_fig:\n\t\t\twords.update({max_fig: words[max_fig]/2})\n\t\t\treturn w\n\n\treturn unirand(seq)\n\ndef unirand(seq):\n\tsum_, freq_ = 0, 0\n\tfor item, freq in seq:\n\t\tsum_ += freq\n\trnd = uniform(0, sum_)\n\tfor token, freq in seq:\n\t\tfreq_ += freq\n\t\tif rnd < freq_:\n\t\t\treturn token\n\ndef compare(S1,S2):\n\tngrams = [S1[i:i+3] for i in range(len(S1))]\n\t# print(ngrams)\n\tcount = 0\n\tfor ngram in ngrams:\n\t\tcount += S2.count(ngram)\n\n\treturn count/max(len(S1), len(S2))\n\ndef compare_sentence(sentence_words, words):\n\tdef sigma(x):\n\t\treturn (1/(1 + exp(-x)) - 0.5)*4\n\n\tres = 0\n\tfor w1 in sentence_words:\n\t\tfor w2 in words:\n\t\t\tc = compare(w1, w2)\n\t\t\tif c > 0.66:\n\t\t\t\tres += c\n\t\t\t# print(w1,w2,c, res)\n\n\treturn sigma(res/max(len(words), len(sentence_words)))\n\nif __name__=='__main__':\n\n\timport pickle\n\ttry:\n\t\tmodel = pickle.load(open('model', 'rb'))\n\texcept FileNotFoundError:\n\t\tmodel = train('uot')\n\t\tpickle.dump(model, open('model', 'wb'))\n\n\t# m = M()\n\n\twords_of_words_initial = [ x for x in open('hands_desc.txt').readlines() ]\n\twords_of_words = []\n\tfor w in words_of_words_initial:\n\t\twords_with_weight = {}\n\t\tw_splitted = [ x for x in re.split('[; ]', w) if x ]\n\t\tprint(w_splitted)\n\t\tfor w1 in w_splitted:\n\t\t\twords_with_weight.update({w1.strip(): 1})\n\t\twords_of_words.append(words_with_weight)\n\t# from pprint import pprint\n\n\t# pprint(words_of_words)\n\t# exit(0)\n\t# words_of_words = [{'робототехника': 1, 'робот': 1, 'деревья': 1, 'избенка': 1}]\n\t# print(unirand(model['$', '$']))\n\tfor words in words_of_words:\n\t\tsent = generate_sentence(words, model)\n\t\tcnt = 0\n\t\twhile compare_sentence(sent, list(words.keys())) < 0.5 and cnt < 1000:\n\t\t\tsent = generate_sentence(words, model)\n\t\t\tcnt += 1\n\t\t\t# if sent == ['.']:\n\t\t\t\t# print(compare_sentence(sent, list(words.keys())))\n\t\t\t\t# exit(0)\n\t\t\t\n\t\tprint(sent, words)\t\n\n","sub_path":"dot2text.py","file_name":"dot2text.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"71400306","text":"from L500analysis.data_io.get_cluster_data import GetClusterData\nfrom L500analysis.utils.utils import aexp2redshift\nfrom L500analysis.plotting.tools.figure_formatting import *\nfrom L500analysis.plotting.profiles.tools.profiles_percentile \\\n import *\nfrom L500analysis.utils.constants import rbins\nfrom derived_field_functions import *\n\ncolor = matplotlib.cm.afmhot_r\nmatplotlib.rcParams['legend.handlelength'] = 0\nmatplotlib.rcParams['legend.numpoints'] = 1\nmatplotlib.rcParams['legend.fontsize'] = 12\naexps = [1.0,0.9,0.8,0.7,0.6,0.5,0.45,0.4,0.35]\ndb_name = 'L500_NR_0'\ndb_dir = '/home/babyostrich/Documents/Repos/L500analysis/'\n\nprofiles_list = ['S_mw', 'r_mid', \n 'S_mw/S500c',\n 'R/R500c']\n\nhalo_properties_list=['r500c','M_total_500c','nu_500c']\n\n\nKratio=r\"$\\tilde{K}=K(R)/K_{500c}$\"\nfKz1=r\"$\\tilde{K}/\\tilde{K}(z=1)$\"\n\npa = PlotAxes(figname='Kmw_r500c',\n axes=[[0.15,0.4,0.80,0.55],[0.15,0.15,0.80,0.24]],\n axes_labels=[Kratio,fKz1],\n ylog=[True,False],\n xlabel=r\"$R/R_{500c}$\",\n xlim=(0.2,5),\n ylims=[(0.1,11),(0.6,1.4)])\n\nTmw={}\nTplots = [Tmw]\nclkeys = ['S_mw/S500c']\nlinestyles = ['-']\n\nfor aexp in aexps :\n cldata = GetClusterData(aexp=aexp,db_name=db_name,\n db_dir=db_dir,\n profiles_list=profiles_list,\n halo_properties_list=halo_properties_list)\n\n for Tplot, key in zip(Tplots,clkeys) :\n Tplot[aexp] = calculate_profiles_mean_variance(cldata[key])\n\n pa.axes[Kratio].plot( rbins, Tmw[aexp]['mean'],color=color(aexp),ls='-',\n label=\"$z=%3.1f$\" % aexp2redshift(aexp))\n\n\n# pa.axes[Kratio].fill_between(rbins, Tmw[0.5]['down'], Tmw[0.5]['up'], \n# color=color(0.5), zorder=0)\n\n \nfor aexp in aexps :\n for T,ls in zip(Tplots,linestyles) :\n fractional_evolution = get_profiles_division_mean_variance(\n mean_profile1=T[aexp]['mean'],\n var_profile1=T[aexp]['var'],\n mean_profile2=T[0.5]['mean'],\n var_profile2=T[0.5]['var'],\n )\n\n\n pa.axes[fKz1].plot( rbins, fractional_evolution['mean'],\n color=color(aexp),ls=ls) \n \n\npa.axes[Kratio].tick_params(labelsize=12)\npa.axes[Kratio].tick_params(labelsize=12)\npa.axes[fKz1].set_yticks(arange(0.6,1.4,0.2))\npa.set_legend(axes_label=Kratio,ncol=3,loc='best', frameon=False)\npa.color_legend_texts(axes_label=Kratio)\n\npa.savefig()\n","sub_path":"plotting/profiles/K_evolution/plot_K_r500c.py","file_name":"plot_K_r500c.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}