diff --git "a/1269.jsonl" "b/1269.jsonl" new file mode 100644--- /dev/null +++ "b/1269.jsonl" @@ -0,0 +1,484 @@ +{"seq_id":"32409365405","text":"#!/usr/bin/env python3\n\nfrom big_query_manager import *\nfrom sql_table_manager import SqlManager\nfrom google.cloud import bigquery\nfrom google.oauth2 import service_account\nimport json\n\nif __name__ == \"__main__\":\n\n with open(\"./bigquery_config.json\") as json_file:\n config = json.load(json_file)\n\n key_path = os.path.abspath(\"./google_api_credentials.json\") \n credentials = service_account.Credentials.from_service_account_file(key_path,\n scopes=[\"https://www.googleapis.com/auth/cloud-platform\"])\n client = bigquery.Client(credentials=credentials,\n project=credentials.project_id)\n\n #Since original table's repository_created_at columns is not of type timestampt it is not queryable\n #So it needs to be cast into timestamp type\n cast_to_timestamp(client= client,\n project_id= config[\"project_id\"],\n dataset_id= config[\"dataset_id\"],\n table_id= config[\"table_id\"],\n target_project_id=config[\"target_project_id\"],\n target_dataset_id=config[\"target_dataset_id\"],\n target_table_id= config[\"target_table_id\"],\n column= config[\"column\"],\n target_column= config[\"target_column\"])\n\n #Sends query qith given date interval and downloads all files from cloud storage\n get_date_range(client= client,\n key_path= key_path,\n project_id= config[\"target_project_id\"],\n dataset_id= config[\"target_dataset_id\"],\n table_id= config[\"target_table_id\"],\n bucket_name= config[\"bucket_name\"],\n from_date= config[\"from_date\"],\n to_date= config[\"to_date\"])\n\n #If you want to quickly check this function u can comment above two functions and run script again\n create_table_str = create_sql_from_table(client= client,\n dataset_id= config[\"target_dataset_id\"],\n table_id= config[\"table_id\"],\n dest_file= config[\"sql_create_script\"])\n\n sqlManager = SqlManager(config_path='./sql_config.json')\n sqlManager.create_database(db_name=config[\"target_table_id\"])\n sqlManager.create_table(create_query=create_table_str)\n #To-do\n # sqlManager.insert_csv_rows(data_dir=\"./github_timeline_test_2009_01_01_2010_12_30\", \n # column_data_path=\"./column_data.json\",\n # table_id=\"github_timeline\")\n ","repo_name":"alpkarakush/BigQueryToSQL","sub_path":"export_bigquery_to_googlestorage.py","file_name":"export_bigquery_to_googlestorage.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"73669621511","text":"import enum\nimport json\nimport re\n\nimport flask\n\noptions = {\n \"date\": {\n \"paydate\": { \"title\": \"Date Paid\" },\n \"expectedpaydate\": { \"title\": \"Expected Pay Date\" },\n \"invoicedate\": { \"title\": \"Invoice Date\" },\n \"dateCreated\": { \"title\": \"Date Created\" },\n \"dateModified\": { \"title\": \"Last Modified\" }\n },\n \"select\": {\n \"paid\": { \n \"options\": {\"all\": \"\", \"paid\": \"2\", \"unpaid\": \"1\", \"overdue\": \"3\"},\n \"title\": \"Payment Status\"\n },\n \"paysource\": {\n \"options\": {\n \"All Methods\": \"-2\",\n \"Cash\": \"CASH\",\n \"EFT\": \"EFT\",\n \"Cheque\": \"CHEQUE\",\n \"Card\": \"CARDRECORD\"\n },\n \"title\": \"Payment Method\"\n },\n \"status\": {\n \"options\": {\n \"All Status\": \"-2\",\n \"Draft\": \"0\",\n \"Open\": \"1\",\n \"Cancelled\": \"3\"\n },\n \"title\": \"Status\"\n },\n \"hasexternalsourceid\": {\n \"options\": { \"Any\": \"-2\", \"No\": \"0\", \"Yes\": \"1\" },\n \"title\": \"Is In Accounting\"\n },\n \"hasduplicatepaymentamount\": {\n \"options\": { \"Any\": \"-2\", \"No\": \"0\", \"Yes\": \"1\" },\n \"title\": \"Has Duplicate Payment Amount\"\n },\n \"overpaid\": {\n \"options\": { \"Any\": \"-2\", \"No\": \"0\", \"Yes\": \"1\" },\n \"title\": \"Overpaid\"\n }\n },\n \"search\": {\n \"invoicenumber\": { \"title\": \"Invoice Number\" },\n \"reference\": { \"title\": \"Reference\" },\n \"title\": { \"title\": \"Title\" },\n \"summary\": { \"title\": \"Summary\" },\n \"terms\": { \"title\": \"Terms\" }\n },\n \"number\": {\n \"subtotal\": { \"title\": \"Sub Total\" },\n \"tax\": { \"title\": \"Tax Amount\" },\n \"total\": { \"title\": \"Total\" },\n \"paid\": { \"title\": \"Amount Paid\" }\n }\n}\n\n\nclass Paid(enum.Enum):\n ALL = 0\n PAID = 1\n UNPAID = 2\n OVERDUE = 3\n\n\nclass InvoiceFilters:\n def __init__(self, options):\n self.options = options\n self.__data = {}\n \n @staticmethod\n def from_request(req: flask.request) -> \"InvoiceFilters\":\n filters = InvoiceFilters(options)\n\n for key in filters.options[\"search\"]:\n seach_term = req.args.get(\"search.\" + key, default=None)\n if seach_term is not None:\n filters.add_search(key, seach_term)\n\n for key in filters.options[\"select\"]:\n selected = req.args.get(\"select.\" + key, default=None)\n if selected is not None and selected in filters.options[\"select\"][key][\"options\"]:\n encoded = filters.options[\"select\"][key][\"options\"][selected]\n filters.add_select(key, encoded)\n\n for key in filters.options[\"date\"]:\n date = req.args.get(\"date.\" + key, default=None)\n if date is not None:\n frm, to, *_ = date.split(\",\")\n filters.add_date(key, frm, to)\n\n for key in filters.options[\"number\"]:\n num = req.args.get(\"number.\" + key, default=None)\n if num is not None:\n frm, to, *_ = num.split(\",\")\n filters.add_number(key, frm, to)\n \n return filters\n \n def to_dict(self):\n if \"paid\" not in self.__data:\n self.add_paid(\"overdue\")\n \n return self.__data\n\n def add_paid(self, paid: str):\n self.__add(\"paid\", paid)\n \n def add_date(self, name, frm, to):\n if frm != \"\":\n self.__add(name + \"-from\", frm)\n if to != \"\":\n self.__add(name + \"-to\", to)\n \n def add_select(self, name, selected):\n self.__add(name, selected)\n\n def add_search(self, name, s):\n self.__add(name, s)\n\n def add_number(self, name, frm, to):\n self.__add(name + \"-toNum\", format_number(to))\n self.__add(name + \"-fromNum\", format_number(frm))\n\n def __add(self, key, value):\n # all filter values are wrapped in an array\n self.__data[key] = [value]\n\n\ndef format_date(date):\n if date is None:\n return \"\"\n\n return date.strftime(\"%d %B %Y\")\n\n\ndef format_number(num):\n if num is None:\n return \"\"\n \n return str(num)\n","repo_name":"christianscott/formitize-api","sub_path":"formitize/invoice.py","file_name":"invoice.py","file_ext":"py","file_size_in_byte":4264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39980300466","text":"import argparse\nimport json\nimport pickle\nfrom pathlib import Path\n\nimport pandas as pd\nfrom autocfr.utils import load_game_configs\nfrom autocfr.evaluator.algorithm_evaluator import AlgorithmEvaluator\n\ndef load_best_algorithm(logid):\n json_file = Path(__file__).parent.parent / \"logs\" / str(logid) / \"metrics.json\"\n with json_file.open(\"r\") as f:\n metrics = json.load(f)\n nas = metrics[\"new_ave_score\"]\n df = pd.DataFrame(data=dict(step=nas[\"steps\"], value=nas[\"values\"]))\n df = df.sort_values(by=\"value\", ascending=False)\n print(df.head(20))\n print(list(df.head(20).iloc[:, 0]))\n algorithm_index = int(df.iloc[0][\"step\"])\n algorithm_file = (\n Path(__file__).parent.parent\n / \"logs\"\n / str(logid)\n / \"valid_algorithms\"\n / \"algorithms_{}.pkl\".format(algorithm_index)\n )\n print(\"Log index: {}, The best algorithm index: {}\".format(logid, algorithm_index))\n with algorithm_file.open(\"rb\") as f:\n algorithm = pickle.load(f)\n return algorithm_index, algorithm\n\n\ndef main():\n args = get_args()\n algorithm_index, algorithm = load_best_algorithm(args.logid)\n game_configs = load_game_configs(mode=\"test\")\n evaluator = AlgorithmEvaluator(\n game_configs,\n algorithm,\n \"Algorithm_{}_{}\".format(args.logid, algorithm_index),\n eval_freq=20,\n print_freq=100,\n num_iters=20000\n )\n evaluator.evaluate()\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description=\"test learned algorithm\")\n parser.add_argument(\"--logid\", type=int, help=\"logid\")\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rpSebastian/AutoCFR","sub_path":"scripts/test_learned_algorithm.py","file_name":"test_learned_algorithm.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"27"} +{"seq_id":"24150495046","text":"# https://www.acmicpc.net/problem/1173\nimport sys\n\nN, m, M, T, R = map(int, sys.stdin.readline().split())\n\nX = m\nexTime = 0\ntotalTime = 0\nwhile True:\n if M - m < T:\n totalTime = -1\n break\n\n totalTime += 1\n if X + T > M:\n X -= R\n if X < m:\n X = m\n else:\n X += T\n exTime += 1\n if exTime == N:\n break\n\nprint(totalTime)","repo_name":"kmg733/CodingTest","sub_path":"BoJ/python/난이도별로 풀기/BRONZE 2/1173_운동.py","file_name":"1173_운동.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25461025380","text":"\"\"\"\r\nFaça um programa que leia um valor N inteiro e positivo, calcule e mostre o valor E,\r\nconforme a fórmula a seguir: E = 1 + 1/1! + 1/2! + 1/3! + 1/4!...+1/N!\r\n\"\"\"\r\n\r\nfrom math import factorial\r\n\r\nnum_final = int(input(\"Digite o termo final da sequência fatorial: \"))\r\nsoma = 1\r\n\r\nfor n in range(1, num_final + 1):\r\n soma += 1 / factorial(n)\r\n\r\nprint(f\"O resultado de E é igual a: {soma:.2f} \")","repo_name":"Viccari073/exercises_for_range_while","sub_path":"exer_estruturas_de_repeticao_28.py","file_name":"exer_estruturas_de_repeticao_28.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1422795515","text":"\r\n\r\nsecret_number = 5\r\nguess_count = 0\r\nguess_limit = 3\r\n\r\n\r\n\r\nprint('Hey, WELCOME')\r\nstart_value = input('Press 0 to start the game!!!!!')\r\n\r\n\r\n\r\n\r\n\r\nif start_value == '0':\r\n while guess_count < guess_limit:\r\n Guess = int(input('Choose a number from 1 to 10'))\r\n guess_count += 1\r\n\r\n if Guess == secret_number:\r\n print(\"You won!!!!!\")\r\n break\r\n\r\n else:\r\n print('You Lose!!!!!!')\r\n\r\n\r\n\r\n\r\nelse:\r\n raise ValueError('Press 0')\r\n","repo_name":"cluxssy/games","sub_path":"Guessing Game.py","file_name":"Guessing Game.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16343192453","text":"\"\"\"\n@Author: Kasugano Sora\n@Github: https://github.com/jiangyuxiaoxiao\n@Date: 2023/09/27-10:34\n@Desc: BertVits2封装\n@Ver : 1.0.0\n\"\"\"\nimport aiohttp\nimport asyncio\nimport aiofiles\nfrom Hiyori.Utils.API.BertVits.config import bertVitsConfig\nfrom Hiyori.Utils.API.Baidu.OpenTranslate import Translate\n\n\ndef getBV_Map() -> dict:\n \"\"\"获取角色名——(model_id,chr_id)映射\"\"\"\n chrDict: dict[str, dict[str, int]] = dict()\n for index, model in enumerate(bertVitsConfig.models):\n for name, cid in model[\"spk2id\"].items():\n chrDict[name] = {\n \"mid\": index,\n \"cid\": cid\n }\n return chrDict\n\n\ndef getModelsConfig() -> list:\n return bertVitsConfig.models\n\n\nasync def getVoice(text: str, model: int | str, character: int | str, sdp_ratio: float = 0.2,\n noise: float = 0.2, noisew: float = 0.9,\n length: float = 1.0, url=None) -> bytes | None:\n \"\"\"\n 获取bertVits语音(TTS)\n\n :param text: 待转换文本\n :param model: 当为int时为模型索引id,当为str时为模型名\n :param character: 当为int时为角色索引id,当为str时为角色名\n :param sdp_ratio:\n :param noise:\n :param noisew:\n :param length:\n :param url: 临时的url\n :return: 音频字节\n \"\"\"\n if url is None:\n url = f\"{bertVitsConfig.host}:{bertVitsConfig.port}/voice\"\n bv_model = None\n model_id = 0\n if isinstance(model, int):\n model_id = model\n if model_id >= len(bertVitsConfig.models):\n # 无效模型\n return None\n bv_model = bertVitsConfig.models[model_id]\n elif isinstance(model, str):\n for index, m in enumerate(bertVitsConfig.models):\n if model in m[\"names\"]:\n bv_model = m\n model_id = index\n break\n if bv_model is None:\n return None\n else:\n raise TypeError(\"model should be a str or int value\")\n\n if isinstance(character, int):\n chr_id = character\n elif isinstance(character, str):\n if character not in bv_model[\"spk2id\"].keys():\n return None\n chr_id = bv_model[\"spk2id\"][character]\n else:\n raise TypeError(\"character should be a str or int value\")\n\n # 检查是否需要翻译\n if \"trans\" in bv_model:\n trans = bv_model[\"trans\"]\n texts = text.split(\"\\n\")\n outs = []\n for t in texts:\n if t != \"\":\n out = await Translate(Sentence=t, to_Language=trans)\n outs.append(out)\n else:\n outs.append(t)\n text = \"\\n\".join(outs)\n\n params = {\n \"model_id\": model_id,\n \"chr_id\": chr_id,\n \"text\": text,\n \"sdp_ratio\": sdp_ratio,\n \"noise\": noise,\n \"noisew\": noisew,\n \"length\": length\n }\n async with aiohttp.ClientSession() as session:\n async with session.get(url, params=params) as response:\n if response.status == 200:\n response = await response.read()\n return response\n return None\n\n\nasync def saveVoice(savePath: str, text: str, model: int | str, chr: int | str, sdp_ratio: float = 0.2,\n noise: float = 0.2, noisew: float = 0.9,\n length: float = 1.0) -> bool:\n \"\"\"保存音频文件至本地\"\"\"\n audio = await getVoice(text, model, chr, sdp_ratio, noise, noisew, length)\n if audio is None:\n return False\n async with aiofiles.open(savePath, 'wb') as f:\n await f.write(audio)\n return True\n\n\nif __name__ == '__main__':\n asyncio.run(saveVoice(\"Data/Test/1.wav\", \"\",\n 1, \"顾真真\"))\n","repo_name":"jiangyuxiaoxiao/Hiyori","sub_path":"Hiyori/Utils/API/BertVits/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"27"} +{"seq_id":"26798719523","text":"\"\"\"Computes what the failure modes were, and then stores this data in the\ngraphs.\"\"\"\nfrom typing import Dict, List, Tuple\n\nimport networkx as nx\nfrom snnalgorithms.sparse.MDSA.alg_params import get_algorithm_setting_name\nfrom typeguard import typechecked\n\nfrom snncompare.exp_config import Exp_config\nfrom snncompare.graph_generation.stage_1_create_graphs import (\n load_input_graph_from_file_with_init_props,\n)\nfrom snncompare.helper import get_snn_graph_name\nfrom snncompare.import_results.load_stage_1_and_2 import load_simsnn_graphs\nfrom snncompare.process_results.helper import graph_of_run_config_passed\nfrom snncompare.run_config.Run_config import Run_config\n\n# from dash.dependencies import Input, Output\n\n\n# pylint: disable=R0902\nclass Failure_mode_entry:\n \"\"\"Contains a list of neuron names.\"\"\"\n\n # pylint: disable=R0913\n # pylint: disable=R0903\n @typechecked\n def __init__(\n self,\n adaptation_name: str,\n incorrectly_spikes: bool,\n incorrectly_silent: bool,\n incorrect_u_increase: bool,\n incorrect_u_decrease: bool,\n neuron_names: List[str],\n run_config: Run_config,\n timestep: int,\n ) -> None:\n \"\"\"Stores a failure mode entry.\n\n Args:\n adaptation_name (str): The name of the adaptation.\n incorrectly_spikes (bool): Indicates if the neurons spiked\n incorrectly.\n neuron_names (List[str]): List of neuron names.\n run_config (Run_config): The run configuration.\n timestep (int): The timestep at which the failure mode occurred.\n \"\"\"\n self.adaptation_name: str = adaptation_name\n self.incorrectly_spikes: bool = incorrectly_spikes\n self.incorrectly_silent: bool = incorrectly_silent\n self.incorrect_u_increase: bool = incorrect_u_increase\n self.incorrect_u_decrease: bool = incorrect_u_decrease\n self.neuron_names: List = neuron_names\n self.run_config: Run_config = run_config\n self.timestep: int = timestep\n\n\n# pylint: disable=R0903\n# pylint: disable=R0902\nclass Table_settings:\n \"\"\"Creates the object with the settings for the Dash table.\"\"\"\n\n @typechecked\n def __init__(\n self,\n exp_config: Exp_config,\n run_configs: List[Run_config],\n ) -> None:\n \"\"\"Stores the Dash failure-mode plot settings.\n\n Args:\n exp_config (Exp_config): The experiment configuration.\n run_configs (List[Run_config]): List of run configurations.\n \"\"\"\n\n self.exp_config: Exp_config = exp_config\n self.run_configs: List[Run_config] = run_configs\n # Dropdown options.\n self.seeds = exp_config.seeds\n\n self.graph_sizes = list(\n map(\n lambda size_and_max_graphs: size_and_max_graphs[0],\n exp_config.size_and_max_graphs,\n )\n )\n\n self.algorithm_setts = []\n\n for algorithm_name, algo_specs in exp_config.algorithms.items():\n for algo_config in algo_specs:\n self.algorithm_setts.append(\n get_algorithm_setting_name(\n algorithm_setting={algorithm_name: algo_config}\n )\n )\n\n self.adaptation_names = []\n for adaptation in exp_config.adaptations:\n self.adaptation_names.append(\n f\"{adaptation.adaptation_type}_{adaptation.redundancy}\"\n )\n\n self.run_config_and_snns: List[\n Tuple[Run_config, Dict]\n ] = self.create_failure_mode_tables()\n\n @typechecked\n def create_failure_mode_tables(\n self,\n ) -> List[Tuple[Run_config, Dict]]:\n \"\"\"Returns the failure mode data for the selected settings.\n\n Returns:\n A list of tuples containing the run configuration and the failure\n mode data.\n \"\"\"\n run_config_and_snns: List[Tuple[Run_config, Dict]] = []\n print(\"Creating failure mode table.\")\n for i, run_config in enumerate(self.run_configs):\n snn_graphs: Dict = {}\n input_graph: nx.Graph = load_input_graph_from_file_with_init_props(\n run_config=run_config\n )\n print(\n f\"{i}/{len(self.run_configs)},{run_config.adaptation.__dict__}\"\n )\n\n for with_adaptation in [False, True]:\n for with_radiation in [False, True]:\n graph_name: str = get_snn_graph_name(\n with_adaptation=with_adaptation,\n with_radiation=with_radiation,\n )\n snn_graphs[graph_name] = load_simsnn_graphs(\n run_config=run_config,\n input_graph=input_graph,\n with_adaptation=with_adaptation,\n with_radiation=with_radiation,\n stage_index=7,\n )\n run_config_and_snns.append((run_config, snn_graphs))\n return run_config_and_snns\n\n # pylint: disable=R0912\n # pylint: disable=R0913\n # pylint: disable=R0914\n @typechecked\n def get_failure_mode_entries(\n self,\n first_timestep_only: bool,\n seed: int,\n graph_size: int,\n algorithm_setting: str,\n show_spike_failures: bool,\n ) -> List[Failure_mode_entry]:\n \"\"\"Returns the failure mode data for the selected settings.\n\n Args:\n seed: The seed value.\n graph_size: The size of the graph.\n algorithm_setting: The algorithm setting.\n\n Returns:\n A list of failure mode entries.\n\n Raises:\n ValueError: If the run configurations are not equal.\n \"\"\"\n failure_mode_entries: List[Failure_mode_entry] = []\n\n # Loop over the combination of run_config and accompanying snn graphs.\n for run_config, snn_graphs in self.run_config_and_snns:\n # Read the failure modes from the graph object.\n failure_run_config, failure_mode = (\n run_config,\n snn_graphs[\"rad_adapted_snn_graph\"].network.graph.graph[\n \"failure_modes\"\n ],\n )\n if run_config != failure_run_config:\n raise ValueError(\"Error, run configs not equal.\")\n\n # Check if the run config settings are desired.\n run_config_algorithm_name: str = get_algorithm_setting_name(\n algorithm_setting=run_config.algorithm\n )\n adaptation_name: str = (\n f\"{run_config.adaptation.adaptation_type}_\"\n + f\"{run_config.adaptation.redundancy}\"\n )\n\n if (\n run_config.seed == seed\n and run_config.graph_size == graph_size\n and run_config_algorithm_name == algorithm_setting\n and not graph_of_run_config_passed(\n graph_name=\"rad_adapted_snn_graph\",\n run_config=run_config,\n )\n ):\n get_failure_mode_obj(\n adaptation_name=adaptation_name,\n failure_mode=failure_mode,\n failure_mode_entries=failure_mode_entries,\n first_timestep_only=first_timestep_only,\n run_config=run_config,\n show_spike_failures=show_spike_failures,\n )\n\n return failure_mode_entries\n\n\n@typechecked\ndef get_failure_mode_obj(\n *,\n adaptation_name: str,\n failure_mode: Dict,\n failure_mode_entries: List[Failure_mode_entry],\n first_timestep_only: bool,\n run_config: Run_config,\n show_spike_failures: bool,\n) -> None:\n \"\"\"Parses input data to return a Failure mode object, containing the\n difference between the radiated and unradiated SNN.\"\"\"\n\n @typechecked\n def create_failure_mode_entry(\n incorrectly_spikes: bool,\n incorrectly_silent: bool,\n incorrect_u_increase: bool,\n incorrect_u_decrease: bool,\n neuron_list: List[str],\n ) -> Failure_mode_entry:\n \"\"\"Returns a Failure mode object, containing the difference between the\n radiated and unradiated SNN.\"\"\"\n return Failure_mode_entry(\n adaptation_name=adaptation_name,\n incorrectly_spikes=incorrectly_spikes,\n incorrectly_silent=incorrectly_silent,\n incorrect_u_increase=incorrect_u_increase,\n incorrect_u_decrease=incorrect_u_decrease,\n neuron_names=neuron_list,\n run_config=run_config,\n timestep=int(timestep),\n )\n\n @typechecked\n def append_failure_mode_entry(\n failure_mode_entry: Failure_mode_entry,\n ) -> None:\n if first_timestep_only:\n failure_mode_entries.append(failure_mode_entry)\n else:\n # Optionally handle first timestep only logic here\n print(\"passing\")\n\n if show_spike_failures:\n if \"incorrectly_silent\" in failure_mode:\n for timestep, neuron_list in failure_mode[\n \"incorrectly_silent\"\n ].items():\n failure_mode_entry = create_failure_mode_entry(\n False, True, False, False, neuron_list\n )\n append_failure_mode_entry(failure_mode_entry)\n\n if \"incorrectly_spikes\" in failure_mode:\n for timestep, neuron_list in failure_mode[\n \"incorrectly_spikes\"\n ].items():\n failure_mode_entry = create_failure_mode_entry(\n True, False, False, False, neuron_list\n )\n append_failure_mode_entry(failure_mode_entry)\n else:\n if \"inhibitory_delta_u\" in failure_mode:\n for timestep, neuron_list in failure_mode[\n \"inhibitory_delta_u\"\n ].items():\n failure_mode_entry = create_failure_mode_entry(\n False, False, False, True, neuron_list\n )\n append_failure_mode_entry(failure_mode_entry)\n\n if \"excitatory_delta_u\" in failure_mode:\n for timestep, neuron_list in failure_mode[\n \"excitatory_delta_u\"\n ].items():\n failure_mode_entry = create_failure_mode_entry(\n False, False, True, False, neuron_list\n )\n","repo_name":"a-t-0/snncompare","sub_path":"src/snncompare/process_results/Table_settings.py","file_name":"Table_settings.py","file_ext":"py","file_size_in_byte":10469,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"32117349865","text":"from django import forms\nfrom django.contrib.flatpages.models import FlatPage\nfrom django.contrib.sites.models import Site\nfrom django.core.cache import cache\nfrom django.urls import reverse\n\nimport posts.settings as posts_settings\nfrom posts.models import Follow, Group, Post\nfrom posts.tests.test_settings import AllSettings\n\n\nclass Addition(AllSettings):\n def setUp(self):\n super().setUp()\n site = Site.objects.get(pk=1)\n self.flat_about = FlatPage.objects.create(\n url='/about-author/',\n title='about',\n content='content'\n )\n self.flat_spec = FlatPage.objects.create(\n url='/about-spec/',\n title='about spec',\n content='content'\n )\n self.flat_about.sites.add(site)\n self.flat_spec.sites.add(site)\n\n def check_context_form(self, response):\n \"\"\"\n The function checks the context of the form\n\n The entrance accepts:\n ~ response - received request response\n \"\"\"\n list_field = {\n 'text': forms.CharField,\n 'group': forms.ChoiceField\n }\n for value, expected in list_field.items():\n with self.subTest(value=value):\n form_field = response.context.get('form').fields.get(value)\n self.assertIsInstance(form_field, expected)\n\n def check_context_page(self, response, check_with, expected_count):\n \"\"\"\n The function checks context ['page']\n\n The entrance accepts:\n ~ response - the result of the request\n ~ check_with - what to compare the first post from page to\n ~ expected_count - how many posts should be on one page\n \"\"\"\n page = response.context['page']\n first_item = page[0]\n page_len = len(page)\n\n self.assertEqual(first_item, check_with)\n self.assertEqual(page_len, expected_count)\n\n\nclass ViewsTest(Addition):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n for i in range(15):\n Post.objects.create(\n author=cls.user,\n text=f'Текст поста {i}',\n group=cls.group,\n )\n\n for i in range(15):\n Group.objects.create(\n title='Тестовый title',\n slug=f'groups-{i}',\n description='Тестовый description'\n )\n\n for i in range(15):\n Post.objects.create(\n author=cls.user_2,\n text=f'Текст поста автора {i}',\n group=cls.group,\n )\n\n def test_show_correct_context_index(self):\n response = self.authorized_client.get(reverse('posts:index'))\n\n count_posts_all = response.context['paginator'].count\n\n self.check_context_page(response, self.post,\n posts_settings.NUMBER_ITEM_PAGINATOR_POST)\n self.assertEqual(count_posts_all, Post.objects.count())\n\n def test_show_correct_follow_index(self):\n self.follow_1 = Follow.objects.create(\n user=self.user,\n author=self.user_2\n )\n response = self.authorized_client.get(reverse('posts:follow_index'))\n\n count_posts_all = response.context['paginator'].count\n\n self.check_context_page(response, self.posts_follow,\n posts_settings.NUMBER_ITEM_PAGINATOR_POST)\n self.assertEqual(count_posts_all, self.user_2.posts.count())\n\n def test_show_correct_follow_index_not_following(self):\n self.follow_1 = Follow.objects.create(\n user=self.user,\n author=self.user_2\n )\n response = self.authorized_client_3.get(reverse('posts:follow_index'))\n\n count_posts_all = response.context['paginator'].count\n\n self.assertEqual(count_posts_all, 0)\n\n def test_show_correct_context_group(self):\n response = self.authorized_client.get(\n reverse('posts:group_posts', args=[self.group.slug])\n )\n\n group = response.context['group']\n\n self.check_context_page(response, self.post,\n posts_settings.NUMBER_ITEM_PAGINATOR_POST)\n self.assertEqual(group, self.group)\n\n def test_show_correct_context_groups(self):\n response = self.authorized_client.get(reverse('posts:groups'))\n\n self.check_context_page(\n response,\n self.group,\n posts_settings.NUMBER_ITEM_PAGINATOR_ALL_GROUPS\n )\n\n def test_show_correct_context_new_post(self):\n response = self.authorized_client.get(reverse('posts:new_post'))\n\n self.check_context_form(response)\n\n def test_show_correct_context_group_without_post(self):\n response = self.authorized_client.get(\n reverse('posts:group_posts', args=[self.group_without_post.slug])\n )\n\n paginator_len = response.context['paginator'].count\n\n self.assertEqual(paginator_len, 0)\n\n def test_show_correct_context_edit(self):\n response = self.authorized_client.get(\n reverse('posts:post_edit', args=[self.user, self.post.id]))\n\n post = response.context['post']\n\n self.assertEqual(post, self.post)\n self.check_context_form(response)\n\n def test_show_correct_context_profile(self):\n response = self.authorized_client.get(\n reverse('posts:profile', args=[self.user])\n )\n\n author = response.context['author']\n\n self.check_context_page(response, self.post,\n posts_settings.NUMBER_ITEM_PAGINATOR_POST)\n self.assertEqual(author, self.user)\n\n def test_show_correct_context_post(self):\n response = self.authorized_client.get(\n reverse('posts:post', args=[self.user, self.post.id])\n )\n\n post = response.context['post']\n\n self.assertEqual(post, self.post)\n\n def test_show_correct_context_flatpages(self):\n list_content_flatpage = {\n 'about': self.flat_about.content,\n 'terms': self.flat_spec.content\n }\n\n for reverse_name, contents in list_content_flatpage.items():\n with self.subTest():\n response = self.authorized_client.get(reverse(reverse_name))\n self.assertEqual(\n response.context['flatpage'].content,\n contents\n )\n\n def test_cash(self):\n response = self.authorized_client.get(reverse('posts:index'))\n should_be_content = response.content\n Post.objects.create(\n text='Просто текст',\n author=self.user\n )\n\n response = self.authorized_client.get(reverse('posts:index'))\n content_without_new_post = response.content\n\n cache.clear()\n response = self.authorized_client.get(reverse('posts:index'))\n content_with_new_post = response.content\n\n self.assertEqual(content_without_new_post, should_be_content)\n self.assertNotEqual(content_with_new_post, should_be_content)\n\n\nclass FollowTest(Addition):\n def test_follow(self):\n follow_count = Follow.objects.count()\n response = self.authorized_client_2.get(\n reverse('posts:profile_follow', args=[self.user])\n )\n\n self.assertRedirects(\n response,\n reverse('posts:profile', args=[self.user])\n )\n\n self.assertEqual(Follow.objects.count(), follow_count + 1)\n follow = Follow.objects.last()\n self.assertEqual(follow.user, self.user_2)\n self.assertEqual(follow.author, self.user)\n\n def test_unfollow(self):\n Follow.objects.create(\n user=self.user,\n author=self.user_2\n )\n response = self.authorized_client.get(\n reverse('posts:profile_unfollow', args=[self.user_2])\n )\n\n self.assertRedirects(\n response,\n reverse('posts:profile', args=[self.user_2])\n )\n self.assertEqual(Follow.objects.count(), 0)\n\n# class LikeTest(Addition):\n# def test_like(self):\n# like_count = Like.objects.count()\n#\n# response = self.authorized_client_2.get(\n# reverse('posts:like_or_unlike', args=[self.user, self.post.id])+'?next='+reverse('posts:profile', args=[self.user.username])\n# )\n#\n# self.assertRedirects(\n# response,\n# reverse(response.request['QUERY_STRING'].split('=')[1])\n# )\n# #\n# # self.assertEqual(Follow.objects.count(), follow_count + 1)\n# # like = Like.objects.last()\n# # self.assertEqual(follow.user, self.user_2)\n# # self.assertEqual(follow.author, self.user)\n","repo_name":"FlowHack/yatube","sub_path":"posts/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":8779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"35879266267","text":"import datetime\n\nfrom Functions import *\n\n\ndef add_interval(intervals, interval, five):\n '''\n This functions links a five to an interval adding it to the intervals list\n - intervals: intervals of playing fives (dictionary of {tuple: set})\n - interval: interval of the game without substitutions (tuple: (string, string))\n - five: set of players (set)\n '''\n intervals[interval] = five\n\n\ndef check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals):\n '''\n This function is launched to check whether the presence of the player was already detected. In\n case it was not, it adds it to the players on court and to the previous fives if needed\n - team: team of the player, either 1 or 2 (string)\n - player: name of the player (string)\n - Q: current quarter (string)\n - oncourt: players on court (list of dictionaries {player: string})\n - tempOncourtIntervals: players on court for each interval without substitutions waiting to be completed (dictionary of {tuple: set of strings})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n '''\n if player != \"-\":\n # we check the player is in the current playing list:\n if player not in oncourt[team-1]:\n clock = quarter_start_time(Q)\n oncourt[team-1][player] = string_from_time(clock)\n # we add the player to previous incomplete fives:\n if len(tempOncourtIntervals[team-1]) > 0:\n toDelete = []\n for interval in tempOncourtIntervals[team-1]:\n tempOncourtIntervals[team-1][interval].add(player)\n # if any five is now complete we add it to the definitive dictionary and delete them from the temporal one:\n if len(tempOncourtIntervals[team-1][interval]) == 5:\n add_interval(oncourtIntervals[team-1], interval, tempOncourtIntervals[team-1][interval])\n toDelete.append(interval)\n for interval in toDelete:\n del tempOncourtIntervals[team-1][interval]\n\n\ndef quarter_end(Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub):\n '''\n This function is launched every time a quarter end is detected.\n It treats the quarter end as a substitution, as the five players can be completely new at the next quarter\n - Q: quarter that has just ended (string)\n - oncourt: players on court at the time of the action (list of dictionaries {player: string})\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n - lastSub: time of the last substitution (string)\n '''\n # we add the minutes of the players that end the quarter (as it is usually done when they are substituted):\n clock = quarter_end_time(Q)\n clock = string_from_time(clock)\n for team in range(1,3):\n for interval in tempOncourtIntervals[team-1]:\n add_interval(oncourtIntervals[team-1], interval, tempOncourtIntervals[team-1][interval])\n \n for player in oncourt[team-1]:\n if player not in playerIntervals[team-1].keys():\n playerIntervals[team-1][player] = []\n playerIntervals[team-1][player].append((oncourt[team-1][player], clock))\n add_interval(oncourtIntervals[team-1], (lastSub[team-1], clock), set(oncourt[team-1]))\n \n # we delete current variables as the five players can be completely new at the next quarter:\n oncourt[team-1].clear()\n tempOncourtIntervals[team-1].clear()\n lastSub[team-1] = string_from_time(quarter_start_time(next_quarter(Q)))\n\n\ndef quarter_check(action, prevQ, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub):\n '''\n This function is launched to detect a change of quarter. If it is the case, quarter_end is launched\n - action: play that we are going to study (list)\n - prevQ: quarter of the previous action (string)\n - oncourt: players on court at the time of the action (list of dictionaries {player: string})\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - tempOncourtIntervals: players on court for each interval without substitutions waiting to be completed (dictionary of {tuple: set of strings})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n - lastSub: time of the last substitution (string)\n Output: quarter of the action (string)\n '''\n clock = action[0]\n Q = quarter_from_time(clock)\n if prevQ != Q:\n quarter_end(prevQ, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n return Q\n\n\ndef substitution(action, Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub):\n '''\n Treatment of an action that was detected as a substitution. It will have the following structure:\n clock team player playerOut playerIn\n The substitution will mean the end of a five and the start of another one\n - action: studied play (list)\n - Q: quarter of the action (string)\n - oncourt: players on court at the time of the action (list of dictionaries {player: string})\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - tempOncourtIntervals: players on court for each interval without substitutions waiting to be completed (dictionary of {tuple: set of strings})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n - lastSub: time of the last substitution (string)\n '''\n clock, team, playerOut, playerIn = action[0], int(action[1]), action[2], action[4]\n check_oncourt(team, playerOut, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n Q, minutes, seconds = clock.split(\":\")\n clock = Q + \":\" + datetime.time(0, int(minutes), int(seconds)).strftime(\"%M:%S\")\n\n # playerIntervals treatment: player played from oncourt[team-1][playerOut] until clock\n if playerOut not in playerIntervals[team-1].keys():\n playerIntervals[team-1][playerOut] = []\n playerIntervals[team-1][playerOut].append((oncourt[team-1][playerOut], clock))\n\n if clock != lastSub[team-1]: # to avoid adding fives in the middle of consecutive substitutions\n if len(oncourt[team-1]) == 5: # if the five is complete, we send it to the definitive list\n add_interval(oncourtIntervals[team-1], (lastSub[team-1], clock), set(oncourt[team-1]))\n else: # if the five is incomplete, we send it to the temporal list\n add_interval(tempOncourtIntervals[team-1], (lastSub[team-1], clock), set(oncourt[team-1]))\n del oncourt[team-1][playerOut]\n oncourt[team-1][playerIn] = clock\n lastSub[team-1] = clock\n\n\ndef treat_line(line, prevQ, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub):\n '''\n This function is launched to detect the type of play an action is and treat it in case it is a shot\n - line: action that we are going to study (string)\n - prevQ: quarter of the previous action (string)\n - oncourt: players on court at the time of the action (list of dictionaries {player: string})\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - tempOncourtIntervals: players on court for each interval without substitutions waiting to be completed (dictionary of {tuple: set of strings})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n - lastSub: time of the last substitution (string)\n Output: quarter of the action (string)\n '''\n action = line.split(\", \")\n\n Q = quarter_check(action, prevQ, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n if len(action) > 3 and action[3] == \"S\": # there can be either one or two players\n team, player = int(action[1]), action[2]\n check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n distGiven = action[5] != \"I\" and action[5] != \"O\" # true if it is not I or O, so in this position we have the distance\n if len(action) == 8+distGiven and action[6+distGiven] == \"A\": # there is an assist\n assistant = action[7+distGiven]\n check_oncourt(team, assistant, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n elif len(action) > 3 and (action[3] == \"R\" or action[3] == \"T\"): # there is only one player\n team, player = int(action[1]), action[2]\n check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n elif len(action) > 3 and (action[3] == \"St\" or action[3] == \"B\"): # there are two players\n team, player, receiver = int(action[1]), action[2], action[4]\n check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n opTeam = other_team(team)\n check_oncourt(opTeam, receiver, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n elif len(action) > 3 and action[3] == \"F\": # there can be either one or two players\n team, player, kind = int(action[1]), action[2], action[4]\n if kind != \"T\":\n check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n if len(action) == 6: # there is a player from the opposite team that receives the foul\n receiver = action[5]\n opTeam = other_team(team)\n check_oncourt(opTeam, receiver, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n elif len(action) > 3 and action[3] == \"Su\":\n substitution(action, Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n return Q\n\n\ndef main(file):\n '''\n This function returns the playing intervals for every player and the 5 on court for each interval\n - file: play-by-play input file (string)\n Output:\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n '''\n playerIntervals = [{}, {}]\n oncourt = [{}, {}]\n tempOncourtIntervals = [{}, {}]\n oncourtIntervals = [{}, {}]\n lastSub = [\"1Q:12:00\", \"1Q:12:00\"]\n Q = \"1Q\"\n\n with open(file, encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines:\n line = line.strip()\n Q = treat_line(line, Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n quarter_end(Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n\n return playerIntervals, oncourtIntervals","repo_name":"XavierRubiesCullell/Basketball-information-extraction-from-play-by-play-data","sub_path":"Code/PlayingIntervals.py","file_name":"PlayingIntervals.py","file_ext":"py","file_size_in_byte":10904,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"2044793358","text":"# Python\nfrom typing import Optional, Dict, List\nfrom enum import Enum\nfrom uuid import UUID\nfrom datetime import date, datetime\n\n\n# Pydantic\nfrom pydantic import BaseModel\nfrom pydantic import SecretStr\nfrom pydantic import EmailStr\nfrom pydantic import Field\n\n\n# FastAPI\nfrom fastapi import FastAPI, status\nfrom fastapi import Body, Path\nfrom fastapi import HTTPException\n\napp = FastAPI()\napp.title = \"Library\"\napp.version = \" 0.0.1\"\n\n\n# Modes\nclass ReadingAge(Enum):\n yearsDefault = \"No defined\"\n years1_3 = \"1 - 3 years\"\n years4_7 = \"4 - 7 years\"\n years8_10 = \"8 - 10 years\"\n years11_14 = \"11 - 14 years\"\n years15_17 = \"15 - 17 years\"\n years18 = \"older than 18\"\n\n\nclass Language(Enum):\n default = \"No defined\"\n english = \"english\"\n spanish = \"spanish\"\n french = \"french \"\n german = \"german \"\n\n\nclass BookBase(BaseModel):\n '''\n Class base of books\n '''\n title: str = Field(\n ...,\n min_length=1,\n max_length=100,\n example=\"A Monster Calls\"\n )\n author: str = Field(\n ...,\n min_length=1,\n max_length=50,\n example=\"Patrick Ness\"\n )\n reading_age: Optional[ReadingAge] = Field(\n default=ReadingAge.yearsDefault,\n example=ReadingAge.years18\n )\n pages: Optional[int] = Field(\n default=None,\n ge=1,\n le=10000,\n example=128\n )\n language: Optional[Language] = Field(\n default=Language.default,\n example=Language.english\n )\n publisher: Optional[str] = Field(\n default=None,\n min_length=1,\n max_length=50,\n example=\"Candlewick\"\n )\n date_add: datetime = Field(default=datetime.now())\n date_update: Optional[datetime] = Field(default=None)\n\n\nclass Book(BookBase):\n isbn_10: str = Field(\n ...,\n min_length=10,\n max_length=12,\n example=\"0763692158\"\n )\n id_book: UUID = Field(...)\n\n\nclass BookOut(BookBase):\n '''\n Books as response\n '''\n pass\n\n\nclass AuthorBase(BaseModel):\n full_name: str = Field(\n ...,\n min_length=1,\n max_length=50,\n example=\"Patrick Ness\"\n )\n birthdate: Optional[date] = Field(\n default=None,\n example='1998-06-23'\n )\n nationality: Optional[str] = Field(\n default=None,\n min_length=1,\n max_length=120,\n example='American-British'\n )\n genre: Optional[str] = Field(\n default=None,\n min_length=1,\n max_length=120,\n example='Young adult'\n )\n\n\nclass Author(AuthorBase):\n id_author: UUID = Field(...)\n\n\nclass AuthorOut(AuthorBase):\n pass\n\n\nclass LoginBase(BaseModel):\n username: str = Field(\n ...,\n max_length=20,\n example=\"lita2021\"\n )\n email: EmailStr = Field(\n ...,\n )\n message: str = Field(\n default=\"Login Succesfully!\"\n )\n\n\nclass Login(LoginBase):\n password: SecretStr = Field(\n ...,\n min_length=8,\n max_length=64\n )\n\n\nclass LoginOut(LoginBase):\n pass\n\n\n# Home\n@app.get(\n path=\"/\",\n status_code=status.HTTP_200_OK,\n tags=[\"Home\"]\n )\ndef home() -> Dict:\n return {\"Hello\": \"World\"}\n\n\n# User\n# Register a user\n@app.post(\n path=\"/signup\",\n response_model=LoginOut,\n status_code=status.HTTP_201_CREATED,\n summary=\"Register a User\",\n tags=[\"Login\"]\n)\ndef signup():\n pass\n\n\n# Login a user\n@app.post(\n path=\"/login\",\n response_model=LoginOut,\n status_code=status.HTTP_200_OK,\n summary=\"Login a User\",\n tags=[\"Login\"]\n)\ndef login():\n pass\n\n\n# Books\n# Create a book\n@app.post(\n path=\"/book/new\",\n response_model=BookOut,\n status_code=status.HTTP_201_CREATED,\n tags=[\"Book\"],\n summary=\"Create a new book and return it\"\n )\ndef create_book(book: Book = Body(...)):\n \"\"\"\n \"Create a new book\"\n\n - Args:\n book (Book): Book = Body(...)\n\n - Returns:\n The book object that was passed in.\n \"\"\"\n return book\n\n\nbooks_id = [1, 2, 3, 4, 5, 6, 7, 8, 9] # books ID\n\n\n# Show a book\n@app.get(\n path=\"/book/{id_book}\",\n status_code=status.HTTP_200_OK,\n response_model=BookOut,\n tags=[\"Book\"],\n summary=\"Show a book\"\n )\ndef show_book_path(\n id_book: int = Path(\n ...,\n title=\"Code book\",\n gt=0,\n example=7\n )\n):\n \"\"\"\n \"Check a book in library\"\n It returns a dictionary with the id_book as the\n key and a string as the value. The id_book is an\n integer that is greater than 0 and the example value is 112233.\n If the id_book is not in the id_book list, then it raises\n an HTTPException with a status code of 404 and a detail message.\n\n - Args:\n id_book (int): int = Path(\n\n - Returns:\n A dictionary with the id_book as the key and a string as the value.\n \"\"\"\n if id_book not in books_id:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"¡This book is not in our library\"\n )\n return {id_book: \"It exists!\"}\n\n\n# Show all books\n@app.get(\n path=\"/books\",\n response_model=List[BookOut],\n status_code=status.HTTP_200_OK,\n summary=\"Show all books\",\n tags=[\"Book\"]\n)\ndef show_all_books():\n pass\n\n\n# Delete a book\n@app.delete(\n path=\"/book/{id_book}/delete\",\n response_model=BookOut,\n status_code=status.HTTP_200_OK,\n summary=\"Delete a book\",\n tags=[\"Book\"]\n)\ndef delete_a_book():\n pass\n\n\n# Update a book\n@app.put(\n path=\"/book/update_book/{id_book}/{isbn_10}\",\n status_code=status.HTTP_200_OK,\n tags=[\"Book\"],\n summary=\"Updates a book\"\n )\ndef update_book(\n id_book: int = Path(\n ...,\n title=\"Code book\",\n gt=0,\n example=7\n ),\n isbn_10: str = Path(\n ...,\n title=\"book ID (ISBN-10)\",\n description=\"Code ISBN-10\",\n min_length=10,\n max_length=12,\n example=\"0111112229\"\n ),\n book: Book = Body(...)\n):\n \"\"\"\n \"Updates a book and returns it\"\n\n - Args:\n code_book (int): The ID of the book to be updated.\n book (Book): A `Book` object with the updated information.\n\n - Returns:\n dict: A dictionary with the updated book information.\n \"\"\"\n results = book.dict()\n results.update({'isbn_10': isbn_10})\n return results\n\n\n# Author\n# Create an author\n@app.post(\n path=\"/author/new\",\n response_model=AuthorOut,\n status_code=status.HTTP_201_CREATED,\n tags=[\"Author\"],\n summary=\"Create a new author\"\n )\ndef create_author(author: Author = Body(...)):\n \"\"\"\n \"Create a new author\"\n\n - Args:\n author (Author): Author = Body(...)\n\n - Returns:\n The author object\n \"\"\"\n return author\n\n\n# Show an author\n@app.get(\n path=\"/author/{id_author}\",\n response_model=AuthorOut,\n status_code=status.HTTP_200_OK,\n summary=\"Show an author\",\n tags=[\"Author\"]\n)\ndef show_an_author():\n pass\n\n\n# Show all authors\n@app.get(\n path=\"/authors\",\n response_model=List[AuthorOut],\n status_code=status.HTTP_200_OK,\n summary=\"Show all authors\",\n tags=[\"Author\"]\n)\ndef show_all_authors():\n pass\n\n\n# Delete an author\n@app.delete(\n path=\"/author/{id_author}/delete\",\n response_model=AuthorOut,\n status_code=status.HTTP_200_OK,\n summary=\"Delete an author\",\n tags=[\"Author\"]\n)\ndef delete_an_author():\n pass\n\n\n# Update an author\n@app.put(\n path=\"/author/{id_author}/update\",\n response_model=AuthorOut,\n status_code=status.HTTP_200_OK,\n summary=\"Update an author\",\n tags=[\"Author\"]\n)\ndef update_an_author():\n pass\n","repo_name":"luisqpra/FastApiBooks","sub_path":"pass_main.py","file_name":"pass_main.py","file_ext":"py","file_size_in_byte":7584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74875972232","text":"class trie:\n def __init__(self, val):\n self.val = val\n self.children = {}# val -> node\n self.order = []\n \nclass Solution:\n \n def helper(self, sub_ans, cur_word, head):\n if len(sub_ans) == 3:\n return\n for e in head.order:\n if e == chr(ord(\"a\")-1):\n sub_ans.append(cur_word)\n else:\n self.helper(sub_ans, cur_word+e, head.children[e])\n \n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n #create a trie to store the product name\n #for each input, return the corresponding words\n head = trie(\"\")\n for name in products:\n cur = head\n for e in name:\n if e not in cur.children:\n cur.children[e] = trie(e)\n cur.order.append(e)\n index = len(cur.order)-1\n while index>0 and ord(cur.order[index-1]) > ord(cur.order[index]):\n cur.order[index-1], cur.order[index] = cur.order[index], cur.order[index-1]\n index -= 1\n cur = cur.children[e]\n cur.order = [chr(ord(\"a\")-1)] + cur.order\n ans = []\n\n for i, e in enumerate(searchWord):\n if e in head.children:\n cur_word = searchWord[:i+1]\n sub_ans = []\n self.helper(sub_ans, cur_word, head.children[e])\n ans.append(sub_ans)\n head = head.children[e]\n else:\n for _ in range(i, len(searchWord)):\n ans.append([])\n break\n return ans\n","repo_name":"ksharma67/LeetCode-NeetCode-All","sub_path":"Binary Search/1268. Search Suggestions System.py","file_name":"1268. Search Suggestions System.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13397526705","text":"import os\nimport pandas as pd\nfrom django.http import FileResponse\nimport psycopg2\n\n\ndef index(request):\n DATABASE_URL = os.environ['DATABASE_URL']\n conn = psycopg2.connect(DATABASE_URL)\n cur = conn.cursor()\n cur.execute(\"select date,flightdate,departure,arrival,price from prices;\")\n allEntries = cur.fetchall()\n df = pd.DataFrame(allEntries)\n df.to_excel(\n 'file.xlsx',\n index=False,\n header=['Date', 'Flight Date', 'Departure', 'Arrival', 'Price (BRL)']\n )\n return FileResponse(\n open('file.xlsx', 'rb'),\n as_attachment=True,\n filename='prices.xlsx'\n )\n","repo_name":"vcalasans/air-ticket-crawler","sub_path":"views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"70258460233","text":"#/sur/bin/python\n#-*- coding:utf-8 -*-\n\nimport sys\n\nanno_file = sys.argv[1]\n\nname = sys.argv[2] #需要绘图的样本名称\ngene = sys.argv[3] #需要绘图的基因名称\n\n'''{'name2': [], 'name3': [], 'name1': []}\n'''\ndict_name = {}\nlist_name = [] #存放样本名称\nwith open(name,\"r\") as name_file:\n for n in name_file:\n n = n.strip()\n list_name.append(n)\n dict_name[n] = []\n\n\n'''{'gene1': {'name2': [], 'name3': [], 'name1': []}, 'gene2': {'name2': [], 'name3': [], 'name1': []}, 'gene3': {'name2': [], 'name3': [], 'name1': []}}\n'''\ndict_all = {}\nwith open(gene, \"r\") as gene_file:\n for g in gene_file:\n g = g.strip()\n dict_all[g] = dict_name\n\n\nwith open(anno_file, \"r\") as infile:\n header = infile.readline().strip()\n head = header.split(\"\\t\")\n GeneName = head.index(\"GeneName\")\n ExonicFunc = head.index(\"ExonicFunc\")\n FORMAT = head.index(\"FORMAT\")\n Ori_REF = head.index(\"Ori_REF\")\n for line in infile:\n line = line.strip()\n lline = line.split(\"\\t\") #分割一行\n #print(lline)\n gene_n = lline[GeneName] #该行的基因名\n #print(gene_n)\n labels = lline[ExonicFunc] #\n for n in range(FORMAT+1, Ori_REF ):\n #print(n)\n if lline[n] == \".\":\n #print(head[n])\n dict_all[gene_n][head[n]].append(\"NA\")\n print(dict_all.keys())\n \n elif lline[n] != \".\" :\n dict_all[gene_n][head[n]].append(labels)\n #dict_all[gene_n][head[n]] = list(set(dict_all[gene_n][head[n]]))\n else:\n break\n #print(dict_all)\n #break\n\n#print(dict_all)\n\n#print(dict_all[\"RAD9A\"]) \nwith open(sys.argv[4], \"w\") as outfile:\n for k,v in dict_all.items():\n outfile.write(\"%s\\t\" % k)\n for name in list_name:\n outfile.write(\"%s\\t\" % dict_all[k][name])\n outfile.write(\"\\n\")\n \n\n#print(dict_all)\n","repo_name":"lvmt/R_releated_Code","sub_path":"landscape/file_mod.py","file_name":"file_mod.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4218415490","text":"import argparse\nimport os\nfrom autoencoder import Autoencoder, soft_relu, matrix_root, normalize\nfrom data_processing import load_data_memory, DATA_PATHS\nfrom bitarray import bitarray\nimport pickle as pkl\nimport numpy as np\nimport json\n\ndef decode_random(ae_path:str,\n random_data_path:str,\n meta_path:str,\n decoded_save_path:str\n ):\n b = Autoencoder(from_saved=True,path=ae_path)\n\n with open(random_data_path,\"rb\") as f:\n data = pkl.load(f)\n\n with open(meta_path,\"rb\") as f:\n mean_b,cov_b = pkl.load(f)\n\n data = normalize(data,(mean_b, cov_b),inverse=True)\n\n decoded = b.decoder.predict(data)\n decoded = np.array(list(map(lambda x: 0 if x <.5 else 1, decoded.flatten()))).reshape(decoded.shape)\n decoded_ba = [bitarray(list(x)) for x in decoded]\n with open(decoded_save_path,\"wb\") as f:\n pkl.dump(decoded_ba,f)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-cf\", type=str, default=\"config.json\", help=\"configuration file path\")\n args = parser.parse_args()\n\n config = json.load(open(args.cf))\n os.chdir(args.cf.rstrip(\".json\"))\n decode_random(config[\"autoencoder\"][\"save_path_b\"],\n config[\"linking\"][\"random_data_path\"],\n config[\"encoder\"][\"path_meta_b\"],\n config[\"linking\"][\"decoded_data_path\"])\n","repo_name":"vicolinho/pprl_autoencoder","sub_path":"src/encode_scripts/b_encoding_mapper.py","file_name":"b_encoding_mapper.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"31528812840","text":"from DSPlogging import log\n#import pytest\nimport unittest\nimport asyncio\nimport os\n\nfrom fastapi.testclient import TestClient\nfrom fastapi import FastAPI, APIRouter\n\nfrom pydantic import BaseModel, Field\nfrom typing import Optional, Union, NewType, Tuple, List, Dict, DefaultDict\n\nclass TestLogWrapper01General(unittest.TestCase):\n \"\"\"Test cases for decorated general/async functions\n \"\"\"\n \n def setUp(self):\n \"\"\"Set up for every test in this class. Test for repeating initialization to same log file (under 'a' mode).\n \"\"\"\n self.file = os.path.basename(__file__) \n self.log = log(logPath=self.logPath)\n\n def tearDown(self):\n \"\"\"Tear down for every test in this class. Nothing to do.\n \"\"\"\n pass\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Set up for all test in this class. Generating class scope log instance and class scope log file (under 'w' mode).\n \"\"\"\n cls.logPath = 'general_error.log'\n cls.file = os.path.basename(__file__) \n cls.log = log(logPath=cls.logPath)\n cls.skipChar = 24 # to skip datetime of records in log file\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"Tear down for all test in this class. Remove shared log file for every test in this class.\n \"\"\"\n os.remove(cls.logPath)\n\n def test01_class_scope_normal1(self):\n @self.log.errlog(self.file)\n def inner_scope_normal1():\n \"\"\" this function won't cause any error being logged used to test log.headLines\n \"\"\"\n x = 0\n y = x + 1\n\n inner_scope_normal1()\n answer = self.log.headLines\n content = self.log.readLog(skipLine=0, skipChar=0)\n self.assertEqual(content, answer)\n\n def test02_class_scope_normal2(self):\n @self.log.errlog(self.file)\n def inner_scope_normal2():\n \"\"\"It won't cause any error being logged. Testing for log.headLines\n \"\"\"\n with open(f'./{self.file}', 'r') as rf:\n rf.read()\n\n inner_scope_normal2()\n answer = self.log.headLines\n content = self.log.readLog(skipLine=0, skipChar=0)\n self.assertEqual(content, answer)\n\n def test03_class_scope_error1(self):\n @self.log.errlog(self.file)\n def inner_scope_error1():\n \"\"\"It will cause NameError: name 'x' is not defined. Testing for skipLine default value of log.readLog() and logging function\n \"\"\"\n y = x + 1\n\n inner_scope_error1()\n answer = f\"|{self.log.logger.name} |ERROR |@{self.file}/inner_scope_error1: name 'x' is not defined\\n\"\n content = self.log.readLog(skipChar=self.skipChar)\n self.assertEqual(content, answer)\n\n def test04_class_scope_error2(self):\n @self.log.errlog(self.file) \n def inner_scope_error2():\n \"\"\"It will cause division by zero error. Testing for skipLine default value of log.readLog() and logging function\n \"\"\"\n # this function cause NameError: name 'x' is not defined\n y = 3/0\n\n inner_scope_error2()\n answer = f\"|{self.log.logger.name} |ERROR |@{self.file}/inner_scope_error2: division by zero\\n\"\n content = self.log.readLog(skipLine=self.log.nHeadLines+1, skipChar=self.skipChar)\n self.assertEqual(content, answer)\n\n def test05_class_scope_error3(self):\n @self.log.errlog(self.file)\n def inner_scope_error3():\n \"\"\"It will cause file not exist error. Testing for skipLine default value of log.readLog() and logging function\n \"\"\"\n # this function cause NameError: name 'x' is not defined\n with open('file not exist', 'r') as rf:\n rf.read()\n \n inner_scope_error3()\n answer = f\"|{self.log.logger.name} |ERROR |@{self.file}/inner_scope_error3: [Errno 2] No such file or directory: 'file not exist'\\n\"\n content = self.log.readLog(skipLine=self.log.nHeadLines+2, skipChar=self.skipChar)\n self.assertEqual(content, answer)\n\n def test06_class_scope_async_normal1(self):\n import requests\n\n @self.log.errlog(self.file)\n async def inner_scope_async_normal1():\n loop = asyncio.get_event_loop()\n future = loop.run_in_executor(None, requests.get, 'https://www.google.com')\n response = await future\n return response\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(inner_scope_async_normal1())\n answer = f\"|{self.log.logger.name} |ERROR |@{self.file}/inner_scope_error1: name 'x' is not defined\\n\" + \\\n f\"|{self.log.logger.name} |ERROR |@{self.file}/inner_scope_error2: division by zero\\n\" + \\\n f\"|{self.log.logger.name} |ERROR |@{self.file}/inner_scope_error3: [Errno 2] No such file or directory: 'file not exist'\\n\"\n content = self.log.readLog(skipChar=self.skipChar)\n self.assertEqual(content, answer)\n\n def test07_class_scope_async_error1(self):\n import requests\n\n @self.log.errlog(self.file)\n async def inner_scope_async_error1():\n \"\"\"It will cause 404 Client Error. Testing for logging on async function\n \"\"\"\n loop = asyncio.get_event_loop()\n future = loop.run_in_executor(None, requests.get, 'http://www.google.com/nopage')\n response = await future\n response.raise_for_status()\n return response\n \n loop = asyncio.get_event_loop()\n loop.run_until_complete(inner_scope_async_error1())\n answer = f\"|{self.log.logger.name} |ERROR |@{self.file}/inner_scope_async_error1: 404 Client Error: Not Found for url: http://www.google.com/nopage\\n\"\n content = self.log.readLog(skipLine=self.log.nHeadLines+3, skipChar=self.skipChar)\n self.assertEqual(content, answer)\n\n\nclass TestLogWrapper02FastAPI(unittest.TestCase):\n \"\"\"Test cases for decorated FastAPI functions\n \"\"\"\n import json\n\n class Json1(BaseModel):\n id: Union[int, None]\n name: str\n config: Union[Dict, None]\n\n def setUp(self):\n \"\"\"Set up for every test in this class. Test for repeating initialization to same log file (under 'a' mode).\n \"\"\"\n self.file = os.path.basename(__file__) \n self.log = log(logPath=self.logPath)\n self.skipChar = 24 # to skip datetime of records in log file\n\n def tearDown(self):\n \"\"\"Tear down for every test in this class. Nothing to do.\n \"\"\"\n pass\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Set up for all test in this class. Generating class scope log instance and class scope log file (under 'w' mode).\n \"\"\" \n cls.logPath = 'fast_api.log'\n cls.file = os.path.basename(__file__) \n cls.log = log(logPath=cls.logPath)\n cls.skipChar = 24 # to skip datetime of records in log file\n\n cls.app = FastAPI()\n\n @staticmethod\n @cls.app.post(\"/test/echo\", response_model=cls.Json1)\n @cls.log.errlog(cls.file)\n async def echo(request: cls.Json1):\n \"\"\"A naive POST api which is able to receive request with json. It will cause customed exception. Testing for logging async FastAPI fucntion\n\n :param request: api request\n :raises Exception: IllegalAccessError is a customed exception\n :return: received json\n \"\"\"\n id, name, config = request.id, request.name, request.config\n if name == 'root': \n raise Exception(\"IllegalAccessError\", \"'root' access is unauthorized.\")\n return {'id':id, 'name':name, 'config':config}\n\n cls.client = TestClient(cls.app)\n \n @classmethod\n def tearDownClass(cls):\n \"\"\"Tear down for all test in this class. Remove shared log file for every test in this class.\n \"\"\"\n os.remove(cls.logPath)\n\n def test01_fastapi_echo_normal1(self):\n \"\"\"It won't cause any error being logged. Testing for FastAPI inside class scope\n \"\"\"\n import json\n answer = {\"id\": 1234, \"name\": \"Johndoe John\", \"config\": {\"verbose\":True, \"level\":3}}\n response = self.client.post(\"/test/echo\", json=answer)\n self.assertEqual(response.json(), answer)\n \n def test02_fastapi_echo(self):\n \"\"\"It will cause customed exception: IllegalAccessError. Testing for FastAPI inside class scope\n \"\"\"\n import json\n answer = {\"id\": 0, \"name\": \"root\", \"config\": {\"verbose\":True, \"level\":3}}\n response = self.client.post(\"/test/echo\", json=answer)\n answer = f\"|{self.log.logger.name} |ERROR |@{self.file}/echo: ('IllegalAccessError', \\\"'root' access is unauthorized.\\\")\\n\"\n content = self.log.readLog(skipChar=self.skipChar)\n self.assertEqual(content, answer)\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"dspim/DSPutility","sub_path":"dsputility/log/test_log.py","file_name":"test_log.py","file_ext":"py","file_size_in_byte":8997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"12447800685","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nfrom requests import RequestException, TooManyRedirects\nfrom six.moves.urllib import parse\n\nfrom school_api.check_code import CHECK_CODE\nfrom school_api.client.api.base import BaseSchoolApi\nfrom school_api.client.api.utils import get_alert_tip, get_view_state_from_html\nfrom school_api.exceptions import IdentityException, CheckCodeException, LoginException, \\\n OtherException\nfrom school_api.utils import to_binary, to_text\n\n\nclass Login(BaseSchoolApi):\n ''' 登录模块 '''\n\n def get_login(self, school, **kwargs):\n ''' 登录入口 与 异常处理 '''\n args = (school.login_url, school.exist_verify)\n try:\n res = self._get_api(*args, **kwargs)\n except OtherException as reqe:\n raise LoginException(self.school_code, to_text(str(reqe)))\n\n except RequestException:\n if school.proxies and not self.user.proxy_state:\n # 使用内网代理\n proxy_session = self._switch_proxy()\n if proxy_session:\n # 存在内网代理会话\n return True\n try:\n res = self._get_api(*args, **kwargs)\n except RequestException:\n raise LoginException(self.school_code, '教务系统异常,切用代理登录失败')\n else:\n\n if self.user.proxy_state:\n raise LoginException(self.school_code, '教务系统异常,使用代理登录失败')\n else:\n raise LoginException(self.school_code, '教务系统外网异常')\n\n # 处理登录结果\n try:\n self._handle_login_result(res)\n except CheckCodeException:\n try:\n # 验证码错误时,再次登录\n res = self._get_api(*args, **kwargs)\n except RequestException:\n raise LoginException(self.school_code, '教务系统请求异常')\n else:\n self._handle_login_result(res)\n\n return True\n\n def _handle_login_result(self, res):\n ''' 处理页面弹框信息 '''\n if res is True:\n # 登录成功\n return\n tip = get_alert_tip(res.text)\n if tip:\n if tip == '验证码不正确!!':\n raise CheckCodeException(self.school_code, tip)\n raise IdentityException(self.school_code, tip)\n raise LoginException(self.school_code, '教务系统请求异常')\n\n def _get_login_payload(self, login_url, **kwargs):\n ''' 获取登录页面的 请求参数'''\n try:\n kwargs['timeout'] = 3\n res = self._get(login_url, **kwargs)\n except TooManyRedirects as reqe:\n res = self._get(reqe.response.headers[\"Location\"], **kwargs)\n\n except RequestException:\n # 首次请求可能出现 Connection aborted\n res = self._get(login_url, **kwargs)\n\n url_info = res.url.split(login_url)[0].split('/(')\n if len(url_info) == 2:\n self._update_url_token('/(' + url_info[1])\n\n view_state = get_view_state_from_html(res.text)\n return {'__VIEWSTATE': view_state}\n\n def _get_api(self, login_url, exist_verify, **kwargs):\n # 登录请求\n code = ''\n login_types = ['学生', '教师', '部门']\n login_payload = self._get_login_payload(login_url, **kwargs)\n if exist_verify:\n res = self._get('/CheckCode.aspx')\n if res.content[:7] != to_binary('GIF89aH'):\n raise CheckCodeException(self.school_code, \"验证码获取失败\")\n code = CHECK_CODE.verify(res.content)\n\n account = self.user.account.encode('gb2312')\n payload = {\n 'txtUserName': account,\n 'TextBox1': account,\n 'TextBox2': self.user.password,\n 'TextBox3': code,\n 'txtSecretCode': code,\n 'RadioButtonList1': login_types[self.user.user_type].encode('gb2312'),\n 'Button1': ' 登 录 '.encode('gb2312')\n }\n payload.update(login_payload)\n try:\n res = self._post(login_url, data=payload, **kwargs)\n except TooManyRedirects:\n # 302跳转 代表登录成功\n return True\n return res\n\n def check_session(self):\n \"\"\" 检查登陆会话是否有效 \"\"\"\n account = parse.quote(self.user.account.encode('gb2312'))\n try:\n self._head(self.school_url['HOME_URL'] + account)\n except RequestException:\n return False\n\n return True\n","repo_name":"dairoot/school-api","sub_path":"school_api/client/api/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","stars":199,"dataset":"github-code","pt":"27"} +{"seq_id":"21206373620","text":"import numpy as np\n\ndef freq_to_prob(freq):\n if (freq < 0):\n return round((-freq) / (1 - freq), 5)\n else:\n return round(1 / (1 + freq), 5)\n\n\nimport scipy.stats\ndef mean_confidence_interval(data, confidence=0.95):\n a = 1.0 * np.array(data)\n n = len(a)\n m, se = np.mean(a), scipy.stats.sem(a)\n h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)\n return m, m-h, m+h\n\n\ndef reject_outliers(data, m = 2.):\n d = np.abs(data - np.median(data))\n mdev = np.median(d)\n s = d/mdev if mdev else 0.\n return data[s int:\n # height, area\n heights.append(0)\n N = len(heights)\n ans = 0\n mins = []\n for j in range(N):\n i = j\n while mins and mins[-1][0] > heights[j]:\n h, i = mins.pop()\n ans = max(ans, (j-i)*h)\n mins.append((heights[j], i))\n return ans\n\nheights = [1]\ns = Solution()\nans = s.largestRectangleArea(heights)\nprint(ans)","repo_name":"liooil/leetcode","sub_path":"largest-rectangle-in-histogram.py","file_name":"largest-rectangle-in-histogram.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"26842560967","text":"import sys\nimport os\nfrom datetime import timedelta, datetime\n\nfrom kivy.core.audio import Sound\nfrom kivy.core.window import window_sdl2 # noqa\nimport pytest\n\n\ndef start(animation, widget):\n animation.dispatch('on_start', widget)\n\n for proprety_name, value in animation.animated_properties.items():\n setattr(widget, proprety_name, value)\n animation.dispatch('on_complete', widget)\n\n\n@staticmethod\ndef load(name):\n return Sound()\n\n\n@pytest.fixture(autouse=True)\ndef patch_env(request, monkeypatch):\n test_name = request._pyfuncitem.name\n try:\n import settings\n\n reload(settings)\n from configure import configure\n settings.KIVY_GRAPHICS_WIDTH = 1\n settings.KIVY_GRAPHICS_HEIGHT = 1\n configure()\n settings.DATABASE_NAME = \"test-%s-db.sqlite3\" % test_name\n settings.DATABASE_PATH = os.path.join(settings.PROJECT_DIR, settings.DATABASE_NAME)\n\n # try to import module overriding\n module_overrides = getattr(request.module, \"SETTINGS_OVERRIDE\", {})\n for option_name, option_value in module_overrides.items():\n setattr(settings, option_name, option_value)\n\n from kivy.config import ConfigParser\n ConfigParser._named_configs = {}\n\n # apply overriding from the function itself\n if hasattr(request.function, 'settings'):\n function_overrides = request.function.settings\n for option_name, option_value in function_overrides.items():\n setattr(settings, option_name, option_value)\n sys.modules[\"settings\"] = settings\n\n monkeypatch.setattr('kivy.animation.Animation.start', start)\n monkeypatch.setattr('kivy.clock.Clock.create_trigger', lambda c, t=None: c)\n monkeypatch.setattr('kivy.core.audio.SoundLoader.load', load)\n\n def fin():\n from managers.database import database_manager\n\n if database_manager._connection:\n database_manager._connection.close()\n database_manager._connection = None\n if os.path.exists(\"test-%s-db.sqlite3\" % test_name):\n os.remove(\"test-%s-db.sqlite3\" % test_name)\n\n if os.path.exists(\"kognitivo-test-%s.ini\" % test_name):\n os.remove(\"kognitivo-test-%s.ini\" % test_name)\n\n request.addfinalizer(fin)\n except:\n if os.path.exists(\"test-%s-db.sqlite3\" % test_name):\n os.remove(\"test-%s-db.sqlite3\" % test_name)\n\n if os.path.exists(\"kognitivo-test-%s.ini\" % test_name):\n os.remove(\"kognitivo-test-%s.ini\" % test_name)\n raise\n\n\n@pytest.fixture(params=[\n \"en\", \"es\", \"ru\", \"de\", \"ua\"\n], ids=[\n \"en_lang\", \"es_lang\", \"ru_lang\", \"de_lang\", \"ua_lang\"\n])\ndef app(request):\n from main import KognitivoApp\n\n test_name = request._pyfuncitem.name\n application = KognitivoApp(name=\"kognitivo-test-%s\" % test_name)\n application.lang = request.param\n from utils import _\n _.switch_lang(application.lang)\n\n def fin():\n if os.path.exists(application.storage.filename):\n os.remove(application.storage.filename)\n\n request.addfinalizer(fin)\n return application\n\n\n@pytest.fixture\ndef running_app(monkeypatch, app):\n @staticmethod\n def get_running_app(**kwargs):\n if not app.manager:\n from root_manager import RootManager\n\n app.manager = RootManager()\n from kivy.base import EventLoop\n\n window = EventLoop.window\n app._app_window = window\n window.children = []\n\n if not app.config:\n app.load_config()\n return app\n\n monkeypatch.setattr('kivy.base.runTouchApp', lambda: None)\n\n monkeypatch.setattr('kivy.app.App.get_running_app', get_running_app)\n from kivy.app import App\n\n return App.get_running_app()\n\n\n@pytest.fixture\ndef root_manager(running_app):\n return running_app.manager\n\n\n@pytest.fixture\ndef navigation(running_app):\n return running_app.root\n\n\n@pytest.fixture\ndef empty_data(monkeypatch):\n monkeypatch.setattr('managers.database.database_manager.day_percents', lambda *args, **kwargs: {})\n monkeypatch.setattr('managers.database.database_manager.hour_percents', lambda *args, **kwargs: {})\n monkeypatch.setattr('managers.database.database_manager.recent_percents', lambda *args, **kwargs: {})\n\n\n@pytest.fixture\ndef not_empty_data(monkeypatch):\n monkeypatch.setattr('managers.database.database_manager.hour_percents',\n lambda *args, **kwargs: {key: 1.0 for key in range(24)})\n monkeypatch.setattr('managers.database.database_manager.day_percents',\n lambda *args, **kwargs: {key: 1.0 for key in range(7)})\n monkeypatch.setattr('managers.database.database_manager.recent_percents',\n lambda *args, **kwargs: {(datetime.now() - timedelta(days=key)).date(): 1.0 for key in\n range(7)})\n\n\n@pytest.fixture\ndef webbrowser(mocker):\n mock_webbrowser_open = mocker.patch('webbrowser.open')\n return mock_webbrowser_open\n\n\n@pytest.fixture\ndef tracker(mocker, running_app):\n mocker.spy(running_app.tracker, 'send_event')\n return running_app.tracker\n\n\n@pytest.fixture\ndef google_client(mocker, running_app):\n mocker.spy(running_app.google_client, 'increment_achievement')\n mocker.spy(running_app.google_client, 'unlock_achievement')\n mocker.spy(running_app.google_client, 'submit_score')\n return running_app.google_client\n\n\n@pytest.fixture\ndef vibrator(mocker):\n from managers.vibration import vibration_manager\n mocker.spy(vibration_manager, 'vibrate')\n return vibration_manager\n\n\n@pytest.fixture\ndef storage(running_app):\n return running_app.storage\n\n\n@pytest.fixture\ndef billing(running_app, mocker):\n running_app.initialize_billing()\n mocker.spy(running_app.billing, 'buy')\n return running_app.billing\n\n\n@pytest.fixture\ndef billing_no_connection(running_app, monkeypatch):\n running_app.initialize_billing()\n monkeypatch.setattr('billing.BillingService.get_available_items', lambda *args, **kwargs: [])\n return running_app.billing\n","repo_name":"thorin-schiffer/kognitivo","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":6149,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"27"} +{"seq_id":"27845113389","text":"\nimport yolo\nimport file\nimport numpy as np\nimport node\nfrom colorManager import ColorManager\nfrom AiManager import AiManager\nfrom SegmentManager import SegmentManager\n\nclass Command:\n yolo = yolo.Yolo()\n sm = SegmentManager()\n cm = ColorManager()\n am = AiManager()\n\n def __init__(self, conn):\n self._node = node.Node(conn)\n self.cmd_list = {'ISEND': self.get_Image,'IGET': self.send_Image,\n 'DFILE': self.del_File, 'CDATA': self.color_data,\n 'RCDATA': self.recommend_data,\n 'FDATA' : self.color_filtering}\n\n def encodeD(self, data):\n data = b'@' + data.encode() + b'#'\n return data\n\n def reset(self):\n self._node.save()\n\n def setFile(self, f):\n self.f = f\n\n def predict(self):\n self.sm.set_img(self.f)\n self.sm.get_output()\n #self.yolo.set_img(self.f.getName())\n #self.yolo.get_output()\n\n def getCmd(self):\n print()\n print(\"Command resived - {0}\".format(self._node.command()))\n return self._node.command()\n\n def do(self):\n self.reset()\n cmd = self.getCmd()\n return self.cmd_list[cmd]()\n\n #세션 유지 : True, 세션 제거시 : False\n def get_Image(self):\n if self._node.pars_filedata() == None:\n raise NameError(\"NoDataError\")\n\n self.f.getFile(self._node.pars_filedata())\n print(\"reciving Success - {0}\".format(self.f.addr))\n self.predict()\n print(\"sending File : {0} - {1}\".format(self.f.exname, self.f.addr))\n self._node.sendIMG(self.f.strFile())\n print(\"sending Success - {0}\".format(self.f.addr))\n return True\n \n \n def send_Image(self):\n print(\"sending File : {0} - {1}\".format(self.f.exname, self.f.addr))\n self._node.sendIMG(self.f.strFile())\n print(\"sending Success - {0}\".format(self.f.addr))\n return True\n \n\n def del_File(self):\n print(\"delete File : {0} - {1}\".format(self.f.name ,self.f.addr))\n self.f.delFile()\n return False\n\n def color_data(self):\n print(\"predicting color data - {0}\".format(self.f.addr))\n cdata = self._node.getData()\n cdata = [int(i) for i in cdata[0].split(\",\")]\n s = self.cm.getName(cdata)['name']\n print(\"color data : {0} - {1}\".format(s, cdata))\n s = self.encodeD('N: ' + s)\n self._node.sendData(s)\n return True\n\n def recommend_data(self):\n print(\"recommend color data - {0}\".format(self.f.addr))\n cdata = self._node.getData()\n s = self.am.do(cdata)\n print(\"color datas : {0} - {1}\".format(s, cdata))\n s = self.encodeD(s)\n self._node.sendData(s)\n return True\n\n def color_filtering(self):\n print(\"filtering img as color - {0}\".format(self.f.addr))\n data = self._node.getData()\n self.sm.file = self.f\n self.sm.setXY(data[:2])\n self.sm.setColor(data[2:])\n self.sm.do()\n print(\"sending File : {0} - {1}\".format(self.f.afname, self.f.addr))\n self._node.sendData(self.f.strAfterFile())\n print(\"sending Success - {0}\".format(self.f.addr))\n return True\n","repo_name":"Roharui/Coloring_Server","sub_path":"command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20630436545","text":"# 112. Path Sum\n\nclass TreeNode:\n\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nfrom typing import Optional\nimport collections\n\nclass Solution:\n\n # recursion\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n return self.backtrack(root, targetSum)\n \n\n def backtrack(self, root, target):\n if not root.left and not root.right:\n if root.val == target:\n return True\n return False\n \n if root.left:\n if (self.backtrack(root.left, target - root.val)):\n return True\n \n if root.right:\n if (self.backtrack(root.right, target - root.val)):\n return True\n \n return False\n\n\n '''\n time complexity:\n o(n)\n \n space complexity:\n o(n)\n '''\n\n # iteration\n def hasPathSum_iteration(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n \n queue = collections.deque()\n pathsum = collections.deque()\n \n queue.append(root)\n pathsum.append(root.val)\n\n while queue:\n cur = queue.popleft()\n cursum = pathsum.popleft()\n if not cur.left and not cur.right and cursum == targetSum:\n return True\n if cur.left:\n queue.append(cur.left)\n pathsum.append(cursum + cur.left.val)\n if cur.right:\n queue.append(cur.right)\n pathsum.append(cursum + cur.right.val)\n \n return False\n \n '''\n time complexity:\n o(n)\n \n space complexity:\n o(n)\n '''\n","repo_name":"Jiashu2000/LeetCode","sub_path":"Oct27/PathSum.py","file_name":"PathSum.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37445015735","text":"# Authors: CommPy contributors\n# License: BSD 3-Clause\n\n\"\"\"\n==================================================\nSequences (:mod:`commpy.sequences`)\n==================================================\n\n.. autosummary::\n :toctree: generated/\n\n pnsequence -- PN Sequence Generator.\n zcsequence -- Zadoff-Chu (ZC) Sequence Generator.\n\n\"\"\"\n__all__ = ['pnsequence', 'zcsequence']\n\nfrom numpy import empty, exp, pi, arange, int8, fromiter, sum\n\ndef pnsequence(pn_order, pn_seed, pn_mask, seq_length):\n \"\"\"\n Generate a PN (Pseudo-Noise) sequence using a Linear Feedback Shift Register (LFSR).\n Seed and mask are ordered so that:\n - seed[-1] will be the first output\n - the new bit computed as :math:`sum(shift_register & mask) % 2` is inserted in shift[0]\n\n Parameters\n ----------\n pn_order : int\n Number of delay elements used in the LFSR.\n\n pn_seed : iterable providing 0's and 1's\n Seed for the initialization of the LFSR delay elements.\n The length of this string must be equal to 'pn_order'.\n\n pn_mask : iterable providing 0's and 1's\n Mask representing which delay elements contribute to the feedback\n in the LFSR. The length of this string must be equal to 'pn_order'.\n\n seq_length : int\n Length of the PN sequence to be generated. Usually (2^pn_order - 1)\n\n Returns\n -------\n pnseq : 1D ndarray of ints\n PN sequence generated.\n\n Raises\n ------\n ValueError\n If the pn_order is equal to the length of the strings pn_seed and pn_mask.\n\n \"\"\"\n # Check if pn_order is equal to the length of the strings 'pn_seed' and 'pn_mask'\n if len(pn_seed) != pn_order:\n raise ValueError('pn_seed has not the same length as pn_order')\n if len(pn_mask) != pn_order:\n raise ValueError('pn_mask has not the same length as pn_order')\n\n # Pre-allocate memory for output\n pnseq = empty(seq_length, int8)\n\n # Convert input as array\n sr = fromiter(pn_seed, int8, pn_order)\n mask = fromiter(pn_mask, int8, pn_order)\n\n for i in range(seq_length):\n pnseq[i] = sr[-1]\n new_bit = sum(sr & mask) % 2\n sr[1:] = sr[:-1]\n sr[0] = new_bit\n\n return pnseq\n\ndef zcsequence(u, seq_length):\n \"\"\"\n Generate a Zadoff-Chu (ZC) sequence.\n\n Parameters\n ----------\n u : int\n Root index of the the ZC sequence.\n\n seq_length : int\n Length of the sequence to be generated. Usually a prime number.\n\n Returns\n -------\n zcseq : 1D ndarray of complex floats\n ZC sequence generated.\n \"\"\"\n zcseq = exp((-1j * pi * u * arange(seq_length) * (arange(seq_length)+1)) / seq_length)\n\n return zcseq\n","repo_name":"Martech123/CommPy","sub_path":"commpy/sequences.py","file_name":"sequences.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"71329012552","text":"import matplotlib.pyplot as plt\nimport random\n\nfrom modu.template import ChangedTemperaturesOnMyBirthday\nfrom modu.template.basic_hist import highest_temperature\n\ndef sorted_random_arr()-> []:\n arr = []\n [arr.append(random.randint(1, 1000)) for i in range(13)]\n return arr\n\ndef show_boxplot(arr:[]):\n plt.boxplot(arr)\n plt.show()\n\ndef show_boxplot_month(month:str):\n plt.boxplot(highest_temperature(month))\n plt.show()\ndef show_boxplot_all_month():\n birth = ChangedTemperaturesOnMyBirthday()\n birth.read_data()\n data = birth.data\n\n #monthls =[]\n #month1 = []\n month = [[],[],[],[],[],[],[],[],[],[],[],[]]\n #for row in data:\n # if row[-1] !='':\n # month[int(row[0].split('-')[1])-1].append(float(row[-1]))\n #print(len(month))\n #print(month)\n #[[month1[int(row[0].split('-')[1]) - 1].append(float(row[-1])) for row in data if row[-1] != ''] for i in range(12)]\n #month = []\n [[month[int(row[0].split('-')[1])-1].append(float(row[-1])) for row in data if row[-1] !=''] for i in range(12)]\n #print(month[4])\n #print(len(month))\n return month\n\ndef show_boxplot_per_date(month : str):\n birth = ChangedTemperaturesOnMyBirthday()\n birth.read_data()\n data = birth.data\n day =[]\n [day.append([]) for i in range(31)]\n [day[int(i[0].split('-')[2])-1].append(float(i[-1])) for i in data if i[-1] !='' if i[0].split('-')[1]==month]\n plt.style.use('ggplot')\n plt.figure(figsize=(10,5),dpi=300)\n plt.boxplot(day, showfliers=False)\n plt.show()\n\nif __name__ == '__main__':\n #highest_temperature_boxplot(arr=highest_temperature(month='08'))\n #show_boxplot_all_month()\n #show_boxplot(show_boxplot_all_month())\n show_boxplot_per_date('08')","repo_name":"YoonHyunSung/Bitcamp_Python","sub_path":"modu/template/basic_boxplot.py","file_name":"basic_boxplot.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"44689963224","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import PassiveAggressiveRegressor\n\ndata = pd.read_csv('C:/Users/A5327/Desktop/New folder/Python/Python/project/Instagram data.csv', encoding = 'latin1')\nprint(data.head())\n\n\n# In[9]:\n\n\ndata.isnull().sum() #contains no nul values\ndata=data.dropna() #drop null values if any\n\n\n# In[10]:\n\n\ndata.info()\n\n\n# In[17]:\n\n\nplt.figure(figsize=(10,8))\nplt.style.use('fivethirtyeight')\nplt.title('Distribution of Impression from home')\nsns.distplot(data['From Home'])\nplt.show\n\n\n# In[19]:\n\n\nplt.figure(figsize=(10,8))\nplt.style.use('fivethirtyeight')\nplt.title('Distribution of Impression from Hastags')\nsns.distplot(data['From Hashtags'])\nplt.show\n\n\n# In[21]:\n\n\nplt.figure(figsize=(10,8))\n#plt.style.use('fivethirtyeight')\nplt.title('Distribution of Impression from Explore')\nsns.distplot(data['From Explore'])\nplt.show\n\n\n# In[30]:\n\n\nhome=data[\"From Home\"].sum()\nhashtags=data[\"From Hashtags\"].sum()\nexplore=data[\"From Explore\"].sum()\nother=data[\"From Other\"].sum()\n\nlabels=['From Home','From Hashtags','From Explore','Other']\nvalues= [home, hashtags, explore, other]\n\nfig=px.pie(data, values=values, names=labels, title='pie chart')\nfig.show()\n\n\n# In[34]:\n\n\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\n\n# In[45]:\n\n\ntext=\" \".join(i for i in data.Caption)\nstopwords=set(STOPWORDS)\nwordcloud= WordCloud(stopwords = stopwords ,background_color=\"white\").generate(text)\nplt.style.use('classic')\nplt.figure(figsize=(10,8))\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis('off')\nplt.show()\n\n\n# In[46]:\n\n\ntext=\" \".join(i for i in data.Hashtags)\nstopwords=set(STOPWORDS)\nwordcloud= WordCloud(stopwords = stopwords ,background_color=\"white\").generate(text)\nplt.style.use('classic')\nplt.figure(figsize=(10,8))\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis('off')\nplt.show()\n\n","repo_name":"akshitaKESHARWANI/Instagram-Reach-Analysis-using-Python","sub_path":"Instagram Reach Analysis using Python.py","file_name":"Instagram Reach Analysis using Python.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28775070594","text":"from ooo.oenv.env_const import UNO_NONE\nfrom .drop_target_drag_event import DropTargetDragEvent as DropTargetDragEvent_d60612e7\nfrom ...uno.x_interface import XInterface as XInterface_8f010a43\nfrom .x_drop_target_drag_context import XDropTargetDragContext as XDropTargetDragContext_10221422\nimport typing\nfrom ..data_flavor import DataFlavor as DataFlavor_ffd30deb\n\n\nclass DropTargetDragEnterEvent(DropTargetDragEvent_d60612e7):\n \"\"\"\n Struct Class\n\n The DropTargetDragEnterEvent is delivered from the drop target to the currently registered drop target listeners whenever the logical cursor associated with a Drag and Drop operation enters the visible geometry of a window associated with a drop target.\n \n It contains the com.sun.star.datatransfer.DataFlavor types supported by the transferable object of the current Drag and Drop operation.\n\n See Also:\n `API DropTargetDragEnterEvent `_\n \"\"\"\n __ooo_ns__: str = 'com.sun.star.datatransfer.dnd'\n __ooo_full_ns__: str = 'com.sun.star.datatransfer.dnd.DropTargetDragEnterEvent'\n __ooo_type_name__: str = 'struct'\n typeName: str = 'com.sun.star.datatransfer.dnd.DropTargetDragEnterEvent'\n \"\"\"Literal Constant ``com.sun.star.datatransfer.dnd.DropTargetDragEnterEvent``\"\"\"\n\n def __init__(self, Source: typing.Optional[XInterface_8f010a43] = None, Dummy: typing.Optional[int] = 0, Context: typing.Optional[XDropTargetDragContext_10221422] = None, DropAction: typing.Optional[int] = 0, LocationX: typing.Optional[int] = 0, LocationY: typing.Optional[int] = 0, SourceActions: typing.Optional[int] = 0, SupportedDataFlavors: typing.Optional[typing.Tuple[DataFlavor_ffd30deb, ...]] = ()) -> None:\n \"\"\"\n Constructor\n\n Arguments:\n Source (XInterface, optional): Source value.\n Dummy (int, optional): Dummy value.\n Context (XDropTargetDragContext, optional): Context value.\n DropAction (int, optional): DropAction value.\n LocationX (int, optional): LocationX value.\n LocationY (int, optional): LocationY value.\n SourceActions (int, optional): SourceActions value.\n SupportedDataFlavors (typing.Tuple[DataFlavor, ...], optional): SupportedDataFlavors value.\n \"\"\"\n\n if isinstance(Source, DropTargetDragEnterEvent):\n oth: DropTargetDragEnterEvent = Source\n self.Source = oth.Source\n self.Dummy = oth.Dummy\n self.Context = oth.Context\n self.DropAction = oth.DropAction\n self.LocationX = oth.LocationX\n self.LocationY = oth.LocationY\n self.SourceActions = oth.SourceActions\n self.SupportedDataFlavors = oth.SupportedDataFlavors\n return\n\n kargs = {\n \"Source\": Source,\n \"Dummy\": Dummy,\n \"Context\": Context,\n \"DropAction\": DropAction,\n \"LocationX\": LocationX,\n \"LocationY\": LocationY,\n \"SourceActions\": SourceActions,\n \"SupportedDataFlavors\": SupportedDataFlavors,\n }\n self._init(**kargs)\n\n def _init(self, **kwargs) -> None:\n self._supported_data_flavors = kwargs[\"SupportedDataFlavors\"]\n inst_keys = ('SupportedDataFlavors',)\n kargs = kwargs.copy()\n for key in inst_keys:\n del kargs[key]\n super()._init(**kargs)\n\n\n @property\n def SupportedDataFlavors(self) -> typing.Tuple[DataFlavor_ffd30deb, ...]:\n \"\"\"\n A sequence of supported com.sun.star.datatransfer.DataFlavor types.\n \"\"\"\n return self._supported_data_flavors\n\n @SupportedDataFlavors.setter\n def SupportedDataFlavors(self, value: typing.Tuple[DataFlavor_ffd30deb, ...]) -> None:\n self._supported_data_flavors = value\n\n\n__all__ = ['DropTargetDragEnterEvent']\n","repo_name":"Amourspirit/python-ooouno","sub_path":"ooo/lo/datatransfer/dnd/drop_target_drag_enter_event.py","file_name":"drop_target_drag_enter_event.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"9882269756","text":"from collections import deque\r\n\r\n\r\nclass BinaryTree:\r\n\r\n\tdef __init__(self, rootObj):\r\n\t\tself.key = rootObj\r\n\t\tself.leftChild = None\r\n\t\tself.rightChild = None\r\n\r\n\tdef insertLeft(self, newNode):\r\n\t\tif self.leftChild == None:\r\n\t\t\tself.leftChild = BinaryTree(newNode)\r\n\t\telse:\r\n\t\t\tt = BinaryTree(newNode)\r\n\t\t\tt.leftChild = self.leftChild\r\n\t\t\tself.leftChild = t\r\n\r\n\tdef insertRight(self, newNode):\r\n\t\tif self.rightChild == None:\r\n\t\t\tself.rightChild = BinaryTree(newNode)\r\n\t\telse:\r\n\t\t\tt = BinaryTree(newNode)\r\n\t\t\tt.rightChild = self.rightChild\r\n\t\t\tself.rightChild = t\r\n\r\n\tdef get_leaves(self):\r\n\t\tif self.leftChild == None and self.rightChild == None:\r\n\t\t\treturn [self.key]\r\n\t\tif self.leftChild == None:\r\n\t\t\treturn self.rightChild.get_leaves()\r\n\t\tif self.rightChild == None:\r\n\t\t\treturn self.leftChild.get_leaves()\r\n\t\treturn self.leftChild.get_leaves() + self.rightChild.get_leaves()\r\n\r\n\tdef preorder(self):\r\n\t\t'''\r\n\t\tRoot -> Left -> Right\r\n\t\t'''\r\n\t\tif self.leftChild == None and self.rightChild == None:\r\n\t\t\treturn [self.key]\r\n\t\tif self.leftChild == None:\r\n\t\t\treturn [self.key] + self.rightChild.preorder()\r\n\t\tif self.rightChild == None:\r\n\t\t\treturn [self.key] + self.leftChild.preorder()\r\n\t\treturn [self.key] + self.leftChild.preorder() + self.rightChild.preorder()\r\n\r\n\tdef inorder(self):\r\n\t\t'''\r\n\t\tLeft -> Root -> Right\r\n\t\t'''\r\n\t\tif self.leftChild == None and self.rightChild == None:\r\n\t\t\treturn [self.key]\r\n\t\tif self.leftChild == None:\r\n\t\t\treturn [self.key] + self.rightChild.inorder()\r\n\t\tif self.rightChild == None:\r\n\t\t\treturn self.leftChild.inorder() + [self.key]\r\n\t\treturn self.leftChild.inorder() + [self.key] + self.rightChild.inorder()\r\n\r\n\tdef postorder(self):\r\n\t\t'''\r\n\t\tLeft -> Right -> Root\r\n\t\t'''\r\n\t\tif self.leftChild == None and self.rightChild == None:\r\n\t\t\treturn [self.key]\r\n\t\tif self.leftChild == None:\r\n\t\t\treturn self.rightChild.postorder() + [self.key]\r\n\t\tif self.rightChild == None:\r\n\t\t\treturn self.leftChild.postorder() + [self.key]\r\n\t\treturn self.leftChild.postorder() + self.rightChild.postorder() + [self.key]\r\n\r\n\r\n\tdef level_order(self):\r\n\t\t'''\r\n\t\tBreadth first search traversal\r\n\t\t'''\r\n\t\tq = deque()\r\n\t\tq.appendleft(self)\r\n\t\twhile len(q) != 0:\r\n\t\t\ttmp = q.pop()\r\n\t\t\tif tmp.leftChild != None:\r\n\t\t\t\tq.appendleft(tmp.leftChild)\r\n\t\t\tif tmp.rightChild != None:\r\n\t\t\t\tq.appendleft(tmp.rightChild)\r\n\t\t\tprint(tmp.key)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\timport argparse\r\n\tCLI=argparse.ArgumentParser()\r\n\tCLI.add_argument(\r\n\t\t\"--list\",\r\n\t\tnargs=\"*\",\r\n\t\ttype=int,\r\n\t\tdefault=[3,2,1]\r\n\t)\r\n\targs = CLI.parse_args()\r\n\r\n\tt = BinaryTree(1)\r\n\tt.insertRight(3)\r\n\tt.insertLeft(4)\r\n\tt.insertLeft(2)\r\n\tt.leftChild.insertRight(5)\r\n\tprint(t.get_leaves())\r\n\tprint(t.inorder())\r\n\tprint(t.postorder())\r\n\tprint(t.preorder())\r\n\tprint(t.level_order())\r\n\r\n","repo_name":"Alshadex/AlgorithmNotes","sub_path":"DataStructures/Trees/BinaryTree.py","file_name":"BinaryTree.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17456088501","text":"#!/usr/bin/python3\n\"\"\"Defines the HBnB console.\"\"\"\nimport cmd\nimport shlex\nfrom models.base_model import BaseModel\nfrom models import storage\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\" defines the HolbertonBnB command \"\"\"\n\n prompt = '(hbnb) '\n validate_classes = ['BaseModel']\n\n def default(self, val):\n \"\"\" default state for the cmd \"\"\"\n\n val_list = val.split('.')\n\n class_name = val_list[0]\n\n the_commend = val_list[1].split('(')\n\n the_method = the_commend[0]\n\n dict = {\n 'update': self.do_update,\n 'destroy': self.do_destroy,\n 'all': self.do_all,\n 'show': self.do_show,\n 'count': self.do_count\n }\n\n if the_method in dict.keys():\n return dict[the_method]('{} {}'.format(class_name, ''))\n\n print('*** error syntax: {} ***'.format(val))\n return False\n\n def do_count(self, val):\n \"\"\" count class retrieve the number\n of instances of a class\n\n \"\"\"\n objs = storage.all()\n\n the_commend = shlex.split(val)\n\n new_class = the_commend[0]\n\n c = 0\n\n if the_commend:\n if new_class in self.validate_classes:\n for obj in objs.values():\n if obj.__class__.__name__ == new_class:\n c += 1\n print(c)\n else:\n print('** unknown class name **')\n else:\n print('** class name missing **')\n\n def emptyline(self):\n \"\"\" do nothing \"\"\"\n pass\n\n def do_quit(self, val):\n \"\"\" return True to exit the program \"\"\"\n\n return True\n\n def do_EOF(self, val):\n \"\"\" return True to exit the program \"\"\"\n\n print()\n return True\n\n def do_create(self, val):\n \"\"\" creates a new instance of BaseModel \"\"\"\n\n the_commend = shlex.split(val)\n\n if len(the_commend) == 0:\n print('** class name missing **')\n elif the_commend[0] not in self.validate_classes:\n print(\"** class doesn't exist **\")\n else:\n new_user = BaseModel()\n new_user.save()\n print(new_user.id)\n\n def do_show(self, val):\n \"\"\"\n prints the string representation of an\n instance based on the class name and id\n \"\"\"\n the_commend = shlex.split(val)\n\n if len(the_commend) == 0:\n print('** class name missing **')\n elif the_commend[0] not in self.validate_classes:\n print(\"** class doesn't exist **\")\n elif len(the_commend) < 2:\n print('** instance id missing **')\n else:\n objs = storage.all()\n\n key = '{}.{}'.format(the_commend[0], the_commend[1])\n if key in objs:\n print(objs[key])\n else:\n print('** no instance found **')\n\n def do_destroy(self, val):\n \"\"\"\n deletes an instance based on the class name and\n id and save the change in json file.\n \"\"\"\n the_commend = shlex.split(val)\n\n if len(the_commend) == 0:\n print('** class name missing **')\n elif the_commend[0] not in self.validate_classes:\n print(\"** class doesn't exist **\")\n elif len(the_commend) < 2:\n print('** instance id missing **')\n else:\n objs = storage.all()\n\n key = '{}.{}'.format(the_commend[0], the_commend[1])\n if key in objs:\n del objs[key]\n storage.save()\n else:\n print('** no instance found **')\n\n def do_all(self, val):\n \"\"\"\n displays all str representation of all instances\n based or not on the class name\n \"\"\"\n objs = storage.all()\n\n the_commend = shlex.split(val)\n\n if len(the_commend) == 0:\n for k, v in objs.items():\n print(str(v))\n elif the_commend[0] not in self.validate_classes:\n print(\"** class doesn't exist **\")\n else:\n for k, v in objs.items():\n if k.split('.')[0] == the_commend[0]:\n print(str(v))\n\n def do_update(self, val):\n \"\"\"\n updates an instance based on the class name and\n id by adding or updating attribute and save the\n change in jsin file.\n \"\"\"\n the_commend = shlex.split(val)\n\n if len(the_commend) == 0:\n print('** class name missing **')\n elif the_commend[0] not in self.validate_classes:\n print(\"** class doesn't exist **\")\n elif len(the_commend) < 2:\n print('** instance id missing **')\n else:\n objs = storage.all()\n\n key = '{}.{}'.format(the_commend[0], the_commend[1])\n\n if key not in objs:\n print('** no instance found **')\n elif len(the_commend) < 3:\n print('** attribute name missing **')\n elif len(the_commend) < 4:\n print('** value missing **')\n else:\n obj = objs[key]\n\n name = the_commend[2]\n value = the_commend[3]\n\n try:\n value = eval(value)\n except Exception:\n pass\n\n setattr(obj, name, value)\n\n obj.save()\n\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","repo_name":"simoIdbrahim/AirBnB_clone","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":5432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"15553015713","text":"from matplotlib.pyplot import axis\nimport numpy as np\nfrom numpy.core.fromnumeric import argmax\nimport torch\nimport time\nfrom .strategy import Strategy\n# *Core-Set方法,使用K-Center-greedy,每次迭代贪婪找k个最远\n# *思路:时间换空间,贪婪寻找,不怕计算量过大;余弦距离与欧氏距离成正比\nclass Core_Sets(Strategy):\n def __init__(self, X, Y, idxs_lb, net, handler, args, device):\n super(Core_Sets, self).__init__(X, Y, idxs_lb, net, handler, args, device)\n def query(self, n):\n log_run = self.args.log_run\n T = self.args.timer\n n_pool = self.n_pool #样本总数\n T.start()\n time_start = time.time()\n\n lb_flag = self.idxs_lb.copy()\n # -1. 获取所有样本在模型下的隐藏层作为特征\n embedding = self.get_embedding(self.X, self.Y)\n embedding = embedding.numpy() #~ size为60000*1\n \n tmp_time = T.stop()\n log_run.logger.debug('获取隐藏层特征部分结束,用时 {:.4f} s'.format(tmp_time))\n T.start()\n\n # -2. 迭代n次,每次贪婪寻找当前距离最远的点\n for count in range(n):\n T.start()\n dist_min = 0\n can_idx = 0\n # -得到当前的标记集和未标记集\n idxs_lbd_tmp = np.arange(n_pool)[lb_flag] #-当前的已标注样本集的对应下标\n idxs_unlbd_tmp = np.arange(n_pool)[~lb_flag]\n n_lbd_tmp = len(idxs_lbd_tmp)\n n_unlbd_tmp = len(idxs_unlbd_tmp)\n vec_lbd = embedding[idxs_lbd_tmp]\n\n for idx_unlbd_i in idxs_unlbd_tmp:\n # -a.计算一个未标记样本距离当前标记集的距离\n # ~算该点到所有点距离,最小的一个为其到集合的距离\n embed_i = embedding[idx_unlbd_i]\n vec_unlbd_i = np.array([embed_i]*n_lbd_tmp)\n # dist = numpy.sqrt(numpy.sum(numpy.square(vec1 - vec2)))欧式距离计算公式\n # torch.pairwise_distance\n dist_vec_i = np.sum(np.square(vec_lbd - vec_unlbd_i), axis=1)\n dist_idx_i = dist_vec_i.min()\n # -b.更新最远距离,添加当前idx到候选\n if dist_idx_i > dist_min:\n dist_min = dist_idx_i\n can_idx = idx_unlbd_i\n \n # -一次取多个,假设一共取100次\n # cau_times = 100\n # count_unlbd = 0\n # cau_once = int(n_unlbd_tmp/cau_times)\n # size_hide = embedding.shape[1]\n # vec_lbd = vec_lbd.reshape(1, n_lbd_tmp, size_hide)\n # for i in range(cau_times):\n # idx_start = i*cau_once\n # if i < cau_times-1 :\n # cau_use_tmp = cau_once\n # else:\n # cau_use_tmp = n_unlbd_tmp - count_unlbd\n # idx_end = idx_start + cau_use_tmp\n # count_unlbd += cau_use_tmp\n # # -取得这些距离,作为一个矩阵\n # idxs_use_tmp = idxs_unlbd_tmp[idx_start:idx_end]\n # embed_unlbd_tmp = embedding[idxs_use_tmp]#~这些是当次计算用到的隐变量\n\n # # -计算距离 \n # embed_unlbd_tmp = embed_unlbd_tmp.reshape(cau_use_tmp, 1, size_hide)#~方便计算,数组进行扩充\n # vec_unlbd_i = np.repeat(embed_unlbd_tmp, n_lbd_tmp, axis=1)\n # vec_lbd_i = np.repeat(vec_lbd, cau_use_tmp, axis=0)\n # dist_vec_i = np.sum(np.square(vec_unlbd_i - vec_lbd_i), axis=2)\n # dist_vec_i_fin = np.min(dist_vec_i, axis=1)\n # #~这一批中选取最大值\n # count_candidate = np.argmax(dist_vec_i_fin)\n # dist_idx_i = np.max(dist_vec_i_fin)\n # idx_unlbd_i = idxs_unlbd_tmp[count_candidate]\n # # -更新最远距离,添加当前idx到候选\n # if dist_idx_i > dist_min:\n # dist_min = dist_idx_i\n # can_idx = idx_unlbd_i\n # -迭代后得到一个最远值\n lb_flag[can_idx] = True\n tmp_time = T.stop()\n print('第{}次筛选结束,对应下标为:{},用时 {:.2f} s'.format(count+1, can_idx, tmp_time))\n\n tmp_time = T.stop()\n time_use = time.time() - time_start\n log_run.logger.debug('贪婪得到K-Center覆盖部分结束,用时 {:.4f} s;本次采样总共用时{:.4f} s'.format(tmp_time, time_use))\n T.start()\n \n return np.arange(self.n_pool)[(self.idxs_lb ^ lb_flag)]","repo_name":"WangGossip/DAL","sub_path":"query_strategies/core_sets.py","file_name":"core_sets.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34923721774","text":"#-*- coding:utf-8 -*-\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome()\n\n\n# 有些弹出对话框窗,我们可以通过判断是否为当前窗口的方式进行操作。\n\n#获得当前窗口\nnowhandle=driver.current_window_handle\n\n#打开弹窗\ndriver.find_element_by_name(\"xxx\").click()\n\n#获得所有窗口\nallhandles=driver.window_handles\nfor handle in allhandles:\n if handle!=nowhandle: #比较当前窗口是不是原先的窗口\n driver.switch_to_window(handle) #获得当前窗口的句柄\n driver.find_element_by_class_name(\"xxxx\").click() #在当前窗口操作\n\n#回到原先的窗口\ndriver.switch_to_window(nowhandle)\n\n\n# 这里只是操作窗口的代码片段, 提供一个思路, 能否完成我们想要的结果, 还需要我们\n# 通过实例去验证。","repo_name":"Yangle16/Spider","sub_path":"selenium/17dilog.py","file_name":"17dilog.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22233934788","text":"##\n# Determine whether or not a string entered by the user is an integer?\n#\n\n## Determine if a string contains a valid representation of an integer\n# @param s the string to check\n# @return True ifs represent and integer. False otherwise\n#\ndef isInteger (s):\n # Remove white space from the beginning and end of the string\n s = s.strip()\n\n # Determine if the remaining characters from a valid integer\n if (s[0] == \"+\" or s[0] == \"-\") and s[1:].isdigit():\n return True\n if s.isdigit():\n return True\n return False\n\nprint(\"Is `1121s` an integer\", isInteger(\"1121s\"))\n\n\n","repo_name":"aaron-goshine/python-scratch-pad","sub_path":"workout/is_string_int.py","file_name":"is_string_int.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28897917338","text":"from accounts.models import UserProfile\r\nfrom django.contrib.auth.models import User\r\nfrom .serializers import *\r\nfrom django.http import Http404\r\nfrom rest_framework.views import APIView\r\nfrom rest_framework.response import Response\r\nfrom rest_framework import status\r\nfrom rest_framework.authentication import TokenAuthentication\r\nfrom rest_framework.permissions import IsAuthenticated\r\nfrom django.core.paginator import Paginator\r\nfrom django.db.models import Q\r\nfrom accounts.models import AnonymousSession\r\n\r\n\r\nclass VerifyAuth(APIView):\r\n authentication_classes=(TokenAuthentication,)\r\n permission_classes=(IsAuthenticated,)\r\n\r\n def get(self,request,format=None):\r\n return Response({'is_authenticated': True}, status=200)\r\n\r\nclass UserProfileApi(APIView):\r\n # authentication_classes = [SessionAuthentication, BasicAuthentication]\r\n # permission_classes = [IsAuthenticated]\r\n\r\n def pagination_response(self,users,serializer,users_length):\r\n response={\r\n 'pages':users.paginator.num_pages,\r\n 'result':serializer.data,\r\n \"length\":users_length\r\n }\r\n try:\r\n response['previous']=users.previous_page_number()\r\n except:\r\n pass\r\n try:\r\n response['next']=users.next_page_number()\r\n except:\r\n pass\r\n return response\r\n\r\n\r\n def get(self,request,format=None):\r\n page = request.GET.get('page')\r\n filters={}\r\n q = Q()\r\n\r\n if request.GET.get(\"pays\") and request.GET.get(\"pays\")!=\"0\" :\r\n filters['commune__wilaya__pays__id']=request.GET.get(\"pays\")\r\n\r\n if request.GET.get(\"wilaya\") and request.GET.get(\"wilaya\")!=\"0\" :\r\n filters['commune__wilaya__id']=request.GET.get(\"wilaya\")\r\n\r\n if request.GET.get(\"commune\") and request.GET.get(\"commune\")!=\"0\" :\r\n filters['commune__id']=request.GET.get(\"commune\")\r\n\r\n\r\n if request.GET.get('spec'):\r\n filters[\"specialite\"]=request.GET.get('spec')\r\n\r\n if request.GET.get(\"commercial\") and request.GET.get(\"commercial\")!=\"\" :\r\n q |= Q(user__first_name__icontains=request.GET.get(\"commercial\"))\r\n q |= Q(user__last_name__icontains=request.GET.get(\"commercial\"))\r\n\r\n\r\n\r\n users_list=UserProfile.objects.filter(**filters).order_by(\"-user__first_name\")\r\n\r\n if q:\r\n users_list=users_list.filter(q)\r\n\r\n paginator = Paginator(users_list, 1)\r\n users=paginator.get_page(page)\r\n\r\n serializer=UserProfileSerializer(users,many=True)\r\n\r\n return Response(self.pagination_response(users,serializer,len(users_list)), status=200)\r\n\r\n\r\n\r\nclass SpecialiteApi(APIView):\r\n def get(self,request,format=None):\r\n content = [\r\n {'id':1,'name':'Généraliste'},\r\n {'id':2,'name':'Diabetologue'},\r\n {'id':3,'name':'Neurologue'},\r\n {'id':4,'name':'Psychologue'},\r\n {'id':5,'name':'Gynécologue'},\r\n {'id':6,'name':'Rumathologue'},\r\n {'id':7,'name':'Allergologue'},\r\n {'id':8,'name':'Phtisio'},\r\n {'id':9,'name':'Cardiologue'},\r\n {'id':10,'name':'Urologue'},\r\n {'id':11,'name':'Hematologue'},\r\n {'id':12,'name':'Orthopedie'},\r\n {'id':13,'name':'Nutritionist'},\r\n {'id':14,'name':'Dermatologue'},\r\n {'id':15,'name':'Pharmacie'},\r\n {'id':16,'name':'Grossiste'},\r\n ]\r\n return Response(content)\r\n\r\n\r\n\r\nclass AccountApi(APIView):\r\n def get(self,request,format=None):\r\n return Response({'id':request.user.id,'name':request.user.username})\r\n\r\n\r\nclass SessionApi(APIView):\r\n def get(self,request,format=None):\r\n sess=AnonymousSession()\r\n ses=sess.set()\r\n sess.save()\r\n print(\"**************** session api *******************\")\r\n print(ses)\r\n return Response({'session':ses})\r\n # sessi=sess.save()\r\n # print(\"**************** session *******************\")\r\n # print(sessi)\r\n # return Response({'session':sessi.session})\r\n\r\n def post(self,request,format=None):\r\n try:\r\n print(f\"*************post sessions verify {request.data.get('session')}\")\r\n session=AnonymousSession.objects.get(session=request.data.get('session'))\r\n return Response({'is_valid':True})\r\n except:\r\n return Response({'is_valid':False})\r\n\r\nclass EditProfileApi(APIView):\r\n authentication_classes=(TokenAuthentication,)\r\n permission_classes=(IsAuthenticated,)\r\n def get(self,request,format=None):\r\n # serializer=EditProfileSerializer(request.user.userprofile)\r\n serializer=EditProfileSerializer(UserProfile.objects.get(user=request.user))\r\n return Response(serializer.data)\r\n\r\n def post(self,request,format=None):\r\n user_serializer = UserSerializer(request.user, data=request.data)\r\n if user_serializer.is_valid():\r\n user_serializer.save()\r\n else:\r\n return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n serializer = EditProfileSerializer(request.user.userprofile, data=request.data)\r\n # serializer = EditProfileSerializer(UserProfile.objects.get(id=1), data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data)\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\nclass RegisterApi(APIView):\r\n def post(self,request,format=None):\r\n user_serializer = UserSerializer(data=request.data)\r\n if user_serializer.is_valid():\r\n user=user_serializer.save()\r\n else:\r\n print(\"****************************************************\")\r\n print(user_serializer.errors)\r\n return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n profile = EditProfileSerializer(user.userprofile, data=request.data)\r\n if profile.is_valid():\r\n profile.save()\r\n user.set_password(request.data.get(\"password\"))\r\n user.save()\r\n return Response(profile.data)\r\n else:\r\n user.delete()\r\n print(\"****************************************************\")\r\n print(profile.errors)\r\n return Response(profile.errors, status=status.HTTP_400_BAD_REQUEST)\r\n","repo_name":"BoughezalaMohamedAimen/market","sub_path":"accounts/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19672850346","text":"#!/usr/bin/python3\n\nimport sys\nimport os\nimport re\n\nplugin_template = \"\"\"\nimport { Plugin } from \"./plugin\";\n\nexport class %s extends Plugin {\n constructor() {\n super(%s); // Replace number with action ID. List of IDs found here: https://salbot.ch/admin/idlist\n }\n\n register(data: any): boolean {\n /**\n * Code to register your plugin\n * Add interval ID to this.registered_intervals using the arrays push method.\n * Add listeneras to this.registered_listeners using the arrays push method.\n * For listeners you need to push an object like so {on: string, function: EventListenerOrEventListenerObject}\n * \n * Return true is plugin was registered successfully false otherwise\n */\n return true;\n }\n\n // Optionally you can override the revoke method\n // revoke(): boolean {\n // return true;\n // }\n}\n\"\"\"\n\ncommand_template = \"\"\"\nimport { Command } from \"./command\";\n\nexport class %s extends Command {\n constructor() {\n super(%s); // Replace number with action ID. List of IDs found here: https://salbot.ch/admin/idlist\n }\n\n execute(data: any) {\n // Code for the action\n }\n}\n\"\"\"\n\ndef main():\n if (len(sys.argv) != 3 and len(sys.argv) != 4) or (sys.argv[1] != \"plugin\" and sys.argv[1] != \"command\"):\n print(\"Wrong usage of generate command. Please use \\\"npm run generate plugin/command [name] [id]\\\"\")\n return\n \n name = re.sub(r'(? None\n \"\"\" Include the registering info related to @implement.\n\n IMPORTANT! Updates self.kwargs[CORE_ELEMENT_KEY].\n\n :param kwargs: Keyword arguments received from call.\n :return: None\n \"\"\"\n if __debug__:\n logger.debug(\"Configuring @implement core element.\")\n\n # Resolve @implement specific parameters\n if 'sourceClass' in self.kwargs:\n another_class = self.kwargs['sourceClass']\n self.kwargs['source_class'] = self.kwargs.pop('sourceClass')\n else:\n another_class = self.kwargs['source_class']\n another_method = self.kwargs['method']\n ce_signature = '.'.join((another_class, another_method))\n impl_type = \"METHOD\"\n # impl_args = [another_class, another_method] # set by @task\n\n if CORE_ELEMENT_KEY in kwargs:\n # Core element has already been created in a higher level decorator\n # (e.g. @constraint)\n kwargs[CORE_ELEMENT_KEY].set_ce_signature(ce_signature)\n kwargs[CORE_ELEMENT_KEY].set_impl_type(impl_type)\n # @task sets the implementation type arguments\n # kwargs[CORE_ELEMENT_KEY].set_impl_type_args(impl_args)\n else:\n # @implement is in the top of the decorators stack.\n # Instantiate a new core element object, update it and include\n # it into kwarg\n core_element = CE()\n core_element.set_ce_signature(ce_signature)\n core_element.set_impl_type(impl_type)\n # @task sets the implementation type arguments\n # core_element.set_impl_type_args(impl_args)\n kwargs[CORE_ELEMENT_KEY] = core_element\n\n # Set as configured\n self.core_element_configured = True\n\n\n# ########################################################################### #\n# ################## IMPLEMENT DECORATOR ALTERNATIVE NAME ################### #\n# ########################################################################### #\n\nimplement = Implement\nIMPLEMENT = Implement\n","repo_name":"curiousTauseef/compss","sub_path":"compss/programming_model/bindings/python/src/pycompss/api/implement.py","file_name":"implement.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"25113324141","text":"from oil.plugins import Plugin\n\n\nclass TotalUsersPlugin(Plugin):\n\n name = 'total_users'\n provider = 'aws'\n service = 'iam'\n\n requirements = {\n 'users': ['aws', 'iam', 'get_credential_report']\n }\n\n default_config = {\n 'total_users_severity_2_threshold': {\n 'name': 'Total Users Severity 2 Threshold',\n 'description': (\n 'Adjust threshold for number of users for a severity 2 finding'\n ),\n 'value_description': 'number of users',\n 'default': 1000,\n },\n 'total_users_severity_1_threshold': {\n 'name': 'Total Users Severity 1 Threshold',\n 'description': (\n 'Adjust threshold for number of users for a severity 1 finding'\n ),\n 'value_description': 'number of users',\n 'default': 500,\n },\n 'total_users_severity_2_message': {\n 'name': 'Total Users Severity 2 Message',\n 'description': (\n 'Change the message for a severity 2 finding'\n ),\n 'value_description': '{total_users}',\n 'default': 'There are {total_users} users for this account',\n },\n 'total_users_severity_1_message': {\n 'name': 'Total Users Severity 1 Message',\n 'description': (\n 'Change the message for a severity 1 finding'\n ),\n 'value_description': '{total_users}',\n 'default': 'There are {total_users} users for this account',\n },\n 'total_users_severity_0_message': {\n 'name': 'Total Users Severity 0 Message',\n 'description': (\n 'Change the message for a severity 0 finding'\n ),\n 'value_description': '{total_users}',\n 'default': 'There are {total_users} users for this account',\n },\n 'no_users_message': {\n 'name': 'No Users Message',\n 'description': (\n 'Change the message for no users for an account'\n ),\n 'value_description': (\n 'This should not be possible because of root account, but '\n 'it may come in handy later'\n ),\n 'default': 'There are no users for this account',\n },\n }\n\n\n def run(self, api_data):\n # Reset the results list for this plugin\n self.results = []\n\n requirements = self.collect_requirements(api_data)\n users = requirements['users']['aws-global']\n\n resource = 'None'\n region = 'aws-global'\n total_users = len(users)\n if not total_users:\n severity = 0\n message = self.config['no_users_message']\n elif total_users > self.config['total_users_severity_2_threshold']:\n severity = 2\n message = self.config['total_users_severity_2_message'].format(\n total_users=total_users,\n )\n elif total_users > self.config['total_users_severity_1_threshold']:\n severity = 1\n message = self.config['total_users_severity_1_message'].format(\n total_users=total_users,\n )\n else:\n severity = 0\n message = self.config['total_users_severity_0_message'].format(\n total_users=total_users,\n )\n\n self.results.append({\n 'resource': resource,\n 'region': region,\n 'severity': severity,\n 'message': message,\n })\n\n return self.results\n","repo_name":"coolfriends/oil","sub_path":"oil/plugins/aws/iam/total_users/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"27318976187","text":"from bs4 import BeautifulSoup\nimport requests\nimport os, shutil\n\n\ndef find_borders(groups):\n \"\"\"Get all + 1 tag is start\n last is end\"\"\"\n indices = [i for i, x in enumerate(groups) if x['value'] == 'All']\n return indices[1] + 1, indices[2]\n\ndef find_border_exam(groups):\n \"\"\"Get all + 1 tag is start\n next all